three.webgpu.nodes.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787
  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, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, RenderTarget, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, PerspectiveCamera, CubeUVReflectionMapping, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, Frustum, FrontSide, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NearestFilter, 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, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<string>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. id: geometry.id,
  133. attributes: this.getAttributesData( geometry.attributes ),
  134. indexVersion: geometry.index ? geometry.index.version : null,
  135. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  136. },
  137. worldMatrix: object.matrixWorld.clone()
  138. };
  139. if ( object.center ) {
  140. data.center = object.center.clone();
  141. }
  142. if ( object.morphTargetInfluences ) {
  143. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  144. }
  145. if ( renderObject.bundle !== null ) {
  146. data.version = renderObject.bundle.version;
  147. }
  148. if ( data.material.transmission > 0 ) {
  149. const { width, height } = renderObject.context;
  150. data.bufferWidth = width;
  151. data.bufferHeight = height;
  152. }
  153. this.renderObjects.set( renderObject, data );
  154. }
  155. return data;
  156. }
  157. /**
  158. * Returns an attribute data structure holding the attributes versions for
  159. * monitoring.
  160. *
  161. * @param {Object} attributes - The geometry attributes.
  162. * @return {Object} An object for monitoring the versions of attributes.
  163. */
  164. getAttributesData( attributes ) {
  165. const attributesData = {};
  166. for ( const name in attributes ) {
  167. const attribute = attributes[ name ];
  168. attributesData[ name ] = {
  169. version: attribute.version
  170. };
  171. }
  172. return attributesData;
  173. }
  174. /**
  175. * Returns `true` if the node builder's material uses
  176. * node properties.
  177. *
  178. * @param {NodeBuilder} builder - The current node builder.
  179. * @return {boolean} Whether the node builder's material uses node properties or not.
  180. */
  181. containsNode( builder ) {
  182. const material = builder.material;
  183. for ( const property in material ) {
  184. if ( material[ property ] && material[ property ].isNode )
  185. return true;
  186. }
  187. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  188. return true;
  189. return false;
  190. }
  191. /**
  192. * Returns a material data structure holding the material property values for
  193. * monitoring.
  194. *
  195. * @param {Material} material - The material.
  196. * @return {Object} An object for monitoring material properties.
  197. */
  198. getMaterialData( material ) {
  199. const data = {};
  200. for ( const property of this.refreshUniforms ) {
  201. const value = material[ property ];
  202. if ( value === null || value === undefined ) continue;
  203. if ( typeof value === 'object' && value.clone !== undefined ) {
  204. if ( value.isTexture === true ) {
  205. data[ property ] = { id: value.id, version: value.version };
  206. } else {
  207. data[ property ] = value.clone();
  208. }
  209. } else {
  210. data[ property ] = value;
  211. }
  212. }
  213. return data;
  214. }
  215. /**
  216. * Returns `true` if the given render object has not changed its state.
  217. *
  218. * @param {RenderObject} renderObject - The render object.
  219. * @return {boolean} Whether the given render object has changed its state or not.
  220. */
  221. equals( renderObject ) {
  222. const { object, material, geometry } = renderObject;
  223. const renderObjectData = this.getRenderObjectData( renderObject );
  224. // world matrix
  225. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  226. renderObjectData.worldMatrix.copy( object.matrixWorld );
  227. return false;
  228. }
  229. // material
  230. const materialData = renderObjectData.material;
  231. for ( const property in materialData ) {
  232. const value = materialData[ property ];
  233. const mtlValue = material[ property ];
  234. if ( value.equals !== undefined ) {
  235. if ( value.equals( mtlValue ) === false ) {
  236. value.copy( mtlValue );
  237. return false;
  238. }
  239. } else if ( mtlValue.isTexture === true ) {
  240. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  241. value.id = mtlValue.id;
  242. value.version = mtlValue.version;
  243. return false;
  244. }
  245. } else if ( value !== mtlValue ) {
  246. materialData[ property ] = mtlValue;
  247. return false;
  248. }
  249. }
  250. if ( materialData.transmission > 0 ) {
  251. const { width, height } = renderObject.context;
  252. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  253. renderObjectData.bufferWidth = width;
  254. renderObjectData.bufferHeight = height;
  255. return false;
  256. }
  257. }
  258. // geometry
  259. const storedGeometryData = renderObjectData.geometry;
  260. const attributes = geometry.attributes;
  261. const storedAttributes = storedGeometryData.attributes;
  262. const storedAttributeNames = Object.keys( storedAttributes );
  263. const currentAttributeNames = Object.keys( attributes );
  264. if ( storedGeometryData.id !== geometry.id ) {
  265. storedGeometryData.id = geometry.id;
  266. return false;
  267. }
  268. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  269. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  270. return false;
  271. }
  272. // compare each attribute
  273. for ( const name of storedAttributeNames ) {
  274. const storedAttributeData = storedAttributes[ name ];
  275. const attribute = attributes[ name ];
  276. if ( attribute === undefined ) {
  277. // attribute was removed
  278. delete storedAttributes[ name ];
  279. return false;
  280. }
  281. if ( storedAttributeData.version !== attribute.version ) {
  282. storedAttributeData.version = attribute.version;
  283. return false;
  284. }
  285. }
  286. // check index
  287. const index = geometry.index;
  288. const storedIndexVersion = storedGeometryData.indexVersion;
  289. const currentIndexVersion = index ? index.version : null;
  290. if ( storedIndexVersion !== currentIndexVersion ) {
  291. storedGeometryData.indexVersion = currentIndexVersion;
  292. return false;
  293. }
  294. // check drawRange
  295. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  296. storedGeometryData.drawRange.start = geometry.drawRange.start;
  297. storedGeometryData.drawRange.count = geometry.drawRange.count;
  298. return false;
  299. }
  300. // morph targets
  301. if ( renderObjectData.morphTargetInfluences ) {
  302. let morphChanged = false;
  303. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  304. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  305. morphChanged = true;
  306. }
  307. }
  308. if ( morphChanged ) return true;
  309. }
  310. // center
  311. if ( renderObjectData.center ) {
  312. if ( renderObjectData.center.equals( object.center ) === false ) {
  313. renderObjectData.center.copy( object.center );
  314. return true;
  315. }
  316. }
  317. // bundle
  318. if ( renderObject.bundle !== null ) {
  319. renderObjectData.version = renderObject.bundle.version;
  320. }
  321. return true;
  322. }
  323. /**
  324. * Checks if the given render object requires a refresh.
  325. *
  326. * @param {RenderObject} renderObject - The render object.
  327. * @param {NodeFrame} nodeFrame - The current node frame.
  328. * @return {boolean} Whether the given render object requires a refresh or not.
  329. */
  330. needsRefresh( renderObject, nodeFrame ) {
  331. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  332. return true;
  333. const { renderId } = nodeFrame;
  334. if ( this.renderId !== renderId ) {
  335. this.renderId = renderId;
  336. return true;
  337. }
  338. const isStatic = renderObject.object.static === true;
  339. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  340. if ( isStatic || isBundle )
  341. return false;
  342. const notEqual = this.equals( renderObject ) !== true;
  343. return notEqual;
  344. }
  345. }
  346. // 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} 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( /*uilder, 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 Node
  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. getNodeType( builder ) {
  2396. if ( this.nodeType === null ) {
  2397. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2398. }
  2399. return this.nodeType;
  2400. }
  2401. getElementType( builder ) {
  2402. return this.getNodeType( builder );
  2403. }
  2404. generate( builder ) {
  2405. const type = this.getNodeType( builder );
  2406. return builder.generateArray( type, this.count, this.values );
  2407. }
  2408. }
  2409. /**
  2410. * TSL function for creating an array node.
  2411. *
  2412. * @tsl
  2413. * @function
  2414. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2415. * or an array containing the default values (e.g., [ vec3() ]).
  2416. * @param {?number} [count] - Size of the array.
  2417. * @returns {ArrayNode}
  2418. */
  2419. const array = ( ...params ) => {
  2420. let node;
  2421. if ( params.length === 1 ) {
  2422. const values = params[ 0 ];
  2423. node = new ArrayNode( null, values.length, values );
  2424. } else {
  2425. const nodeType = params[ 0 ];
  2426. const count = params[ 1 ];
  2427. node = new ArrayNode( nodeType, count );
  2428. }
  2429. return nodeObject( node );
  2430. };
  2431. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2432. /**
  2433. * This node can be used to group single instances of {@link UniformNode}
  2434. * and manage them as a uniform buffer.
  2435. *
  2436. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2437. * will be used when defining the {@link UniformNode#groupNode} property.
  2438. *
  2439. * - `objectGroup`: Uniform buffer per object.
  2440. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2441. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2442. *
  2443. * @augments Node
  2444. */
  2445. class UniformGroupNode extends Node {
  2446. static get type() {
  2447. return 'UniformGroupNode';
  2448. }
  2449. /**
  2450. * Constructs a new uniform group node.
  2451. *
  2452. * @param {string} name - The name of the uniform group node.
  2453. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2454. * @param {number} [order=1] - Influences the internal sorting.
  2455. */
  2456. constructor( name, shared = false, order = 1 ) {
  2457. super( 'string' );
  2458. /**
  2459. * The name of the uniform group node.
  2460. *
  2461. * @type {string}
  2462. */
  2463. this.name = name;
  2464. /**
  2465. * Whether this uniform group node is shared or not.
  2466. *
  2467. * @type {boolean}
  2468. * @default false
  2469. */
  2470. this.shared = shared;
  2471. /**
  2472. * Influences the internal sorting.
  2473. * TODO: Add details when this property should be changed.
  2474. *
  2475. * @type {number}
  2476. * @default 1
  2477. */
  2478. this.order = order;
  2479. /**
  2480. * This flag can be used for type testing.
  2481. *
  2482. * @type {boolean}
  2483. * @readonly
  2484. * @default true
  2485. */
  2486. this.isUniformGroup = true;
  2487. }
  2488. serialize( data ) {
  2489. super.serialize( data );
  2490. data.name = this.name;
  2491. data.version = this.version;
  2492. data.shared = this.shared;
  2493. }
  2494. deserialize( data ) {
  2495. super.deserialize( data );
  2496. this.name = data.name;
  2497. this.version = data.version;
  2498. this.shared = data.shared;
  2499. }
  2500. }
  2501. /**
  2502. * TSL function for creating a uniform group node with the given name.
  2503. *
  2504. * @tsl
  2505. * @function
  2506. * @param {string} name - The name of the uniform group node.
  2507. * @returns {UniformGroupNode}
  2508. */
  2509. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2510. /**
  2511. * TSL function for creating a shared uniform group node with the given name and order.
  2512. *
  2513. * @tsl
  2514. * @function
  2515. * @param {string} name - The name of the uniform group node.
  2516. * @param {number} [order=0] - Influences the internal sorting.
  2517. * @returns {UniformGroupNode}
  2518. */
  2519. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2520. /**
  2521. * TSL object that represents a shared uniform group node which is updated once per frame.
  2522. *
  2523. * @tsl
  2524. * @type {UniformGroupNode}
  2525. */
  2526. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2527. /**
  2528. * TSL object that represents a shared uniform group node which is updated once per render.
  2529. *
  2530. * @tsl
  2531. * @type {UniformGroupNode}
  2532. */
  2533. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2534. /**
  2535. * TSL object that represents a uniform group node which is updated once per object.
  2536. *
  2537. * @tsl
  2538. * @type {UniformGroupNode}
  2539. */
  2540. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2541. /**
  2542. * Class for representing a uniform.
  2543. *
  2544. * @augments InputNode
  2545. */
  2546. class UniformNode extends InputNode {
  2547. static get type() {
  2548. return 'UniformNode';
  2549. }
  2550. /**
  2551. * Constructs a new uniform node.
  2552. *
  2553. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2554. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2555. */
  2556. constructor( value, nodeType = null ) {
  2557. super( value, nodeType );
  2558. /**
  2559. * This flag can be used for type testing.
  2560. *
  2561. * @type {boolean}
  2562. * @readonly
  2563. * @default true
  2564. */
  2565. this.isUniformNode = true;
  2566. /**
  2567. * The name or label of the uniform.
  2568. *
  2569. * @type {string}
  2570. * @default ''
  2571. */
  2572. this.name = '';
  2573. /**
  2574. * The uniform group of this uniform. By default, uniforms are
  2575. * managed per object but they might belong to a shared group
  2576. * which is updated per frame or render call.
  2577. *
  2578. * @type {UniformGroupNode}
  2579. */
  2580. this.groupNode = objectGroup;
  2581. }
  2582. /**
  2583. * Sets the {@link UniformNode#name} property.
  2584. *
  2585. * @param {string} name - The name of the uniform.
  2586. * @return {UniformNode} A reference to this node.
  2587. */
  2588. label( name ) {
  2589. this.name = name;
  2590. return this;
  2591. }
  2592. /**
  2593. * Sets the {@link UniformNode#groupNode} property.
  2594. *
  2595. * @param {UniformGroupNode} group - The uniform group.
  2596. * @return {UniformNode} A reference to this node.
  2597. */
  2598. setGroup( group ) {
  2599. this.groupNode = group;
  2600. return this;
  2601. }
  2602. /**
  2603. * Returns the {@link UniformNode#groupNode}.
  2604. *
  2605. * @return {UniformGroupNode} The uniform group.
  2606. */
  2607. getGroup() {
  2608. return this.groupNode;
  2609. }
  2610. /**
  2611. * By default, this method returns the result of {@link Node#getHash} but derived
  2612. * classes might overwrite this method with a different implementation.
  2613. *
  2614. * @param {NodeBuilder} builder - The current node builder.
  2615. * @return {string} The uniform hash.
  2616. */
  2617. getUniformHash( builder ) {
  2618. return this.getHash( builder );
  2619. }
  2620. onUpdate( callback, updateType ) {
  2621. const self = this.getSelf();
  2622. callback = callback.bind( self );
  2623. return super.onUpdate( ( frame ) => {
  2624. const value = callback( frame, self );
  2625. if ( value !== undefined ) {
  2626. this.value = value;
  2627. }
  2628. }, updateType );
  2629. }
  2630. generate( builder, output ) {
  2631. const type = this.getNodeType( builder );
  2632. const hash = this.getUniformHash( builder );
  2633. let sharedNode = builder.getNodeFromHash( hash );
  2634. if ( sharedNode === undefined ) {
  2635. builder.setHashNode( this, hash );
  2636. sharedNode = this;
  2637. }
  2638. const sharedNodeType = sharedNode.getInputType( builder );
  2639. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2640. const propertyName = builder.getPropertyName( nodeUniform );
  2641. if ( builder.context.label !== undefined ) delete builder.context.label;
  2642. return builder.format( propertyName, type, output );
  2643. }
  2644. }
  2645. /**
  2646. * TSL function for creating a uniform node.
  2647. *
  2648. * @tsl
  2649. * @function
  2650. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2651. * @param {?string} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2652. * @returns {UniformNode}
  2653. */
  2654. const uniform = ( arg1, arg2 ) => {
  2655. const nodeType = getConstNodeType( arg2 || arg1 );
  2656. // @TODO: get ConstNode from .traverse() in the future
  2657. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2658. return nodeObject( new UniformNode( value, nodeType ) );
  2659. };
  2660. /**
  2661. * This class represents a shader property. It can be used
  2662. * to explicitly define a property and assign a value to it.
  2663. *
  2664. * ```js
  2665. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2666. *```
  2667. * `PropertyNode` is used by the engine to predefined common material properties
  2668. * for TSL code.
  2669. *
  2670. * @augments Node
  2671. */
  2672. class PropertyNode extends Node {
  2673. static get type() {
  2674. return 'PropertyNode';
  2675. }
  2676. /**
  2677. * Constructs a new property node.
  2678. *
  2679. * @param {string} nodeType - The type of the node.
  2680. * @param {?string} [name=null] - The name of the property in the shader.
  2681. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2682. */
  2683. constructor( nodeType, name = null, varying = false ) {
  2684. super( nodeType );
  2685. /**
  2686. * The name of the property in the shader. If no name is defined,
  2687. * the node system auto-generates one.
  2688. *
  2689. * @type {?string}
  2690. * @default null
  2691. */
  2692. this.name = name;
  2693. /**
  2694. * Whether this property is a varying or not.
  2695. *
  2696. * @type {boolean}
  2697. * @default false
  2698. */
  2699. this.varying = varying;
  2700. /**
  2701. * This flag can be used for type testing.
  2702. *
  2703. * @type {boolean}
  2704. * @readonly
  2705. * @default true
  2706. */
  2707. this.isPropertyNode = true;
  2708. }
  2709. getHash( builder ) {
  2710. return this.name || super.getHash( builder );
  2711. }
  2712. /**
  2713. * The method is overwritten so it always returns `true`.
  2714. *
  2715. * @param {NodeBuilder} builder - The current node builder.
  2716. * @return {boolean} Whether this node is global or not.
  2717. */
  2718. isGlobal( /*builder*/ ) {
  2719. return true;
  2720. }
  2721. generate( builder ) {
  2722. let nodeVar;
  2723. if ( this.varying === true ) {
  2724. nodeVar = builder.getVaryingFromNode( this, this.name );
  2725. nodeVar.needsInterpolation = true;
  2726. } else {
  2727. nodeVar = builder.getVarFromNode( this, this.name );
  2728. }
  2729. return builder.getPropertyName( nodeVar );
  2730. }
  2731. }
  2732. /**
  2733. * TSL function for creating a property node.
  2734. *
  2735. * @tsl
  2736. * @function
  2737. * @param {string} type - The type of the node.
  2738. * @param {?string} [name=null] - The name of the property in the shader.
  2739. * @returns {PropertyNode}
  2740. */
  2741. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2742. /**
  2743. * TSL function for creating a varying property node.
  2744. *
  2745. * @tsl
  2746. * @function
  2747. * @param {string} type - The type of the node.
  2748. * @param {?string} [name=null] - The name of the varying in the shader.
  2749. * @returns {PropertyNode}
  2750. */
  2751. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2752. /**
  2753. * TSL object that represents the shader variable `DiffuseColor`.
  2754. *
  2755. * @tsl
  2756. * @type {PropertyNode<vec4>}
  2757. */
  2758. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2759. /**
  2760. * TSL object that represents the shader variable `EmissiveColor`.
  2761. *
  2762. * @tsl
  2763. * @type {PropertyNode<vec3>}
  2764. */
  2765. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2766. /**
  2767. * TSL object that represents the shader variable `Roughness`.
  2768. *
  2769. * @tsl
  2770. * @type {PropertyNode<float>}
  2771. */
  2772. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2773. /**
  2774. * TSL object that represents the shader variable `Metalness`.
  2775. *
  2776. * @tsl
  2777. * @type {PropertyNode<float>}
  2778. */
  2779. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2780. /**
  2781. * TSL object that represents the shader variable `Clearcoat`.
  2782. *
  2783. * @tsl
  2784. * @type {PropertyNode<float>}
  2785. */
  2786. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2787. /**
  2788. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2789. *
  2790. * @tsl
  2791. * @type {PropertyNode<float>}
  2792. */
  2793. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2794. /**
  2795. * TSL object that represents the shader variable `Sheen`.
  2796. *
  2797. * @tsl
  2798. * @type {PropertyNode<vec3>}
  2799. */
  2800. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2801. /**
  2802. * TSL object that represents the shader variable `SheenRoughness`.
  2803. *
  2804. * @tsl
  2805. * @type {PropertyNode<float>}
  2806. */
  2807. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2808. /**
  2809. * TSL object that represents the shader variable `Iridescence`.
  2810. *
  2811. * @tsl
  2812. * @type {PropertyNode<float>}
  2813. */
  2814. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2815. /**
  2816. * TSL object that represents the shader variable `IridescenceIOR`.
  2817. *
  2818. * @tsl
  2819. * @type {PropertyNode<float>}
  2820. */
  2821. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2822. /**
  2823. * TSL object that represents the shader variable `IridescenceThickness`.
  2824. *
  2825. * @tsl
  2826. * @type {PropertyNode<float>}
  2827. */
  2828. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2829. /**
  2830. * TSL object that represents the shader variable `AlphaT`.
  2831. *
  2832. * @tsl
  2833. * @type {PropertyNode<float>}
  2834. */
  2835. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2836. /**
  2837. * TSL object that represents the shader variable `Anisotropy`.
  2838. *
  2839. * @tsl
  2840. * @type {PropertyNode<float>}
  2841. */
  2842. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2843. /**
  2844. * TSL object that represents the shader variable `AnisotropyT`.
  2845. *
  2846. * @tsl
  2847. * @type {PropertyNode<vec3>}
  2848. */
  2849. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2850. /**
  2851. * TSL object that represents the shader variable `AnisotropyB`.
  2852. *
  2853. * @tsl
  2854. * @type {PropertyNode<vec3>}
  2855. */
  2856. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2857. /**
  2858. * TSL object that represents the shader variable `SpecularColor`.
  2859. *
  2860. * @tsl
  2861. * @type {PropertyNode<color>}
  2862. */
  2863. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2864. /**
  2865. * TSL object that represents the shader variable `SpecularF90`.
  2866. *
  2867. * @tsl
  2868. * @type {PropertyNode<float>}
  2869. */
  2870. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2871. /**
  2872. * TSL object that represents the shader variable `Shininess`.
  2873. *
  2874. * @tsl
  2875. * @type {PropertyNode<float>}
  2876. */
  2877. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2878. /**
  2879. * TSL object that represents the shader variable `Output`.
  2880. *
  2881. * @tsl
  2882. * @type {PropertyNode<vec4>}
  2883. */
  2884. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2885. /**
  2886. * TSL object that represents the shader variable `dashSize`.
  2887. *
  2888. * @tsl
  2889. * @type {PropertyNode<float>}
  2890. */
  2891. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2892. /**
  2893. * TSL object that represents the shader variable `gapSize`.
  2894. *
  2895. * @tsl
  2896. * @type {PropertyNode<float>}
  2897. */
  2898. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2899. /**
  2900. * TSL object that represents the shader variable `pointWidth`.
  2901. *
  2902. * @tsl
  2903. * @type {PropertyNode<float>}
  2904. */
  2905. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2906. /**
  2907. * TSL object that represents the shader variable `IOR`.
  2908. *
  2909. * @tsl
  2910. * @type {PropertyNode<float>}
  2911. */
  2912. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2913. /**
  2914. * TSL object that represents the shader variable `Transmission`.
  2915. *
  2916. * @tsl
  2917. * @type {PropertyNode<float>}
  2918. */
  2919. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2920. /**
  2921. * TSL object that represents the shader variable `Thickness`.
  2922. *
  2923. * @tsl
  2924. * @type {PropertyNode<float>}
  2925. */
  2926. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2927. /**
  2928. * TSL object that represents the shader variable `AttenuationDistance`.
  2929. *
  2930. * @tsl
  2931. * @type {PropertyNode<float>}
  2932. */
  2933. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2934. /**
  2935. * TSL object that represents the shader variable `AttenuationColor`.
  2936. *
  2937. * @tsl
  2938. * @type {PropertyNode<color>}
  2939. */
  2940. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2941. /**
  2942. * TSL object that represents the shader variable `Dispersion`.
  2943. *
  2944. * @tsl
  2945. * @type {PropertyNode<float>}
  2946. */
  2947. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2948. /**
  2949. * These node represents an assign operation. Meaning a node is assigned
  2950. * to another node.
  2951. *
  2952. * @augments TempNode
  2953. */
  2954. class AssignNode extends TempNode {
  2955. static get type() {
  2956. return 'AssignNode';
  2957. }
  2958. /**
  2959. * Constructs a new assign node.
  2960. *
  2961. * @param {Node} targetNode - The target node.
  2962. * @param {Node} sourceNode - The source type.
  2963. */
  2964. constructor( targetNode, sourceNode ) {
  2965. super();
  2966. /**
  2967. * The target node.
  2968. *
  2969. * @type {Node}
  2970. */
  2971. this.targetNode = targetNode;
  2972. /**
  2973. * The source node.
  2974. *
  2975. * @type {Node}
  2976. */
  2977. this.sourceNode = sourceNode;
  2978. }
  2979. /**
  2980. * Whether this node is used more than once in context of other nodes. This method
  2981. * is overwritten since it always returns `false` (assigns are unique).
  2982. *
  2983. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2984. */
  2985. hasDependencies() {
  2986. return false;
  2987. }
  2988. getNodeType( builder, output ) {
  2989. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2990. }
  2991. /**
  2992. * Whether a split is required when assigning source to target. This can happen when the component length of
  2993. * target and source data type does not match.
  2994. *
  2995. * @param {NodeBuilder} builder - The current node builder.
  2996. * @return {boolean} Whether a split is required when assigning source to target.
  2997. */
  2998. needsSplitAssign( builder ) {
  2999. const { targetNode } = this;
  3000. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3001. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3002. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3003. return assignDifferentVector;
  3004. }
  3005. return false;
  3006. }
  3007. generate( builder, output ) {
  3008. const { targetNode, sourceNode } = this;
  3009. const needsSplitAssign = this.needsSplitAssign( builder );
  3010. const targetType = targetNode.getNodeType( builder );
  3011. const target = targetNode.context( { assign: true } ).build( builder );
  3012. const source = sourceNode.build( builder, targetType );
  3013. const sourceType = sourceNode.getNodeType( builder );
  3014. const nodeData = builder.getDataFromNode( this );
  3015. //
  3016. let snippet;
  3017. if ( nodeData.initialized === true ) {
  3018. if ( output !== 'void' ) {
  3019. snippet = target;
  3020. }
  3021. } else if ( needsSplitAssign ) {
  3022. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3023. const sourceProperty = builder.getPropertyName( sourceVar );
  3024. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3025. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3026. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3027. const component = targetNode.components[ i ];
  3028. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3029. }
  3030. if ( output !== 'void' ) {
  3031. snippet = target;
  3032. }
  3033. } else {
  3034. snippet = `${ target } = ${ source }`;
  3035. if ( output === 'void' || sourceType === 'void' ) {
  3036. builder.addLineFlowCode( snippet, this );
  3037. if ( output !== 'void' ) {
  3038. snippet = target;
  3039. }
  3040. }
  3041. }
  3042. nodeData.initialized = true;
  3043. return builder.format( snippet, targetType, output );
  3044. }
  3045. }
  3046. /**
  3047. * TSL function for creating an assign node.
  3048. *
  3049. * @tsl
  3050. * @function
  3051. * @param {Node} targetNode - The target node.
  3052. * @param {Node} sourceNode - The source type.
  3053. * @returns {AssignNode}
  3054. */
  3055. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  3056. addMethodChaining( 'assign', assign );
  3057. /**
  3058. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3059. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3060. * this logic.
  3061. *
  3062. * @augments TempNode
  3063. */
  3064. class FunctionCallNode extends TempNode {
  3065. static get type() {
  3066. return 'FunctionCallNode';
  3067. }
  3068. /**
  3069. * Constructs a new function call node.
  3070. *
  3071. * @param {?FunctionNode} functionNode - The function node.
  3072. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3073. */
  3074. constructor( functionNode = null, parameters = {} ) {
  3075. super();
  3076. /**
  3077. * The function node.
  3078. *
  3079. * @type {?FunctionNode}
  3080. * @default null
  3081. */
  3082. this.functionNode = functionNode;
  3083. /**
  3084. * The parameters of the function call.
  3085. *
  3086. * @type {Object<string, Node>}
  3087. * @default {}
  3088. */
  3089. this.parameters = parameters;
  3090. }
  3091. /**
  3092. * Sets the parameters of the function call node.
  3093. *
  3094. * @param {Object<string, Node>} parameters - The parameters to set.
  3095. * @return {FunctionCallNode} A reference to this node.
  3096. */
  3097. setParameters( parameters ) {
  3098. this.parameters = parameters;
  3099. return this;
  3100. }
  3101. /**
  3102. * Returns the parameters of the function call node.
  3103. *
  3104. * @return {Object<string, Node>} The parameters of this node.
  3105. */
  3106. getParameters() {
  3107. return this.parameters;
  3108. }
  3109. getNodeType( builder ) {
  3110. return this.functionNode.getNodeType( builder );
  3111. }
  3112. generate( builder ) {
  3113. const params = [];
  3114. const functionNode = this.functionNode;
  3115. const inputs = functionNode.getInputs( builder );
  3116. const parameters = this.parameters;
  3117. const generateInput = ( node, inputNode ) => {
  3118. const type = inputNode.type;
  3119. const pointer = type === 'pointer';
  3120. let output;
  3121. if ( pointer ) output = '&' + node.build( builder );
  3122. else output = node.build( builder, type );
  3123. return output;
  3124. };
  3125. if ( Array.isArray( parameters ) ) {
  3126. for ( let i = 0; i < parameters.length; i ++ ) {
  3127. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3128. }
  3129. } else {
  3130. for ( const inputNode of inputs ) {
  3131. const node = parameters[ inputNode.name ];
  3132. if ( node !== undefined ) {
  3133. params.push( generateInput( node, inputNode ) );
  3134. } else {
  3135. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3136. }
  3137. }
  3138. }
  3139. const functionName = functionNode.build( builder, 'property' );
  3140. return `${functionName}( ${params.join( ', ' )} )`;
  3141. }
  3142. }
  3143. const call = ( func, ...params ) => {
  3144. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3145. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3146. };
  3147. addMethodChaining( 'call', call );
  3148. /**
  3149. * This node represents basic mathematical and logical operations like addition,
  3150. * subtraction or comparisons (e.g. `equal()`).
  3151. *
  3152. * @augments TempNode
  3153. */
  3154. class OperatorNode extends TempNode {
  3155. static get type() {
  3156. return 'OperatorNode';
  3157. }
  3158. /**
  3159. * Constructs a new operator node.
  3160. *
  3161. * @param {string} op - The operator.
  3162. * @param {Node} aNode - The first input.
  3163. * @param {Node} bNode - The second input.
  3164. * @param {...Node} params - Additional input parameters.
  3165. */
  3166. constructor( op, aNode, bNode, ...params ) {
  3167. super();
  3168. if ( params.length > 0 ) {
  3169. let finalOp = new OperatorNode( op, aNode, bNode );
  3170. for ( let i = 0; i < params.length - 1; i ++ ) {
  3171. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3172. }
  3173. aNode = finalOp;
  3174. bNode = params[ params.length - 1 ];
  3175. }
  3176. /**
  3177. * The operator.
  3178. *
  3179. * @type {string}
  3180. */
  3181. this.op = op;
  3182. /**
  3183. * The first input.
  3184. *
  3185. * @type {Node}
  3186. */
  3187. this.aNode = aNode;
  3188. /**
  3189. * The second input.
  3190. *
  3191. * @type {Node}
  3192. */
  3193. this.bNode = bNode;
  3194. /**
  3195. * This flag can be used for type testing.
  3196. *
  3197. * @type {boolean}
  3198. * @readonly
  3199. * @default true
  3200. */
  3201. this.isOperatorNode = true;
  3202. }
  3203. /**
  3204. * This method is overwritten since the node type is inferred from the operator
  3205. * and the input node types.
  3206. *
  3207. * @param {NodeBuilder} builder - The current node builder.
  3208. * @param {string} output - The current output string.
  3209. * @return {string} The node type.
  3210. */
  3211. getNodeType( builder, output ) {
  3212. const op = this.op;
  3213. const aNode = this.aNode;
  3214. const bNode = this.bNode;
  3215. const typeA = aNode.getNodeType( builder );
  3216. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3217. if ( typeA === 'void' || typeB === 'void' ) {
  3218. return 'void';
  3219. } else if ( op === '%' ) {
  3220. return typeA;
  3221. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3222. return builder.getIntegerType( typeA );
  3223. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3224. return 'bool';
  3225. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3226. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3227. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3228. } else {
  3229. // Handle matrix operations
  3230. if ( builder.isMatrix( typeA ) ) {
  3231. if ( typeB === 'float' ) {
  3232. return typeA; // matrix * scalar = matrix
  3233. } else if ( builder.isVector( typeB ) ) {
  3234. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3235. } else if ( builder.isMatrix( typeB ) ) {
  3236. return typeA; // matrix * matrix
  3237. }
  3238. } else if ( builder.isMatrix( typeB ) ) {
  3239. if ( typeA === 'float' ) {
  3240. return typeB; // scalar * matrix = matrix
  3241. } else if ( builder.isVector( typeA ) ) {
  3242. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3243. }
  3244. }
  3245. // Handle non-matrix cases
  3246. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3247. // anytype x anytype: use the greater length vector
  3248. return typeB;
  3249. }
  3250. return typeA;
  3251. }
  3252. }
  3253. generate( builder, output ) {
  3254. const op = this.op;
  3255. const aNode = this.aNode;
  3256. const bNode = this.bNode;
  3257. const type = this.getNodeType( builder, output );
  3258. let typeA = null;
  3259. let typeB = null;
  3260. if ( type !== 'void' ) {
  3261. typeA = aNode.getNodeType( builder );
  3262. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3263. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3264. if ( builder.isVector( typeA ) ) {
  3265. typeB = typeA;
  3266. } else if ( typeA !== typeB ) {
  3267. typeA = typeB = 'float';
  3268. }
  3269. } else if ( op === '>>' || op === '<<' ) {
  3270. typeA = type;
  3271. typeB = builder.changeComponentType( typeB, 'uint' );
  3272. } else if ( builder.isMatrix( typeA ) ) {
  3273. if ( typeB === 'float' ) {
  3274. // Keep matrix type for typeA, but ensure typeB stays float
  3275. typeB = 'float';
  3276. } else if ( builder.isVector( typeB ) ) {
  3277. // matrix x vector
  3278. typeB = builder.getVectorFromMatrix( typeA );
  3279. } else if ( builder.isMatrix( typeB ) ) ; else {
  3280. typeA = typeB = type;
  3281. }
  3282. } else if ( builder.isMatrix( typeB ) ) {
  3283. if ( typeA === 'float' ) {
  3284. // Keep matrix type for typeB, but ensure typeA stays float
  3285. typeA = 'float';
  3286. } else if ( builder.isVector( typeA ) ) {
  3287. // vector x matrix
  3288. typeA = builder.getVectorFromMatrix( typeB );
  3289. } else {
  3290. typeA = typeB = type;
  3291. }
  3292. } else {
  3293. // anytype x anytype
  3294. typeA = typeB = type;
  3295. }
  3296. } else {
  3297. typeA = typeB = type;
  3298. }
  3299. const a = aNode.build( builder, typeA );
  3300. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3301. const outputLength = builder.getTypeLength( output );
  3302. const fnOpSnippet = builder.getFunctionOperator( op );
  3303. if ( output !== 'void' ) {
  3304. if ( op === '<' && outputLength > 1 ) {
  3305. if ( builder.useComparisonMethod ) {
  3306. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3307. } else {
  3308. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3309. }
  3310. } else if ( op === '<=' && outputLength > 1 ) {
  3311. if ( builder.useComparisonMethod ) {
  3312. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3313. } else {
  3314. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3315. }
  3316. } else if ( op === '>' && outputLength > 1 ) {
  3317. if ( builder.useComparisonMethod ) {
  3318. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3319. } else {
  3320. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3321. }
  3322. } else if ( op === '>=' && outputLength > 1 ) {
  3323. if ( builder.useComparisonMethod ) {
  3324. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3325. } else {
  3326. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3327. }
  3328. } else if ( op === '!' || op === '~' ) {
  3329. return builder.format( `(${op}${a})`, typeA, output );
  3330. } else if ( fnOpSnippet ) {
  3331. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3332. } else {
  3333. // Handle matrix operations
  3334. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3335. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3336. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3337. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3338. } else {
  3339. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3340. }
  3341. }
  3342. } else if ( typeA !== 'void' ) {
  3343. if ( fnOpSnippet ) {
  3344. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3345. } else {
  3346. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3347. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3348. } else {
  3349. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3350. }
  3351. }
  3352. }
  3353. }
  3354. serialize( data ) {
  3355. super.serialize( data );
  3356. data.op = this.op;
  3357. }
  3358. deserialize( data ) {
  3359. super.deserialize( data );
  3360. this.op = data.op;
  3361. }
  3362. }
  3363. /**
  3364. * Returns the addition of two or more value.
  3365. *
  3366. * @tsl
  3367. * @function
  3368. * @param {Node} aNode - The first input.
  3369. * @param {Node} bNode - The second input.
  3370. * @param {...Node} params - Additional input parameters.
  3371. * @returns {OperatorNode}
  3372. */
  3373. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3374. /**
  3375. * Returns the subtraction of two or more value.
  3376. *
  3377. * @tsl
  3378. * @function
  3379. * @param {Node} aNode - The first input.
  3380. * @param {Node} bNode - The second input.
  3381. * @param {...Node} params - Additional input parameters.
  3382. * @returns {OperatorNode}
  3383. */
  3384. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3385. /**
  3386. * Returns the multiplication of two or more value.
  3387. *
  3388. * @tsl
  3389. * @function
  3390. * @param {Node} aNode - The first input.
  3391. * @param {Node} bNode - The second input.
  3392. * @param {...Node} params - Additional input parameters.
  3393. * @returns {OperatorNode}
  3394. */
  3395. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3396. /**
  3397. * Returns the division of two or more value.
  3398. *
  3399. * @tsl
  3400. * @function
  3401. * @param {Node} aNode - The first input.
  3402. * @param {Node} bNode - The second input.
  3403. * @param {...Node} params - Additional input parameters.
  3404. * @returns {OperatorNode}
  3405. */
  3406. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3407. /**
  3408. * Computes the remainder of dividing the first node by the second, for integer values.
  3409. *
  3410. * @tsl
  3411. * @function
  3412. * @param {Node} aNode - The first input.
  3413. * @param {Node} bNode - The second input.
  3414. * @returns {OperatorNode}
  3415. */
  3416. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3417. /**
  3418. * Checks if two nodes are equal.
  3419. *
  3420. * @tsl
  3421. * @function
  3422. * @param {Node} aNode - The first input.
  3423. * @param {Node} bNode - The second input.
  3424. * @returns {OperatorNode}
  3425. */
  3426. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3427. /**
  3428. * Checks if two nodes are not equal.
  3429. *
  3430. * @tsl
  3431. * @function
  3432. * @param {Node} aNode - The first input.
  3433. * @param {Node} bNode - The second input.
  3434. * @returns {OperatorNode}
  3435. */
  3436. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3437. /**
  3438. * Checks if the first node is less than the second.
  3439. *
  3440. * @tsl
  3441. * @function
  3442. * @param {Node} aNode - The first input.
  3443. * @param {Node} bNode - The second input.
  3444. * @returns {OperatorNode}
  3445. */
  3446. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3447. /**
  3448. * Checks if the first node is greater than the second.
  3449. *
  3450. * @tsl
  3451. * @function
  3452. * @param {Node} aNode - The first input.
  3453. * @param {Node} bNode - The second input.
  3454. * @returns {OperatorNode}
  3455. */
  3456. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3457. /**
  3458. * Checks if the first node is less than or equal to the second.
  3459. *
  3460. * @tsl
  3461. * @function
  3462. * @param {Node} aNode - The first input.
  3463. * @param {Node} bNode - The second input.
  3464. * @returns {OperatorNode}
  3465. */
  3466. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3467. /**
  3468. * Checks if the first node is greater than or equal to the second.
  3469. *
  3470. * @tsl
  3471. * @function
  3472. * @param {Node} aNode - The first input.
  3473. * @param {Node} bNode - The second input.
  3474. * @returns {OperatorNode}
  3475. */
  3476. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3477. /**
  3478. * Performs logical AND on two nodes.
  3479. *
  3480. * @tsl
  3481. * @function
  3482. * @param {Node} aNode - The first input.
  3483. * @param {Node} bNode - The second input.
  3484. * @returns {OperatorNode}
  3485. */
  3486. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3487. /**
  3488. * Performs logical OR on two nodes.
  3489. *
  3490. * @tsl
  3491. * @function
  3492. * @param {Node} aNode - The first input.
  3493. * @param {Node} bNode - The second input.
  3494. * @returns {OperatorNode}
  3495. */
  3496. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3497. /**
  3498. * Performs logical NOT on a node.
  3499. *
  3500. * @tsl
  3501. * @function
  3502. * @param {Node} aNode - The first input.
  3503. * @param {Node} bNode - The second input.
  3504. * @returns {OperatorNode}
  3505. */
  3506. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3507. /**
  3508. * Performs logical XOR on two nodes.
  3509. *
  3510. * @tsl
  3511. * @function
  3512. * @param {Node} aNode - The first input.
  3513. * @param {Node} bNode - The second input.
  3514. * @returns {OperatorNode}
  3515. */
  3516. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3517. /**
  3518. * Performs bitwise AND on two nodes.
  3519. *
  3520. * @tsl
  3521. * @function
  3522. * @param {Node} aNode - The first input.
  3523. * @param {Node} bNode - The second input.
  3524. * @returns {OperatorNode}
  3525. */
  3526. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3527. /**
  3528. * Performs bitwise NOT on a node.
  3529. *
  3530. * @tsl
  3531. * @function
  3532. * @param {Node} aNode - The first input.
  3533. * @param {Node} bNode - The second input.
  3534. * @returns {OperatorNode}
  3535. */
  3536. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3537. /**
  3538. * Performs bitwise OR on two nodes.
  3539. *
  3540. * @tsl
  3541. * @function
  3542. * @param {Node} aNode - The first input.
  3543. * @param {Node} bNode - The second input.
  3544. * @returns {OperatorNode}
  3545. */
  3546. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3547. /**
  3548. * Performs bitwise XOR on two nodes.
  3549. *
  3550. * @tsl
  3551. * @function
  3552. * @param {Node} aNode - The first input.
  3553. * @param {Node} bNode - The second input.
  3554. * @returns {OperatorNode}
  3555. */
  3556. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3557. /**
  3558. * Shifts a node to the left.
  3559. *
  3560. * @tsl
  3561. * @function
  3562. * @param {Node} aNode - The node to shift.
  3563. * @param {Node} bNode - The value to shift.
  3564. * @returns {OperatorNode}
  3565. */
  3566. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3567. /**
  3568. * Shifts a node to the right.
  3569. *
  3570. * @tsl
  3571. * @function
  3572. * @param {Node} aNode - The node to shift.
  3573. * @param {Node} bNode - The value to shift.
  3574. * @returns {OperatorNode}
  3575. */
  3576. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3577. addMethodChaining( 'add', add );
  3578. addMethodChaining( 'sub', sub );
  3579. addMethodChaining( 'mul', mul );
  3580. addMethodChaining( 'div', div );
  3581. addMethodChaining( 'modInt', modInt );
  3582. addMethodChaining( 'equal', equal );
  3583. addMethodChaining( 'notEqual', notEqual );
  3584. addMethodChaining( 'lessThan', lessThan );
  3585. addMethodChaining( 'greaterThan', greaterThan );
  3586. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3587. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3588. addMethodChaining( 'and', and );
  3589. addMethodChaining( 'or', or );
  3590. addMethodChaining( 'not', not );
  3591. addMethodChaining( 'xor', xor );
  3592. addMethodChaining( 'bitAnd', bitAnd );
  3593. addMethodChaining( 'bitNot', bitNot );
  3594. addMethodChaining( 'bitOr', bitOr );
  3595. addMethodChaining( 'bitXor', bitXor );
  3596. addMethodChaining( 'shiftLeft', shiftLeft );
  3597. addMethodChaining( 'shiftRight', shiftRight );
  3598. /**
  3599. * @tsl
  3600. * @function
  3601. * @deprecated since r168. Use {@link modInt} instead.
  3602. *
  3603. * @param {...any} params
  3604. * @returns {Function}
  3605. */
  3606. const remainder = ( ...params ) => { // @deprecated, r168
  3607. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3608. return modInt( ...params );
  3609. };
  3610. addMethodChaining( 'remainder', remainder );
  3611. /**
  3612. * This node represents a variety of mathematical methods available in shaders.
  3613. * They are divided into three categories:
  3614. *
  3615. * - Methods with one input like `sin`, `cos` or `normalize`.
  3616. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3617. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3618. *
  3619. * @augments TempNode
  3620. */
  3621. class MathNode extends TempNode {
  3622. static get type() {
  3623. return 'MathNode';
  3624. }
  3625. /**
  3626. * Constructs a new math node.
  3627. *
  3628. * @param {string} method - The method name.
  3629. * @param {Node} aNode - The first input.
  3630. * @param {?Node} [bNode=null] - The second input.
  3631. * @param {?Node} [cNode=null] - The third input.
  3632. */
  3633. constructor( method, aNode, bNode = null, cNode = null ) {
  3634. super();
  3635. /**
  3636. * The method name.
  3637. *
  3638. * @type {string}
  3639. */
  3640. this.method = method;
  3641. /**
  3642. * The first input.
  3643. *
  3644. * @type {Node}
  3645. */
  3646. this.aNode = aNode;
  3647. /**
  3648. * The second input.
  3649. *
  3650. * @type {?Node}
  3651. * @default null
  3652. */
  3653. this.bNode = bNode;
  3654. /**
  3655. * The third input.
  3656. *
  3657. * @type {?Node}
  3658. * @default null
  3659. */
  3660. this.cNode = cNode;
  3661. /**
  3662. * This flag can be used for type testing.
  3663. *
  3664. * @type {boolean}
  3665. * @readonly
  3666. * @default true
  3667. */
  3668. this.isMathNode = true;
  3669. }
  3670. /**
  3671. * The input type is inferred from the node types of the input nodes.
  3672. *
  3673. * @param {NodeBuilder} builder - The current node builder.
  3674. * @return {string} The input type.
  3675. */
  3676. getInputType( builder ) {
  3677. const aType = this.aNode.getNodeType( builder );
  3678. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3679. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3680. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3681. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3682. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3683. if ( aLen > bLen && aLen > cLen ) {
  3684. return aType;
  3685. } else if ( bLen > cLen ) {
  3686. return bType;
  3687. } else if ( cLen > aLen ) {
  3688. return cType;
  3689. }
  3690. return aType;
  3691. }
  3692. /**
  3693. * The selected method as well as the input type determine the node type of this node.
  3694. *
  3695. * @param {NodeBuilder} builder - The current node builder.
  3696. * @return {string} The node type.
  3697. */
  3698. getNodeType( builder ) {
  3699. const method = this.method;
  3700. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3701. return 'float';
  3702. } else if ( method === MathNode.CROSS ) {
  3703. return 'vec3';
  3704. } else if ( method === MathNode.ALL ) {
  3705. return 'bool';
  3706. } else if ( method === MathNode.EQUALS ) {
  3707. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3708. } else if ( method === MathNode.MOD ) {
  3709. return this.aNode.getNodeType( builder );
  3710. } else {
  3711. return this.getInputType( builder );
  3712. }
  3713. }
  3714. generate( builder, output ) {
  3715. let method = this.method;
  3716. const type = this.getNodeType( builder );
  3717. const inputType = this.getInputType( builder );
  3718. const a = this.aNode;
  3719. const b = this.bNode;
  3720. const c = this.cNode;
  3721. const coordinateSystem = builder.renderer.coordinateSystem;
  3722. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3723. // dir can be either a direction vector or a normal vector
  3724. // upper-left 3x3 of matrix is assumed to be orthogonal
  3725. let tA = a;
  3726. let tB = b;
  3727. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3728. tB = vec4( vec3( tB ), 0.0 );
  3729. } else {
  3730. tA = vec4( vec3( tA ), 0.0 );
  3731. }
  3732. const mulNode = mul( tA, tB ).xyz;
  3733. return normalize( mulNode ).build( builder, output );
  3734. } else if ( method === MathNode.NEGATE ) {
  3735. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3736. } else if ( method === MathNode.ONE_MINUS ) {
  3737. return sub( 1.0, a ).build( builder, output );
  3738. } else if ( method === MathNode.RECIPROCAL ) {
  3739. return div( 1.0, a ).build( builder, output );
  3740. } else if ( method === MathNode.DIFFERENCE ) {
  3741. return abs( sub( a, b ) ).build( builder, output );
  3742. } else {
  3743. const params = [];
  3744. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3745. params.push(
  3746. a.build( builder, type ),
  3747. b.build( builder, type )
  3748. );
  3749. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3750. params.push(
  3751. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3752. b.build( builder, inputType )
  3753. );
  3754. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3755. params.push(
  3756. a.build( builder, inputType ),
  3757. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3758. );
  3759. } else if ( method === MathNode.REFRACT ) {
  3760. params.push(
  3761. a.build( builder, inputType ),
  3762. b.build( builder, inputType ),
  3763. c.build( builder, 'float' )
  3764. );
  3765. } else if ( method === MathNode.MIX ) {
  3766. params.push(
  3767. a.build( builder, inputType ),
  3768. b.build( builder, inputType ),
  3769. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3770. );
  3771. } else {
  3772. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3773. method = 'atan2';
  3774. }
  3775. params.push( a.build( builder, inputType ) );
  3776. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3777. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3778. }
  3779. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3780. }
  3781. }
  3782. serialize( data ) {
  3783. super.serialize( data );
  3784. data.method = this.method;
  3785. }
  3786. deserialize( data ) {
  3787. super.deserialize( data );
  3788. this.method = data.method;
  3789. }
  3790. }
  3791. // 1 input
  3792. MathNode.ALL = 'all';
  3793. MathNode.ANY = 'any';
  3794. MathNode.RADIANS = 'radians';
  3795. MathNode.DEGREES = 'degrees';
  3796. MathNode.EXP = 'exp';
  3797. MathNode.EXP2 = 'exp2';
  3798. MathNode.LOG = 'log';
  3799. MathNode.LOG2 = 'log2';
  3800. MathNode.SQRT = 'sqrt';
  3801. MathNode.INVERSE_SQRT = 'inversesqrt';
  3802. MathNode.FLOOR = 'floor';
  3803. MathNode.CEIL = 'ceil';
  3804. MathNode.NORMALIZE = 'normalize';
  3805. MathNode.FRACT = 'fract';
  3806. MathNode.SIN = 'sin';
  3807. MathNode.COS = 'cos';
  3808. MathNode.TAN = 'tan';
  3809. MathNode.ASIN = 'asin';
  3810. MathNode.ACOS = 'acos';
  3811. MathNode.ATAN = 'atan';
  3812. MathNode.ABS = 'abs';
  3813. MathNode.SIGN = 'sign';
  3814. MathNode.LENGTH = 'length';
  3815. MathNode.NEGATE = 'negate';
  3816. MathNode.ONE_MINUS = 'oneMinus';
  3817. MathNode.DFDX = 'dFdx';
  3818. MathNode.DFDY = 'dFdy';
  3819. MathNode.ROUND = 'round';
  3820. MathNode.RECIPROCAL = 'reciprocal';
  3821. MathNode.TRUNC = 'trunc';
  3822. MathNode.FWIDTH = 'fwidth';
  3823. MathNode.TRANSPOSE = 'transpose';
  3824. // 2 inputs
  3825. MathNode.BITCAST = 'bitcast';
  3826. MathNode.EQUALS = 'equals';
  3827. MathNode.MIN = 'min';
  3828. MathNode.MAX = 'max';
  3829. MathNode.MOD = 'mod';
  3830. MathNode.STEP = 'step';
  3831. MathNode.REFLECT = 'reflect';
  3832. MathNode.DISTANCE = 'distance';
  3833. MathNode.DIFFERENCE = 'difference';
  3834. MathNode.DOT = 'dot';
  3835. MathNode.CROSS = 'cross';
  3836. MathNode.POW = 'pow';
  3837. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3838. // 3 inputs
  3839. MathNode.MIX = 'mix';
  3840. MathNode.CLAMP = 'clamp';
  3841. MathNode.REFRACT = 'refract';
  3842. MathNode.SMOOTHSTEP = 'smoothstep';
  3843. MathNode.FACEFORWARD = 'faceforward';
  3844. // 1 inputs
  3845. /**
  3846. * A small value used to handle floating-point precision errors.
  3847. *
  3848. * @tsl
  3849. * @type {Node<float>}
  3850. */
  3851. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3852. /**
  3853. * Represents infinity.
  3854. *
  3855. * @tsl
  3856. * @type {Node<float>}
  3857. */
  3858. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3859. /**
  3860. * Represents PI.
  3861. *
  3862. * @tsl
  3863. * @type {Node<float>}
  3864. */
  3865. const PI = /*@__PURE__*/ float( Math.PI );
  3866. /**
  3867. * Represents PI * 2.
  3868. *
  3869. * @tsl
  3870. * @type {Node<float>}
  3871. */
  3872. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3873. /**
  3874. * Returns `true` if all components of `x` are `true`.
  3875. *
  3876. * @tsl
  3877. * @function
  3878. * @param {Node | number} x - The parameter.
  3879. * @returns {Node<bool>}
  3880. */
  3881. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3882. /**
  3883. * Returns `true` if any components of `x` are `true`.
  3884. *
  3885. * @tsl
  3886. * @function
  3887. * @param {Node | number} x - The parameter.
  3888. * @returns {Node<bool>}
  3889. */
  3890. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3891. /**
  3892. * Converts a quantity in degrees to radians.
  3893. *
  3894. * @tsl
  3895. * @function
  3896. * @param {Node | number} x - The input in degrees.
  3897. * @returns {Node}
  3898. */
  3899. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3900. /**
  3901. * Convert a quantity in radians to degrees.
  3902. *
  3903. * @tsl
  3904. * @function
  3905. * @param {Node | number} x - The input in radians.
  3906. * @returns {Node}
  3907. */
  3908. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3909. /**
  3910. * Returns the natural exponentiation of the parameter.
  3911. *
  3912. * @tsl
  3913. * @function
  3914. * @param {Node | number} x - The parameter.
  3915. * @returns {Node}
  3916. */
  3917. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3918. /**
  3919. * Returns 2 raised to the power of the parameter.
  3920. *
  3921. * @tsl
  3922. * @function
  3923. * @param {Node | number} x - The parameter.
  3924. * @returns {Node}
  3925. */
  3926. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3927. /**
  3928. * Returns the natural logarithm of the parameter.
  3929. *
  3930. * @tsl
  3931. * @function
  3932. * @param {Node | number} x - The parameter.
  3933. * @returns {Node}
  3934. */
  3935. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3936. /**
  3937. * Returns the base 2 logarithm of the parameter.
  3938. *
  3939. * @tsl
  3940. * @function
  3941. * @param {Node | number} x - The parameter.
  3942. * @returns {Node}
  3943. */
  3944. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3945. /**
  3946. * Returns the square root of the parameter.
  3947. *
  3948. * @tsl
  3949. * @function
  3950. * @param {Node | number} x - The parameter.
  3951. * @returns {Node}
  3952. */
  3953. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3954. /**
  3955. * Returns the inverse of the square root of the parameter.
  3956. *
  3957. * @tsl
  3958. * @function
  3959. * @param {Node | number} x - The parameter.
  3960. * @returns {Node}
  3961. */
  3962. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3963. /**
  3964. * Finds the nearest integer less than or equal to the parameter.
  3965. *
  3966. * @tsl
  3967. * @function
  3968. * @param {Node | number} x - The parameter.
  3969. * @returns {Node}
  3970. */
  3971. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3972. /**
  3973. * Finds the nearest integer that is greater than or equal to the parameter.
  3974. *
  3975. * @tsl
  3976. * @function
  3977. * @param {Node | number} x - The parameter.
  3978. * @returns {Node}
  3979. */
  3980. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3981. /**
  3982. * Calculates the unit vector in the same direction as the original vector.
  3983. *
  3984. * @tsl
  3985. * @function
  3986. * @param {Node} x - The input vector.
  3987. * @returns {Node}
  3988. */
  3989. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3990. /**
  3991. * Computes the fractional part of the parameter.
  3992. *
  3993. * @tsl
  3994. * @function
  3995. * @param {Node | number} x - The parameter.
  3996. * @returns {Node}
  3997. */
  3998. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3999. /**
  4000. * Returns the sine of the parameter.
  4001. *
  4002. * @tsl
  4003. * @function
  4004. * @param {Node | number} x - The parameter.
  4005. * @returns {Node}
  4006. */
  4007. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  4008. /**
  4009. * Returns the cosine of the parameter.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {Node | number} x - The parameter.
  4014. * @returns {Node}
  4015. */
  4016. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  4017. /**
  4018. * Returns the tangent of the parameter.
  4019. *
  4020. * @tsl
  4021. * @function
  4022. * @param {Node | number} x - The parameter.
  4023. * @returns {Node}
  4024. */
  4025. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  4026. /**
  4027. * Returns the arcsine of the parameter.
  4028. *
  4029. * @tsl
  4030. * @function
  4031. * @param {Node | number} x - The parameter.
  4032. * @returns {Node}
  4033. */
  4034. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  4035. /**
  4036. * Returns the arccosine of the parameter.
  4037. *
  4038. * @tsl
  4039. * @function
  4040. * @param {Node | number} x - The parameter.
  4041. * @returns {Node}
  4042. */
  4043. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  4044. /**
  4045. * Returns the arc-tangent of the parameter.
  4046. * If two parameters are provided, the result is `atan2(y/x)`.
  4047. *
  4048. * @tsl
  4049. * @function
  4050. * @param {Node | number} y - The y parameter.
  4051. * @param {?(Node | number)} x - The x parameter.
  4052. * @returns {Node}
  4053. */
  4054. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  4055. /**
  4056. * Returns the absolute value of the parameter.
  4057. *
  4058. * @tsl
  4059. * @function
  4060. * @param {Node | number} x - The parameter.
  4061. * @returns {Node}
  4062. */
  4063. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  4064. /**
  4065. * Extracts the sign of the parameter.
  4066. *
  4067. * @tsl
  4068. * @function
  4069. * @param {Node | number} x - The parameter.
  4070. * @returns {Node}
  4071. */
  4072. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  4073. /**
  4074. * Calculates the length of a vector.
  4075. *
  4076. * @tsl
  4077. * @function
  4078. * @param {Node} x - The parameter.
  4079. * @returns {Node<float>}
  4080. */
  4081. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  4082. /**
  4083. * Negates the value of the parameter (-x).
  4084. *
  4085. * @tsl
  4086. * @function
  4087. * @param {Node | number} x - The parameter.
  4088. * @returns {Node}
  4089. */
  4090. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  4091. /**
  4092. * Return `1` minus the parameter.
  4093. *
  4094. * @tsl
  4095. * @function
  4096. * @param {Node | number} x - The parameter.
  4097. * @returns {Node}
  4098. */
  4099. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  4100. /**
  4101. * Returns the partial derivative of the parameter with respect to x.
  4102. *
  4103. * @tsl
  4104. * @function
  4105. * @param {Node | number} x - The parameter.
  4106. * @returns {Node}
  4107. */
  4108. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  4109. /**
  4110. * Returns the partial derivative of the parameter with respect to y.
  4111. *
  4112. * @tsl
  4113. * @function
  4114. * @param {Node | number} x - The parameter.
  4115. * @returns {Node}
  4116. */
  4117. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  4118. /**
  4119. * Rounds the parameter to the nearest integer.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node | number} x - The parameter.
  4124. * @returns {Node}
  4125. */
  4126. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  4127. /**
  4128. * Returns the reciprocal of the parameter `(1/x)`.
  4129. *
  4130. * @tsl
  4131. * @function
  4132. * @param {Node | number} x - The parameter.
  4133. * @returns {Node}
  4134. */
  4135. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  4136. /**
  4137. * Truncates the parameter, removing the fractional part.
  4138. *
  4139. * @tsl
  4140. * @function
  4141. * @param {Node | number} x - The parameter.
  4142. * @returns {Node}
  4143. */
  4144. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  4145. /**
  4146. * Returns the sum of the absolute derivatives in x and y.
  4147. *
  4148. * @tsl
  4149. * @function
  4150. * @param {Node | number} x - The parameter.
  4151. * @returns {Node}
  4152. */
  4153. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4154. /**
  4155. * Returns the transpose of a matrix.
  4156. *
  4157. * @tsl
  4158. * @function
  4159. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4160. * @returns {Node}
  4161. */
  4162. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4163. // 2 inputs
  4164. /**
  4165. * Reinterpret the bit representation of a value in one type as a value in another type.
  4166. *
  4167. * @tsl
  4168. * @function
  4169. * @param {Node | number} x - The parameter.
  4170. * @param {string} y - The new type.
  4171. * @returns {Node}
  4172. */
  4173. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4174. /**
  4175. * Returns `true` if `x` equals `y`.
  4176. *
  4177. * @tsl
  4178. * @function
  4179. * @param {Node | number} x - The first parameter.
  4180. * @param {Node | number} y - The second parameter.
  4181. * @returns {Node<bool>}
  4182. */
  4183. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4184. /**
  4185. * Returns the lesser of two values.
  4186. *
  4187. * @tsl
  4188. * @function
  4189. * @param {Node | number} x - The y parameter.
  4190. * @param {Node | number} y - The x parameter.
  4191. * @returns {Node}
  4192. */
  4193. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4194. /**
  4195. * Returns the greater of two values.
  4196. *
  4197. * @tsl
  4198. * @function
  4199. * @param {Node | number} x - The y parameter.
  4200. * @param {Node | number} y - The x parameter.
  4201. * @returns {Node}
  4202. */
  4203. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4204. /**
  4205. * Computes the remainder of dividing the first node by the second one.
  4206. *
  4207. * @tsl
  4208. * @function
  4209. * @param {Node | number} x - The y parameter.
  4210. * @param {Node | number} y - The x parameter.
  4211. * @returns {Node}
  4212. */
  4213. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4214. /**
  4215. * Generate a step function by comparing two values.
  4216. *
  4217. * @tsl
  4218. * @function
  4219. * @param {Node | number} x - The y parameter.
  4220. * @param {Node | number} y - The x parameter.
  4221. * @returns {Node}
  4222. */
  4223. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4224. /**
  4225. * Calculates the reflection direction for an incident vector.
  4226. *
  4227. * @tsl
  4228. * @function
  4229. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4230. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4231. * @returns {Node<vec2|vec3|vec4>}
  4232. */
  4233. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4234. /**
  4235. * Calculates the distance between two points.
  4236. *
  4237. * @tsl
  4238. * @function
  4239. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4240. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4241. * @returns {Node<float>}
  4242. */
  4243. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4244. /**
  4245. * Calculates the absolute difference between two values.
  4246. *
  4247. * @tsl
  4248. * @function
  4249. * @param {Node | number} x - The first parameter.
  4250. * @param {Node | number} y - The second parameter.
  4251. * @returns {Node}
  4252. */
  4253. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4254. /**
  4255. * Calculates the dot product of two vectors.
  4256. *
  4257. * @tsl
  4258. * @function
  4259. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4260. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4261. * @returns {Node<float>}
  4262. */
  4263. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4264. /**
  4265. * Calculates the cross product of two vectors.
  4266. *
  4267. * @tsl
  4268. * @function
  4269. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4270. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4271. * @returns {Node<vec2|vec3|vec4>}
  4272. */
  4273. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4274. /**
  4275. * Return the value of the first parameter raised to the power of the second one.
  4276. *
  4277. * @tsl
  4278. * @function
  4279. * @param {Node | number} x - The first parameter.
  4280. * @param {Node | number} y - The second parameter.
  4281. * @returns {Node}
  4282. */
  4283. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4284. /**
  4285. * Returns the square of the parameter.
  4286. *
  4287. * @tsl
  4288. * @function
  4289. * @param {Node | number} x - The first parameter.
  4290. * @returns {Node}
  4291. */
  4292. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4293. /**
  4294. * Returns the cube of the parameter.
  4295. *
  4296. * @tsl
  4297. * @function
  4298. * @param {Node | number} x - The first parameter.
  4299. * @returns {Node}
  4300. */
  4301. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4302. /**
  4303. * Returns the fourth power of the parameter.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node | number} x - The first parameter.
  4308. * @returns {Node}
  4309. */
  4310. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4311. /**
  4312. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4313. *
  4314. * @tsl
  4315. * @function
  4316. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4317. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4318. * @returns {Node}
  4319. */
  4320. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4321. /**
  4322. * Returns the cube root of a number.
  4323. *
  4324. * @tsl
  4325. * @function
  4326. * @param {Node | number} a - The first parameter.
  4327. * @returns {Node}
  4328. */
  4329. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4330. /**
  4331. * Calculate the squared length of a vector.
  4332. *
  4333. * @tsl
  4334. * @function
  4335. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4336. * @returns {Node<float>}
  4337. */
  4338. const lengthSq = ( a ) => dot( a, a );
  4339. /**
  4340. * Linearly interpolates between two values.
  4341. *
  4342. * @tsl
  4343. * @function
  4344. * @param {Node | number} a - The first parameter.
  4345. * @param {Node | number} b - The second parameter.
  4346. * @param {Node | number} t - The interpolation value.
  4347. * @returns {Node}
  4348. */
  4349. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4350. /**
  4351. * Constrains a value to lie between two further values.
  4352. *
  4353. * @tsl
  4354. * @function
  4355. * @param {Node | number} value - The value to constrain.
  4356. * @param {Node | number} [low=0] - The lower bound.
  4357. * @param {Node | number} [high=1] - The upper bound.
  4358. * @returns {Node}
  4359. */
  4360. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4361. /**
  4362. * Constrains a value between `0` and `1`.
  4363. *
  4364. * @tsl
  4365. * @function
  4366. * @param {Node | number} value - The value to constrain.
  4367. * @returns {Node}
  4368. */
  4369. const saturate = ( value ) => clamp( value );
  4370. /**
  4371. * Calculates the refraction direction for an incident vector.
  4372. *
  4373. * @tsl
  4374. * @function
  4375. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4376. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4377. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4378. * @returns {Node<vec2|vec3|vec4>}
  4379. */
  4380. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4381. /**
  4382. * Performs a Hermite interpolation between two values.
  4383. *
  4384. * @tsl
  4385. * @function
  4386. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4387. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4388. * @param {Node | number} x - The source value for interpolation.
  4389. * @returns {Node}
  4390. */
  4391. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4392. /**
  4393. * Returns a vector pointing in the same direction as another.
  4394. *
  4395. * @tsl
  4396. * @function
  4397. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4398. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4399. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4400. * @returns {Node<vec2|vec3|vec4>}
  4401. */
  4402. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4403. /**
  4404. * Returns a random value for the given uv.
  4405. *
  4406. * @tsl
  4407. * @function
  4408. * @param {Node<vec2>} uv - The uv node.
  4409. * @returns {Node<float>}
  4410. */
  4411. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4412. const a = 12.9898, b = 78.233, c = 43758.5453;
  4413. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4414. return fract( sin( sn ).mul( c ) );
  4415. } );
  4416. /**
  4417. * Alias for `mix()` with a different parameter order.
  4418. *
  4419. * @tsl
  4420. * @function
  4421. * @param {Node | number} t - The interpolation value.
  4422. * @param {Node | number} e1 - The first parameter.
  4423. * @param {Node | number} e2 - The second parameter.
  4424. * @returns {Node}
  4425. */
  4426. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4427. /**
  4428. * Alias for `smoothstep()` with a different parameter order.
  4429. *
  4430. * @tsl
  4431. * @function
  4432. * @param {Node | number} x - The source value for interpolation.
  4433. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4434. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4435. * @returns {Node}
  4436. */
  4437. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4438. /**
  4439. * Returns the arc-tangent of the quotient of its parameters.
  4440. *
  4441. * @tsl
  4442. * @function
  4443. * @deprecated since r172. Use {@link atan} instead.
  4444. *
  4445. * @param {Node | number} y - The y parameter.
  4446. * @param {Node | number} x - The x parameter.
  4447. * @returns {Node}
  4448. */
  4449. const atan2 = ( y, x ) => { // @deprecated, r172
  4450. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4451. return atan( y, x );
  4452. };
  4453. // GLSL alias function
  4454. const faceforward = faceForward;
  4455. const inversesqrt = inverseSqrt;
  4456. // Method chaining
  4457. addMethodChaining( 'all', all );
  4458. addMethodChaining( 'any', any );
  4459. addMethodChaining( 'equals', equals );
  4460. addMethodChaining( 'radians', radians );
  4461. addMethodChaining( 'degrees', degrees );
  4462. addMethodChaining( 'exp', exp );
  4463. addMethodChaining( 'exp2', exp2 );
  4464. addMethodChaining( 'log', log );
  4465. addMethodChaining( 'log2', log2 );
  4466. addMethodChaining( 'sqrt', sqrt );
  4467. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4468. addMethodChaining( 'floor', floor );
  4469. addMethodChaining( 'ceil', ceil );
  4470. addMethodChaining( 'normalize', normalize );
  4471. addMethodChaining( 'fract', fract );
  4472. addMethodChaining( 'sin', sin );
  4473. addMethodChaining( 'cos', cos );
  4474. addMethodChaining( 'tan', tan );
  4475. addMethodChaining( 'asin', asin );
  4476. addMethodChaining( 'acos', acos );
  4477. addMethodChaining( 'atan', atan );
  4478. addMethodChaining( 'abs', abs );
  4479. addMethodChaining( 'sign', sign );
  4480. addMethodChaining( 'length', length );
  4481. addMethodChaining( 'lengthSq', lengthSq );
  4482. addMethodChaining( 'negate', negate );
  4483. addMethodChaining( 'oneMinus', oneMinus );
  4484. addMethodChaining( 'dFdx', dFdx );
  4485. addMethodChaining( 'dFdy', dFdy );
  4486. addMethodChaining( 'round', round );
  4487. addMethodChaining( 'reciprocal', reciprocal );
  4488. addMethodChaining( 'trunc', trunc );
  4489. addMethodChaining( 'fwidth', fwidth );
  4490. addMethodChaining( 'atan2', atan2 );
  4491. addMethodChaining( 'min', min$1 );
  4492. addMethodChaining( 'max', max$1 );
  4493. addMethodChaining( 'mod', mod );
  4494. addMethodChaining( 'step', step );
  4495. addMethodChaining( 'reflect', reflect );
  4496. addMethodChaining( 'distance', distance );
  4497. addMethodChaining( 'dot', dot );
  4498. addMethodChaining( 'cross', cross );
  4499. addMethodChaining( 'pow', pow );
  4500. addMethodChaining( 'pow2', pow2 );
  4501. addMethodChaining( 'pow3', pow3 );
  4502. addMethodChaining( 'pow4', pow4 );
  4503. addMethodChaining( 'transformDirection', transformDirection );
  4504. addMethodChaining( 'mix', mixElement );
  4505. addMethodChaining( 'clamp', clamp );
  4506. addMethodChaining( 'refract', refract );
  4507. addMethodChaining( 'smoothstep', smoothstepElement );
  4508. addMethodChaining( 'faceForward', faceForward );
  4509. addMethodChaining( 'difference', difference );
  4510. addMethodChaining( 'saturate', saturate );
  4511. addMethodChaining( 'cbrt', cbrt );
  4512. addMethodChaining( 'transpose', transpose );
  4513. addMethodChaining( 'rand', rand );
  4514. /**
  4515. * Represents a logical `if/else` statement. Can be used as an alternative
  4516. * to the `If()`/`Else()` syntax.
  4517. *
  4518. * The corresponding TSL `select()` looks like so:
  4519. * ```js
  4520. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4521. * ```
  4522. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4523. * determine the outcome of the entire statement.
  4524. *
  4525. * @augments Node
  4526. */
  4527. class ConditionalNode extends Node {
  4528. static get type() {
  4529. return 'ConditionalNode';
  4530. }
  4531. /**
  4532. * Constructs a new conditional node.
  4533. *
  4534. * @param {Node} condNode - The node that defines the condition.
  4535. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4536. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4537. */
  4538. constructor( condNode, ifNode, elseNode = null ) {
  4539. super();
  4540. /**
  4541. * The node that defines the condition.
  4542. *
  4543. * @type {Node}
  4544. */
  4545. this.condNode = condNode;
  4546. /**
  4547. * The node that is evaluate when the condition ends up `true`.
  4548. *
  4549. * @type {Node}
  4550. */
  4551. this.ifNode = ifNode;
  4552. /**
  4553. * The node that is evaluate when the condition ends up `false`.
  4554. *
  4555. * @type {?Node}
  4556. * @default null
  4557. */
  4558. this.elseNode = elseNode;
  4559. }
  4560. /**
  4561. * This method is overwritten since the node type is inferred from the if/else
  4562. * nodes.
  4563. *
  4564. * @param {NodeBuilder} builder - The current node builder.
  4565. * @return {string} The node type.
  4566. */
  4567. getNodeType( builder ) {
  4568. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4569. if ( ifNode === undefined ) {
  4570. // fallback setup
  4571. this.setup( builder );
  4572. return this.getNodeType( builder );
  4573. }
  4574. const ifType = ifNode.getNodeType( builder );
  4575. if ( elseNode !== null ) {
  4576. const elseType = elseNode.getNodeType( builder );
  4577. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4578. return elseType;
  4579. }
  4580. }
  4581. return ifType;
  4582. }
  4583. setup( builder ) {
  4584. const condNode = this.condNode.cache();
  4585. const ifNode = this.ifNode.cache();
  4586. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4587. //
  4588. const currentNodeBlock = builder.context.nodeBlock;
  4589. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4590. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4591. //
  4592. const properties = builder.getNodeProperties( this );
  4593. properties.condNode = condNode;
  4594. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4595. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4596. }
  4597. generate( builder, output ) {
  4598. const type = this.getNodeType( builder );
  4599. const nodeData = builder.getDataFromNode( this );
  4600. if ( nodeData.nodeProperty !== undefined ) {
  4601. return nodeData.nodeProperty;
  4602. }
  4603. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4604. const needsOutput = output !== 'void';
  4605. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4606. nodeData.nodeProperty = nodeProperty;
  4607. const nodeSnippet = condNode.build( builder, 'bool' );
  4608. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4609. let ifSnippet = ifNode.build( builder, type );
  4610. if ( ifSnippet ) {
  4611. if ( needsOutput ) {
  4612. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4613. } else {
  4614. ifSnippet = 'return ' + ifSnippet + ';';
  4615. }
  4616. }
  4617. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4618. if ( elseNode !== null ) {
  4619. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4620. let elseSnippet = elseNode.build( builder, type );
  4621. if ( elseSnippet ) {
  4622. if ( needsOutput ) {
  4623. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4624. } else {
  4625. elseSnippet = 'return ' + elseSnippet + ';';
  4626. }
  4627. }
  4628. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4629. } else {
  4630. builder.addFlowCode( '\n\n' );
  4631. }
  4632. return builder.format( nodeProperty, type, output );
  4633. }
  4634. }
  4635. /**
  4636. * TSL function for creating a conditional node.
  4637. *
  4638. * @tsl
  4639. * @function
  4640. * @param {Node} condNode - The node that defines the condition.
  4641. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4642. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4643. * @returns {ConditionalNode}
  4644. */
  4645. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4646. addMethodChaining( 'select', select );
  4647. // Deprecated
  4648. /**
  4649. * @tsl
  4650. * @function
  4651. * @deprecated since r168. Use {@link select} instead.
  4652. *
  4653. * @param {...any} params
  4654. * @returns {ConditionalNode}
  4655. */
  4656. const cond = ( ...params ) => { // @deprecated, r168
  4657. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4658. return select( ...params );
  4659. };
  4660. addMethodChaining( 'cond', cond );
  4661. /**
  4662. * This node can be used as a context management component for another node.
  4663. * {@link NodeBuilder} performs its node building process in a specific context and
  4664. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4665. *
  4666. * ```js
  4667. *node.context( { getUV: () => customCoord } );
  4668. *```
  4669. * @augments Node
  4670. */
  4671. class ContextNode extends Node {
  4672. static get type() {
  4673. return 'ContextNode';
  4674. }
  4675. /**
  4676. * Constructs a new context node.
  4677. *
  4678. * @param {Node} node - The node whose context should be modified.
  4679. * @param {Object} [value={}] - The modified context data.
  4680. */
  4681. constructor( node, value = {} ) {
  4682. super();
  4683. /**
  4684. * This flag can be used for type testing.
  4685. *
  4686. * @type {boolean}
  4687. * @readonly
  4688. * @default true
  4689. */
  4690. this.isContextNode = true;
  4691. /**
  4692. * The node whose context should be modified.
  4693. *
  4694. * @type {Node}
  4695. */
  4696. this.node = node;
  4697. /**
  4698. * The modified context data.
  4699. *
  4700. * @type {Object}
  4701. * @default {}
  4702. */
  4703. this.value = value;
  4704. }
  4705. /**
  4706. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4707. *
  4708. * @return {Node} A reference to {@link ContextNode#node}.
  4709. */
  4710. getScope() {
  4711. return this.node.getScope();
  4712. }
  4713. /**
  4714. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  4715. *
  4716. * @param {NodeBuilder} builder - The current node builder.
  4717. * @return {string} The node type.
  4718. */
  4719. getNodeType( builder ) {
  4720. return this.node.getNodeType( builder );
  4721. }
  4722. analyze( builder ) {
  4723. this.node.build( builder );
  4724. }
  4725. setup( builder ) {
  4726. const previousContext = builder.getContext();
  4727. builder.setContext( { ...builder.context, ...this.value } );
  4728. const node = this.node.build( builder );
  4729. builder.setContext( previousContext );
  4730. return node;
  4731. }
  4732. generate( builder, output ) {
  4733. const previousContext = builder.getContext();
  4734. builder.setContext( { ...builder.context, ...this.value } );
  4735. const snippet = this.node.build( builder, output );
  4736. builder.setContext( previousContext );
  4737. return snippet;
  4738. }
  4739. }
  4740. /**
  4741. * TSL function for creating a context node.
  4742. *
  4743. * @tsl
  4744. * @function
  4745. * @param {Node} node - The node whose context should be modified.
  4746. * @param {Object} [value={}] - The modified context data.
  4747. * @returns {ContextNode}
  4748. */
  4749. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4750. /**
  4751. * TSL function for defining a label context value for a given node.
  4752. *
  4753. * @tsl
  4754. * @function
  4755. * @param {Node} node - The node whose context should be modified.
  4756. * @param {string} name - The name/label to set.
  4757. * @returns {ContextNode}
  4758. */
  4759. const label = ( node, name ) => context( node, { label: name } );
  4760. addMethodChaining( 'context', context );
  4761. addMethodChaining( 'label', label );
  4762. /**
  4763. * Class for representing shader variables as nodes. Variables are created from
  4764. * existing nodes like the following:
  4765. *
  4766. * ```js
  4767. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4768. * ```
  4769. *
  4770. * @augments Node
  4771. */
  4772. class VarNode extends Node {
  4773. static get type() {
  4774. return 'VarNode';
  4775. }
  4776. /**
  4777. * Constructs a new variable node.
  4778. *
  4779. * @param {Node} node - The node for which a variable should be created.
  4780. * @param {?string} name - The name of the variable in the shader.
  4781. * @param {?boolean} readOnly - The read-only flag.
  4782. */
  4783. constructor( node, name = null, readOnly = false ) {
  4784. super();
  4785. /**
  4786. * The node for which a variable should be created.
  4787. *
  4788. * @type {Node}
  4789. */
  4790. this.node = node;
  4791. /**
  4792. * The name of the variable in the shader. If no name is defined,
  4793. * the node system auto-generates one.
  4794. *
  4795. * @type {?string}
  4796. * @default null
  4797. */
  4798. this.name = name;
  4799. /**
  4800. * `VarNode` sets this property to `true` by default.
  4801. *
  4802. * @type {boolean}
  4803. * @default true
  4804. */
  4805. this.global = true;
  4806. /**
  4807. * This flag can be used for type testing.
  4808. *
  4809. * @type {boolean}
  4810. * @readonly
  4811. * @default true
  4812. */
  4813. this.isVarNode = true;
  4814. /**
  4815. *
  4816. * The read-only flag.
  4817. *
  4818. * @type {boolean}
  4819. * @default false
  4820. */
  4821. this.readOnly = readOnly;
  4822. }
  4823. getHash( builder ) {
  4824. return this.name || super.getHash( builder );
  4825. }
  4826. getMemberType( builder, name ) {
  4827. return this.node.getMemberType( builder, name );
  4828. }
  4829. getElementType( builder ) {
  4830. return this.node.getElementType( builder );
  4831. }
  4832. getNodeType( builder ) {
  4833. return this.node.getNodeType( builder );
  4834. }
  4835. generate( builder ) {
  4836. const { node, name, readOnly } = this;
  4837. const { renderer } = builder;
  4838. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4839. let isDeterministic = false;
  4840. let shouldTreatAsReadOnly = false;
  4841. if ( readOnly ) {
  4842. isDeterministic = builder.isDeterministic( node );
  4843. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4844. }
  4845. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4846. const snippet = node.build( builder, vectorType );
  4847. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4848. const propertyName = builder.getPropertyName( nodeVar );
  4849. let declarationPrefix = propertyName;
  4850. if ( shouldTreatAsReadOnly ) {
  4851. if ( isWebGPUBackend ) {
  4852. declarationPrefix = isDeterministic
  4853. ? `const ${ propertyName }`
  4854. : `let ${ propertyName }`;
  4855. } else {
  4856. const count = builder.getArrayCount( node );
  4857. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4858. }
  4859. }
  4860. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4861. return propertyName;
  4862. }
  4863. }
  4864. /**
  4865. * TSL function for creating a var node.
  4866. *
  4867. * @tsl
  4868. * @function
  4869. * @param {Node} node - The node for which a variable should be created.
  4870. * @param {?string} name - The name of the variable in the shader.
  4871. * @returns {VarNode}
  4872. */
  4873. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4874. /**
  4875. * TSL function for creating a var node.
  4876. *
  4877. * @tsl
  4878. * @function
  4879. * @param {Node} node - The node for which a variable should be created.
  4880. * @param {?string} name - The name of the variable in the shader.
  4881. * @returns {VarNode}
  4882. */
  4883. const Var = ( node, name = null ) => createVar( node, name ).append();
  4884. /**
  4885. * TSL function for creating a const node.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node} node - The node for which a constant should be created.
  4890. * @param {?string} name - The name of the constant in the shader.
  4891. * @returns {VarNode}
  4892. */
  4893. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4894. // Method chaining
  4895. addMethodChaining( 'toVar', Var );
  4896. addMethodChaining( 'toConst', Const );
  4897. // Deprecated
  4898. /**
  4899. * @tsl
  4900. * @function
  4901. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4902. *
  4903. * @param {any} node
  4904. * @returns {VarNode}
  4905. */
  4906. const temp = ( node ) => { // @deprecated, r170
  4907. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4908. return createVar( node );
  4909. };
  4910. addMethodChaining( 'temp', temp );
  4911. /**
  4912. * Class for representing shader varyings as nodes. Varyings are create from
  4913. * existing nodes like the following:
  4914. *
  4915. * ```js
  4916. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4917. * ```
  4918. *
  4919. * @augments Node
  4920. */
  4921. class VaryingNode extends Node {
  4922. static get type() {
  4923. return 'VaryingNode';
  4924. }
  4925. /**
  4926. * Constructs a new varying node.
  4927. *
  4928. * @param {Node} node - The node for which a varying should be created.
  4929. * @param {?string} name - The name of the varying in the shader.
  4930. */
  4931. constructor( node, name = null ) {
  4932. super();
  4933. /**
  4934. * The node for which a varying should be created.
  4935. *
  4936. * @type {Node}
  4937. */
  4938. this.node = node;
  4939. /**
  4940. * The name of the varying in the shader. If no name is defined,
  4941. * the node system auto-generates one.
  4942. *
  4943. * @type {?string}
  4944. * @default null
  4945. */
  4946. this.name = name;
  4947. /**
  4948. * This flag can be used for type testing.
  4949. *
  4950. * @type {boolean}
  4951. * @readonly
  4952. * @default true
  4953. */
  4954. this.isVaryingNode = true;
  4955. }
  4956. /**
  4957. * The method is overwritten so it always returns `true`.
  4958. *
  4959. * @param {NodeBuilder} builder - The current node builder.
  4960. * @return {boolean} Whether this node is global or not.
  4961. */
  4962. isGlobal( /*builder*/ ) {
  4963. return true;
  4964. }
  4965. getHash( builder ) {
  4966. return this.name || super.getHash( builder );
  4967. }
  4968. getNodeType( builder ) {
  4969. // VaryingNode is auto type
  4970. return this.node.getNodeType( builder );
  4971. }
  4972. /**
  4973. * This method performs the setup of a varying node with the current node builder.
  4974. *
  4975. * @param {NodeBuilder} builder - The current node builder.
  4976. * @return {NodeVarying} The node varying from the node builder.
  4977. */
  4978. setupVarying( builder ) {
  4979. const properties = builder.getNodeProperties( this );
  4980. let varying = properties.varying;
  4981. if ( varying === undefined ) {
  4982. const name = this.name;
  4983. const type = this.getNodeType( builder );
  4984. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4985. properties.node = this.node;
  4986. }
  4987. // this property can be used to check if the varying can be optimized for a variable
  4988. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4989. return varying;
  4990. }
  4991. setup( builder ) {
  4992. this.setupVarying( builder );
  4993. }
  4994. analyze( builder ) {
  4995. this.setupVarying( builder );
  4996. return this.node.analyze( builder );
  4997. }
  4998. generate( builder ) {
  4999. const properties = builder.getNodeProperties( this );
  5000. const varying = this.setupVarying( builder );
  5001. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5002. if ( properties.propertyName === undefined || needsReassign ) {
  5003. const type = this.getNodeType( builder );
  5004. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5005. // force node run in vertex stage
  5006. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5007. properties.propertyName = propertyName;
  5008. if ( needsReassign ) {
  5009. // once reassign varying in fragment stage
  5010. properties.reassignPosition = false;
  5011. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5012. properties.reassignPosition = true;
  5013. }
  5014. }
  5015. return builder.getPropertyName( varying );
  5016. }
  5017. }
  5018. /**
  5019. * TSL function for creating a varying node.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node} node - The node for which a varying should be created.
  5024. * @param {?string} name - The name of the varying in the shader.
  5025. * @returns {VaryingNode}
  5026. */
  5027. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  5028. /**
  5029. * Computes a node in the vertex stage.
  5030. *
  5031. * @tsl
  5032. * @function
  5033. * @param {Node} node - The node which should be executed in the vertex stage.
  5034. * @returns {VaryingNode}
  5035. */
  5036. const vertexStage = ( node ) => varying( node );
  5037. addMethodChaining( 'toVarying', varying );
  5038. addMethodChaining( 'toVertexStage', vertexStage );
  5039. // Deprecated
  5040. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5041. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  5042. return varying( ...params );
  5043. } );
  5044. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5045. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  5046. return varying( ...params );
  5047. } );
  5048. /**
  5049. * Converts the given color value from sRGB to linear-sRGB color space.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node<vec3>} color - The sRGB color.
  5054. * @return {Node<vec3>} The linear-sRGB color.
  5055. */
  5056. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5057. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5058. const b = color.mul( 0.0773993808 );
  5059. const factor = color.lessThanEqual( 0.04045 );
  5060. const rgbResult = mix( a, b, factor );
  5061. return rgbResult;
  5062. } ).setLayout( {
  5063. name: 'sRGBTransferEOTF',
  5064. type: 'vec3',
  5065. inputs: [
  5066. { name: 'color', type: 'vec3' }
  5067. ]
  5068. } );
  5069. /**
  5070. * Converts the given color value from linear-sRGB to sRGB color space.
  5071. *
  5072. * @tsl
  5073. * @function
  5074. * @param {Node<vec3>} color - The linear-sRGB color.
  5075. * @return {Node<vec3>} The sRGB color.
  5076. */
  5077. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5078. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5079. const b = color.mul( 12.92 );
  5080. const factor = color.lessThanEqual( 0.0031308 );
  5081. const rgbResult = mix( a, b, factor );
  5082. return rgbResult;
  5083. } ).setLayout( {
  5084. name: 'sRGBTransferOETF',
  5085. type: 'vec3',
  5086. inputs: [
  5087. { name: 'color', type: 'vec3' }
  5088. ]
  5089. } );
  5090. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5091. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5092. /**
  5093. * This node represents a color space conversion. Meaning it converts
  5094. * a color value from a source to a target color space.
  5095. *
  5096. * @augments TempNode
  5097. */
  5098. class ColorSpaceNode extends TempNode {
  5099. static get type() {
  5100. return 'ColorSpaceNode';
  5101. }
  5102. /**
  5103. * Constructs a new color space node.
  5104. *
  5105. * @param {Node} colorNode - Represents the color to convert.
  5106. * @param {string} source - The source color space.
  5107. * @param {string} target - The target color space.
  5108. */
  5109. constructor( colorNode, source, target ) {
  5110. super( 'vec4' );
  5111. /**
  5112. * Represents the color to convert.
  5113. *
  5114. * @type {Node}
  5115. */
  5116. this.colorNode = colorNode;
  5117. /**
  5118. * The source color space.
  5119. *
  5120. * @type {string}
  5121. */
  5122. this.source = source;
  5123. /**
  5124. * The target color space.
  5125. *
  5126. * @type {string}
  5127. */
  5128. this.target = target;
  5129. }
  5130. /**
  5131. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5132. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5133. * color management and renderer.
  5134. *
  5135. * @param {NodeBuilder} builder - The current node builder.
  5136. * @param {string} colorSpace - The color space to resolve.
  5137. * @return {string} The resolved color space.
  5138. */
  5139. resolveColorSpace( builder, colorSpace ) {
  5140. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5141. return ColorManagement.workingColorSpace;
  5142. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5143. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5144. }
  5145. return colorSpace;
  5146. }
  5147. setup( builder ) {
  5148. const { colorNode } = this;
  5149. const source = this.resolveColorSpace( builder, this.source );
  5150. const target = this.resolveColorSpace( builder, this.target );
  5151. let outputNode = colorNode;
  5152. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5153. return outputNode;
  5154. }
  5155. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5156. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5157. }
  5158. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5159. outputNode = vec4(
  5160. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5161. outputNode.a
  5162. );
  5163. }
  5164. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5165. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5166. }
  5167. return outputNode;
  5168. }
  5169. }
  5170. /**
  5171. * TSL function for converting a given color node to the current output color space.
  5172. *
  5173. * @tsl
  5174. * @function
  5175. * @param {Node} node - Represents the node to convert.
  5176. * @returns {ColorSpaceNode}
  5177. */
  5178. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5179. /**
  5180. * TSL function for converting a given color node to the current working color space.
  5181. *
  5182. * @tsl
  5183. * @function
  5184. * @param {Node} node - Represents the node to convert.
  5185. * @returns {ColorSpaceNode}
  5186. */
  5187. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5188. /**
  5189. * TSL function for converting a given color node from the current working color space to the given color space.
  5190. *
  5191. * @tsl
  5192. * @function
  5193. * @param {Node} node - Represents the node to convert.
  5194. * @param {string} colorSpace - The target color space.
  5195. * @returns {ColorSpaceNode}
  5196. */
  5197. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5198. /**
  5199. * TSL function for converting a given color node from the given color space to the current working color space.
  5200. *
  5201. * @tsl
  5202. * @function
  5203. * @param {Node} node - Represents the node to convert.
  5204. * @param {string} colorSpace - The source color space.
  5205. * @returns {ColorSpaceNode}
  5206. */
  5207. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5208. /**
  5209. * TSL function for converting a given color node from one color space to another one.
  5210. *
  5211. * @tsl
  5212. * @function
  5213. * @param {Node} node - Represents the node to convert.
  5214. * @param {string} sourceColorSpace - The source color space.
  5215. * @param {string} targetColorSpace - The target color space.
  5216. * @returns {ColorSpaceNode}
  5217. */
  5218. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5219. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5220. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5221. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5222. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5223. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5224. /**
  5225. * This class is only relevant if the referenced property is array-like.
  5226. * In this case, `ReferenceElementNode` allows to refer to a specific
  5227. * element inside the data structure via an index.
  5228. *
  5229. * @augments ArrayElementNode
  5230. */
  5231. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5232. static get type() {
  5233. return 'ReferenceElementNode';
  5234. }
  5235. /**
  5236. * Constructs a new reference element node.
  5237. *
  5238. * @param {?ReferenceBaseNode} referenceNode - The reference node.
  5239. * @param {Node} indexNode - The index node that defines the element access.
  5240. */
  5241. constructor( referenceNode, indexNode ) {
  5242. super( referenceNode, indexNode );
  5243. /**
  5244. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5245. * property references to the current node.
  5246. *
  5247. * @type {?ReferenceBaseNode}
  5248. * @default null
  5249. */
  5250. this.referenceNode = referenceNode;
  5251. /**
  5252. * This flag can be used for type testing.
  5253. *
  5254. * @type {boolean}
  5255. * @readonly
  5256. * @default true
  5257. */
  5258. this.isReferenceElementNode = true;
  5259. }
  5260. /**
  5261. * This method is overwritten since the node type is inferred from
  5262. * the uniform type of the reference node.
  5263. *
  5264. * @return {string} The node type.
  5265. */
  5266. getNodeType() {
  5267. return this.referenceNode.uniformType;
  5268. }
  5269. generate( builder ) {
  5270. const snippet = super.generate( builder );
  5271. const arrayType = this.referenceNode.getNodeType();
  5272. const elementType = this.getNodeType();
  5273. return builder.format( snippet, arrayType, elementType );
  5274. }
  5275. };
  5276. /**
  5277. * Base class for nodes which establishes a reference to a property of another object.
  5278. * In this way, the value of the node is automatically linked to the value of
  5279. * referenced object. Reference nodes internally represent the linked value
  5280. * as a uniform.
  5281. *
  5282. * @augments Node
  5283. */
  5284. class ReferenceBaseNode extends Node {
  5285. static get type() {
  5286. return 'ReferenceBaseNode';
  5287. }
  5288. /**
  5289. * Constructs a new reference base node.
  5290. *
  5291. * @param {string} property - The name of the property the node refers to.
  5292. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5293. * @param {?Object} [object=null] - The object the property belongs to.
  5294. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5295. */
  5296. constructor( property, uniformType, object = null, count = null ) {
  5297. super();
  5298. /**
  5299. * The name of the property the node refers to.
  5300. *
  5301. * @type {string}
  5302. */
  5303. this.property = property;
  5304. /**
  5305. * The uniform type that should be used to represent the property value.
  5306. *
  5307. * @type {string}
  5308. */
  5309. this.uniformType = uniformType;
  5310. /**
  5311. * The object the property belongs to.
  5312. *
  5313. * @type {?Object}
  5314. * @default null
  5315. */
  5316. this.object = object;
  5317. /**
  5318. * When the linked property is an array, this parameter defines its length.
  5319. *
  5320. * @type {?number}
  5321. * @default null
  5322. */
  5323. this.count = count;
  5324. /**
  5325. * The property name might have dots so nested properties can be referred.
  5326. * The hierarchy of the names is stored inside this array.
  5327. *
  5328. * @type {Array<string>}
  5329. */
  5330. this.properties = property.split( '.' );
  5331. /**
  5332. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5333. * since the final reference might be updated from calling code.
  5334. *
  5335. * @type {?Object}
  5336. * @default null
  5337. */
  5338. this.reference = object;
  5339. /**
  5340. * The uniform node that holds the value of the reference node.
  5341. *
  5342. * @type {UniformNode}
  5343. * @default null
  5344. */
  5345. this.node = null;
  5346. /**
  5347. * The uniform group of the internal uniform.
  5348. *
  5349. * @type {UniformGroupNode}
  5350. * @default null
  5351. */
  5352. this.group = null;
  5353. /**
  5354. * Overwritten since reference nodes are updated per object.
  5355. *
  5356. * @type {string}
  5357. * @default 'object'
  5358. */
  5359. this.updateType = NodeUpdateType.OBJECT;
  5360. }
  5361. /**
  5362. * Sets the uniform group for this reference node.
  5363. *
  5364. * @param {UniformGroupNode} group - The uniform group to set.
  5365. * @return {ReferenceBaseNode} A reference to this node.
  5366. */
  5367. setGroup( group ) {
  5368. this.group = group;
  5369. return this;
  5370. }
  5371. /**
  5372. * When the referred property is array-like, this method can be used
  5373. * to access elements via an index node.
  5374. *
  5375. * @param {IndexNode} indexNode - indexNode.
  5376. * @return {ReferenceElementNode} A reference to an element.
  5377. */
  5378. element( indexNode ) {
  5379. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5380. }
  5381. /**
  5382. * Sets the node type which automatically defines the internal
  5383. * uniform type.
  5384. *
  5385. * @param {string} uniformType - The type to set.
  5386. */
  5387. setNodeType( uniformType ) {
  5388. const node = uniform( null, uniformType ).getSelf();
  5389. if ( this.group !== null ) {
  5390. node.setGroup( this.group );
  5391. }
  5392. this.node = node;
  5393. }
  5394. /**
  5395. * This method is overwritten since the node type is inferred from
  5396. * the type of the reference node.
  5397. *
  5398. * @param {NodeBuilder} builder - The current node builder.
  5399. * @return {string} The node type.
  5400. */
  5401. getNodeType( builder ) {
  5402. if ( this.node === null ) {
  5403. this.updateReference( builder );
  5404. this.updateValue();
  5405. }
  5406. return this.node.getNodeType( builder );
  5407. }
  5408. /**
  5409. * Returns the property value from the given referred object.
  5410. *
  5411. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5412. * @return {any} The value.
  5413. */
  5414. getValueFromReference( object = this.reference ) {
  5415. const { properties } = this;
  5416. let value = object[ properties[ 0 ] ];
  5417. for ( let i = 1; i < properties.length; i ++ ) {
  5418. value = value[ properties[ i ] ];
  5419. }
  5420. return value;
  5421. }
  5422. /**
  5423. * Allows to update the reference based on the given state. The state is only
  5424. * evaluated {@link ReferenceBaseNode#object} is not set.
  5425. *
  5426. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5427. * @return {Object} The updated reference.
  5428. */
  5429. updateReference( state ) {
  5430. this.reference = this.object !== null ? this.object : state.object;
  5431. return this.reference;
  5432. }
  5433. /**
  5434. * The output of the reference node is the internal uniform node.
  5435. *
  5436. * @return {UniformNode} The output node.
  5437. */
  5438. setup() {
  5439. this.updateValue();
  5440. return this.node;
  5441. }
  5442. /**
  5443. * Overwritten to to update the internal uniform value.
  5444. *
  5445. * @param {NodeFrame} frame - A reference to the current node frame.
  5446. */
  5447. update( /*frame*/ ) {
  5448. this.updateValue();
  5449. }
  5450. /**
  5451. * Retrieves the value from the referred object property and uses it
  5452. * to updated the internal uniform.
  5453. */
  5454. updateValue() {
  5455. if ( this.node === null ) this.setNodeType( this.uniformType );
  5456. const value = this.getValueFromReference();
  5457. if ( Array.isArray( value ) ) {
  5458. this.node.array = value;
  5459. } else {
  5460. this.node.value = value;
  5461. }
  5462. }
  5463. }
  5464. /**
  5465. * TSL function for creating a reference base node.
  5466. *
  5467. * @tsl
  5468. * @function
  5469. * @param {string} name - The name of the property the node refers to.
  5470. * @param {string} type - The uniform type that should be used to represent the property value.
  5471. * @param {Object} object - The object the property belongs to.
  5472. * @returns {ReferenceBaseNode}
  5473. */
  5474. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5475. /**
  5476. * This node is a special type of reference node which is intended
  5477. * for linking renderer properties with node values.
  5478. * ```js
  5479. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5480. * ```
  5481. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5482. * automatically be updated.
  5483. *
  5484. * @augments ReferenceBaseNode
  5485. */
  5486. class RendererReferenceNode extends ReferenceBaseNode {
  5487. static get type() {
  5488. return 'RendererReferenceNode';
  5489. }
  5490. /**
  5491. * Constructs a new renderer reference node.
  5492. *
  5493. * @param {string} property - The name of the property the node refers to.
  5494. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5495. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5496. * the node refers to the renderer of the current state.
  5497. */
  5498. constructor( property, inputType, renderer = null ) {
  5499. super( property, inputType, renderer );
  5500. /**
  5501. * The renderer the property belongs to. When no renderer is set,
  5502. * the node refers to the renderer of the current state.
  5503. *
  5504. * @type {?Renderer}
  5505. * @default null
  5506. */
  5507. this.renderer = renderer;
  5508. this.setGroup( renderGroup );
  5509. }
  5510. /**
  5511. * Updates the reference based on the given state. The state is only evaluated
  5512. * {@link RendererReferenceNode#renderer} is not set.
  5513. *
  5514. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5515. * @return {Object} The updated reference.
  5516. */
  5517. updateReference( state ) {
  5518. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5519. return this.reference;
  5520. }
  5521. }
  5522. /**
  5523. * TSL function for creating a renderer reference node.
  5524. *
  5525. * @tsl
  5526. * @function
  5527. * @param {string} name - The name of the property the node refers to.
  5528. * @param {string} type - The uniform type that should be used to represent the property value.
  5529. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5530. * the node refers to the renderer of the current state.
  5531. * @returns {RendererReferenceNode}
  5532. */
  5533. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5534. /**
  5535. * This node represents a tone mapping operation.
  5536. *
  5537. * @augments TempNode
  5538. */
  5539. class ToneMappingNode extends TempNode {
  5540. static get type() {
  5541. return 'ToneMappingNode';
  5542. }
  5543. /**
  5544. * Constructs a new tone mapping node.
  5545. *
  5546. * @param {number} toneMapping - The tone mapping type.
  5547. * @param {Node} exposureNode - The tone mapping exposure.
  5548. * @param {Node} [colorNode=null] - The color node to process.
  5549. */
  5550. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5551. super( 'vec3' );
  5552. /**
  5553. * The tone mapping type.
  5554. *
  5555. * @type {number}
  5556. */
  5557. this.toneMapping = toneMapping;
  5558. /**
  5559. * The tone mapping exposure.
  5560. *
  5561. * @type {Node}
  5562. * @default null
  5563. */
  5564. this.exposureNode = exposureNode;
  5565. /**
  5566. * Represents the color to process.
  5567. *
  5568. * @type {?Node}
  5569. * @default null
  5570. */
  5571. this.colorNode = colorNode;
  5572. }
  5573. /**
  5574. * Overwrites the default `customCacheKey()` implementation by including the tone
  5575. * mapping type into the cache key.
  5576. *
  5577. * @return {number} The hash.
  5578. */
  5579. customCacheKey() {
  5580. return hash$1( this.toneMapping );
  5581. }
  5582. setup( builder ) {
  5583. const colorNode = this.colorNode || builder.context.color;
  5584. const toneMapping = this.toneMapping;
  5585. if ( toneMapping === NoToneMapping ) return colorNode;
  5586. let outputNode = null;
  5587. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5588. if ( toneMappingFn !== null ) {
  5589. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5590. } else {
  5591. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5592. outputNode = colorNode;
  5593. }
  5594. return outputNode;
  5595. }
  5596. }
  5597. /**
  5598. * TSL function for creating a tone mapping node.
  5599. *
  5600. * @tsl
  5601. * @function
  5602. * @param {number} mapping - The tone mapping type.
  5603. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5604. * @param {Node<vec3> | Color} color - The color node to process.
  5605. * @returns {ToneMappingNode<vec3>}
  5606. */
  5607. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5608. /**
  5609. * TSL object that represents the global tone mapping exposure of the renderer.
  5610. *
  5611. * @tsl
  5612. * @type {RendererReferenceNode<vec3>}
  5613. */
  5614. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5615. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5616. /**
  5617. * In earlier `three.js` versions it was only possible to define attribute data
  5618. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5619. * on the node level.
  5620. * ```js
  5621. * const geometry = new THREE.PlaneGeometry();
  5622. * const positionAttribute = geometry.getAttribute( 'position' );
  5623. *
  5624. * const colors = [];
  5625. * for ( let i = 0; i < position.count; i ++ ) {
  5626. * colors.push( 1, 0, 0 );
  5627. * }
  5628. *
  5629. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5630. * ```
  5631. * This new approach is especially interesting when geometry data are generated via
  5632. * compute shaders. The below line converts a storage buffer into an attribute node.
  5633. * ```js
  5634. * material.positionNode = positionBuffer.toAttribute();
  5635. * ```
  5636. * @augments InputNode
  5637. */
  5638. class BufferAttributeNode extends InputNode {
  5639. static get type() {
  5640. return 'BufferAttributeNode';
  5641. }
  5642. /**
  5643. * Constructs a new buffer attribute node.
  5644. *
  5645. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5646. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5647. * @param {number} [bufferStride=0] - The buffer stride.
  5648. * @param {number} [bufferOffset=0] - The buffer offset.
  5649. */
  5650. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5651. super( value, bufferType );
  5652. /**
  5653. * This flag can be used for type testing.
  5654. *
  5655. * @type {boolean}
  5656. * @readonly
  5657. * @default true
  5658. */
  5659. this.isBufferNode = true;
  5660. /**
  5661. * The buffer type (e.g. `'vec3'`).
  5662. *
  5663. * @type {string}
  5664. * @default null
  5665. */
  5666. this.bufferType = bufferType;
  5667. /**
  5668. * The buffer stride.
  5669. *
  5670. * @type {number}
  5671. * @default 0
  5672. */
  5673. this.bufferStride = bufferStride;
  5674. /**
  5675. * The buffer offset.
  5676. *
  5677. * @type {number}
  5678. * @default 0
  5679. */
  5680. this.bufferOffset = bufferOffset;
  5681. /**
  5682. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5683. * if you are planning to update the attribute data per frame.
  5684. *
  5685. * @type {number}
  5686. * @default StaticDrawUsage
  5687. */
  5688. this.usage = StaticDrawUsage;
  5689. /**
  5690. * Whether the attribute is instanced or not.
  5691. *
  5692. * @type {boolean}
  5693. * @default false
  5694. */
  5695. this.instanced = false;
  5696. /**
  5697. * A reference to the buffer attribute.
  5698. *
  5699. * @type {?BufferAttribute}
  5700. * @default null
  5701. */
  5702. this.attribute = null;
  5703. /**
  5704. * `BufferAttributeNode` sets this property to `true` by default.
  5705. *
  5706. * @type {boolean}
  5707. * @default true
  5708. */
  5709. this.global = true;
  5710. if ( value && value.isBufferAttribute === true ) {
  5711. this.attribute = value;
  5712. this.usage = value.usage;
  5713. this.instanced = value.isInstancedBufferAttribute;
  5714. }
  5715. }
  5716. /**
  5717. * This method is overwritten since the attribute data might be shared
  5718. * and thus the hash should be shared as well.
  5719. *
  5720. * @param {NodeBuilder} builder - The current node builder.
  5721. * @return {string} The hash.
  5722. */
  5723. getHash( builder ) {
  5724. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5725. let bufferData = builder.globalCache.getData( this.value );
  5726. if ( bufferData === undefined ) {
  5727. bufferData = {
  5728. node: this
  5729. };
  5730. builder.globalCache.setData( this.value, bufferData );
  5731. }
  5732. return bufferData.node.uuid;
  5733. }
  5734. return this.uuid;
  5735. }
  5736. /**
  5737. * This method is overwritten since the node type is inferred from
  5738. * the buffer attribute.
  5739. *
  5740. * @param {NodeBuilder} builder - The current node builder.
  5741. * @return {string} The node type.
  5742. */
  5743. getNodeType( builder ) {
  5744. if ( this.bufferType === null ) {
  5745. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5746. }
  5747. return this.bufferType;
  5748. }
  5749. /**
  5750. * Depending on which value was passed to the node, `setup()` behaves
  5751. * differently. If no instance of `BufferAttribute` was passed, the method
  5752. * creates an internal attribute and configures it respectively.
  5753. *
  5754. * @param {NodeBuilder} builder - The current node builder.
  5755. */
  5756. setup( builder ) {
  5757. if ( this.attribute !== null ) return;
  5758. const type = this.getNodeType( builder );
  5759. const array = this.value;
  5760. const itemSize = builder.getTypeLength( type );
  5761. const stride = this.bufferStride || itemSize;
  5762. const offset = this.bufferOffset;
  5763. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5764. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5765. buffer.setUsage( this.usage );
  5766. this.attribute = bufferAttribute;
  5767. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5768. }
  5769. /**
  5770. * Generates the code snippet of the buffer attribute node.
  5771. *
  5772. * @param {NodeBuilder} builder - The current node builder.
  5773. * @return {string} The generated code snippet.
  5774. */
  5775. generate( builder ) {
  5776. const nodeType = this.getNodeType( builder );
  5777. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5778. const propertyName = builder.getPropertyName( nodeAttribute );
  5779. let output = null;
  5780. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5781. this.name = propertyName;
  5782. output = propertyName;
  5783. } else {
  5784. const nodeVarying = varying( this );
  5785. output = nodeVarying.build( builder, nodeType );
  5786. }
  5787. return output;
  5788. }
  5789. /**
  5790. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5791. *
  5792. * @param {NodeBuilder} builder - The current node builder.
  5793. * @return {string} The input type.
  5794. */
  5795. getInputType( /*builder*/ ) {
  5796. return 'bufferAttribute';
  5797. }
  5798. /**
  5799. * Sets the `usage` property to the given value.
  5800. *
  5801. * @param {number} value - The usage to set.
  5802. * @return {BufferAttributeNode} A reference to this node.
  5803. */
  5804. setUsage( value ) {
  5805. this.usage = value;
  5806. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5807. this.attribute.usage = value;
  5808. }
  5809. return this;
  5810. }
  5811. /**
  5812. * Sets the `instanced` property to the given value.
  5813. *
  5814. * @param {boolean} value - The value to set.
  5815. * @return {BufferAttributeNode} A reference to this node.
  5816. */
  5817. setInstanced( value ) {
  5818. this.instanced = value;
  5819. return this;
  5820. }
  5821. }
  5822. /**
  5823. * TSL function for creating a buffer attribute node.
  5824. *
  5825. * @tsl
  5826. * @function
  5827. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5828. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5829. * @param {number} [stride=0] - The buffer stride.
  5830. * @param {number} [offset=0] - The buffer offset.
  5831. * @returns {BufferAttributeNode}
  5832. */
  5833. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5834. /**
  5835. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5836. * Use this function if attribute data are updated per frame.
  5837. *
  5838. * @tsl
  5839. * @function
  5840. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5841. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5842. * @param {number} [stride=0] - The buffer stride.
  5843. * @param {number} [offset=0] - The buffer offset.
  5844. * @returns {BufferAttributeNode}
  5845. */
  5846. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5847. /**
  5848. * TSL function for creating a buffer attribute node but with enabled instancing
  5849. *
  5850. * @tsl
  5851. * @function
  5852. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5853. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5854. * @param {number} [stride=0] - The buffer stride.
  5855. * @param {number} [offset=0] - The buffer offset.
  5856. * @returns {BufferAttributeNode}
  5857. */
  5858. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5859. /**
  5860. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5861. *
  5862. * @tsl
  5863. * @function
  5864. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5865. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5866. * @param {number} [stride=0] - The buffer stride.
  5867. * @param {number} [offset=0] - The buffer offset.
  5868. * @returns {BufferAttributeNode}
  5869. */
  5870. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5871. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5872. /**
  5873. * TODO
  5874. *
  5875. * @augments Node
  5876. */
  5877. class ComputeNode extends Node {
  5878. static get type() {
  5879. return 'ComputeNode';
  5880. }
  5881. /**
  5882. * Constructs a new compute node.
  5883. *
  5884. * @param {Node} computeNode - TODO
  5885. * @param {number} count - TODO.
  5886. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  5887. */
  5888. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5889. super( 'void' );
  5890. /**
  5891. * This flag can be used for type testing.
  5892. *
  5893. * @type {boolean}
  5894. * @readonly
  5895. * @default true
  5896. */
  5897. this.isComputeNode = true;
  5898. /**
  5899. * TODO
  5900. *
  5901. * @type {Node}
  5902. */
  5903. this.computeNode = computeNode;
  5904. /**
  5905. * TODO
  5906. *
  5907. * @type {number}
  5908. */
  5909. this.count = count;
  5910. /**
  5911. * TODO
  5912. *
  5913. * @type {Array<number>}
  5914. * @default [64]
  5915. */
  5916. this.workgroupSize = workgroupSize;
  5917. /**
  5918. * TODO
  5919. *
  5920. * @type {number}
  5921. */
  5922. this.dispatchCount = 0;
  5923. /**
  5924. * TODO
  5925. *
  5926. * @type {number}
  5927. */
  5928. this.version = 1;
  5929. /**
  5930. * The name or label of the uniform.
  5931. *
  5932. * @type {string}
  5933. * @default ''
  5934. */
  5935. this.name = '';
  5936. /**
  5937. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5938. * is executed once per object by default.
  5939. *
  5940. * @type {string}
  5941. * @default 'object'
  5942. */
  5943. this.updateBeforeType = NodeUpdateType.OBJECT;
  5944. /**
  5945. * TODO
  5946. *
  5947. * @type {Function}
  5948. */
  5949. this.onInitFunction = null;
  5950. this.updateDispatchCount();
  5951. }
  5952. /**
  5953. * Executes the `dispose` event for this node.
  5954. */
  5955. dispose() {
  5956. this.dispatchEvent( { type: 'dispose' } );
  5957. }
  5958. /**
  5959. * Sets the {@link ComputeNode#name} property.
  5960. *
  5961. * @param {string} name - The name of the uniform.
  5962. * @return {ComputeNode} A reference to this node.
  5963. */
  5964. label( name ) {
  5965. this.name = name;
  5966. return this;
  5967. }
  5968. /**
  5969. * TODO
  5970. */
  5971. updateDispatchCount() {
  5972. const { count, workgroupSize } = this;
  5973. let size = workgroupSize[ 0 ];
  5974. for ( let i = 1; i < workgroupSize.length; i ++ )
  5975. size *= workgroupSize[ i ];
  5976. this.dispatchCount = Math.ceil( count / size );
  5977. }
  5978. /**
  5979. * TODO
  5980. *
  5981. * @param {Function} callback - TODO.
  5982. * @return {ComputeNode} A reference to this node.
  5983. */
  5984. onInit( callback ) {
  5985. this.onInitFunction = callback;
  5986. return this;
  5987. }
  5988. /**
  5989. * The method execute the compute for this node.
  5990. *
  5991. * @param {NodeFrame} frame - A reference to the current node frame.
  5992. */
  5993. updateBefore( { renderer } ) {
  5994. renderer.compute( this );
  5995. }
  5996. generate( builder ) {
  5997. const { shaderStage } = builder;
  5998. if ( shaderStage === 'compute' ) {
  5999. const snippet = this.computeNode.build( builder, 'void' );
  6000. if ( snippet !== '' ) {
  6001. builder.addLineFlowCode( snippet, this );
  6002. }
  6003. }
  6004. }
  6005. }
  6006. /**
  6007. * TSL function for creating a compute node.
  6008. *
  6009. * @tsl
  6010. * @function
  6011. * @param {Node} node - TODO
  6012. * @param {number} count - TODO.
  6013. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6014. * @returns {AtomicFunctionNode}
  6015. */
  6016. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6017. addMethodChaining( 'compute', compute );
  6018. /**
  6019. * This node can be used as a cache management component for another node.
  6020. * Caching is in general used by default in {@link NodeBuilder} but this node
  6021. * allows the usage of a shared parent cache during the build process.
  6022. *
  6023. * @augments Node
  6024. */
  6025. class CacheNode extends Node {
  6026. static get type() {
  6027. return 'CacheNode';
  6028. }
  6029. /**
  6030. * Constructs a new cache node.
  6031. *
  6032. * @param {Node} node - The node that should be cached.
  6033. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6034. */
  6035. constructor( node, parent = true ) {
  6036. super();
  6037. /**
  6038. * The node that should be cached.
  6039. *
  6040. * @type {Node}
  6041. */
  6042. this.node = node;
  6043. /**
  6044. * Whether this node refers to a shared parent cache or not.
  6045. *
  6046. * @type {boolean}
  6047. * @default true
  6048. */
  6049. this.parent = parent;
  6050. /**
  6051. * This flag can be used for type testing.
  6052. *
  6053. * @type {boolean}
  6054. * @readonly
  6055. * @default true
  6056. */
  6057. this.isCacheNode = true;
  6058. }
  6059. getNodeType( builder ) {
  6060. const previousCache = builder.getCache();
  6061. const cache = builder.getCacheFromNode( this, this.parent );
  6062. builder.setCache( cache );
  6063. const nodeType = this.node.getNodeType( builder );
  6064. builder.setCache( previousCache );
  6065. return nodeType;
  6066. }
  6067. build( builder, ...params ) {
  6068. const previousCache = builder.getCache();
  6069. const cache = builder.getCacheFromNode( this, this.parent );
  6070. builder.setCache( cache );
  6071. const data = this.node.build( builder, ...params );
  6072. builder.setCache( previousCache );
  6073. return data;
  6074. }
  6075. }
  6076. /**
  6077. * TSL function for creating a cache node.
  6078. *
  6079. * @tsl
  6080. * @function
  6081. * @param {Node} node - The node that should be cached.
  6082. * @param {boolean} parent - Whether this node refers to a shared parent cache or not.
  6083. * @returns {CacheNode}
  6084. */
  6085. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6086. addMethodChaining( 'cache', cache );
  6087. /**
  6088. * The class generates the code of a given node but returns another node in the output.
  6089. * This can be used to call a method or node that does not return a value, i.e.
  6090. * type `void` on an input where returning a value is required. Example:
  6091. *
  6092. * ```js
  6093. * material.colorNode = myColor.bypass( runVoidFn() )
  6094. *```
  6095. *
  6096. * @augments Node
  6097. */
  6098. class BypassNode extends Node {
  6099. static get type() {
  6100. return 'BypassNode';
  6101. }
  6102. /**
  6103. * Constructs a new bypass node.
  6104. *
  6105. * @param {Node} outputNode - The output node.
  6106. * @param {Node} callNode - The call node.
  6107. */
  6108. constructor( outputNode, callNode ) {
  6109. super();
  6110. /**
  6111. * This flag can be used for type testing.
  6112. *
  6113. * @type {boolean}
  6114. * @readonly
  6115. * @default true
  6116. */
  6117. this.isBypassNode = true;
  6118. /**
  6119. * The output node.
  6120. *
  6121. * @type {Node}
  6122. */
  6123. this.outputNode = outputNode;
  6124. /**
  6125. * The call node.
  6126. *
  6127. * @type {Node}
  6128. */
  6129. this.callNode = callNode;
  6130. }
  6131. getNodeType( builder ) {
  6132. return this.outputNode.getNodeType( builder );
  6133. }
  6134. generate( builder ) {
  6135. const snippet = this.callNode.build( builder, 'void' );
  6136. if ( snippet !== '' ) {
  6137. builder.addLineFlowCode( snippet, this );
  6138. }
  6139. return this.outputNode.build( builder );
  6140. }
  6141. }
  6142. /**
  6143. * TSL function for creating a bypass node.
  6144. *
  6145. * @tsl
  6146. * @function
  6147. * @param {Node} outputNode - The output node.
  6148. * @param {Node} callNode - The call node.
  6149. * @returns {BypassNode}
  6150. */
  6151. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  6152. addMethodChaining( 'bypass', bypass );
  6153. /**
  6154. * This node allows to remap a node value from one range into another. E.g a value of
  6155. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6156. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6157. *
  6158. * @augments Node
  6159. */
  6160. class RemapNode extends Node {
  6161. static get type() {
  6162. return 'RemapNode';
  6163. }
  6164. /**
  6165. * Constructs a new remap node.
  6166. *
  6167. * @param {Node} node - The node that should be remapped.
  6168. * @param {Node} inLowNode - The source or current lower bound of the range.
  6169. * @param {Node} inHighNode - The source or current upper bound of the range.
  6170. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6171. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6172. */
  6173. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6174. super();
  6175. /**
  6176. * The node that should be remapped.
  6177. *
  6178. * @type {Node}
  6179. */
  6180. this.node = node;
  6181. /**
  6182. * The source or current lower bound of the range.
  6183. *
  6184. * @type {Node}
  6185. */
  6186. this.inLowNode = inLowNode;
  6187. /**
  6188. * The source or current upper bound of the range.
  6189. *
  6190. * @type {Node}
  6191. */
  6192. this.inHighNode = inHighNode;
  6193. /**
  6194. * The target lower bound of the range.
  6195. *
  6196. * @type {Node}
  6197. * @default float(0)
  6198. */
  6199. this.outLowNode = outLowNode;
  6200. /**
  6201. * The target upper bound of the range.
  6202. *
  6203. * @type {Node}
  6204. * @default float(1)
  6205. */
  6206. this.outHighNode = outHighNode;
  6207. /**
  6208. * Whether the node value should be clamped before
  6209. * remapping it to the target range.
  6210. *
  6211. * @type {boolean}
  6212. * @default true
  6213. */
  6214. this.doClamp = true;
  6215. }
  6216. setup() {
  6217. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6218. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6219. if ( doClamp === true ) t = t.clamp();
  6220. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6221. }
  6222. }
  6223. /**
  6224. * TSL function for creating a remap node.
  6225. *
  6226. * @tsl
  6227. * @function
  6228. * @param {Node} node - The node that should be remapped.
  6229. * @param {Node} inLowNode - The source or current lower bound of the range.
  6230. * @param {Node} inHighNode - The source or current upper bound of the range.
  6231. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6232. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6233. * @returns {RemapNode}
  6234. */
  6235. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6236. /**
  6237. * TSL function for creating a remap node, but with enabled clamping.
  6238. *
  6239. * @tsl
  6240. * @function
  6241. * @param {Node} node - The node that should be remapped.
  6242. * @param {Node} inLowNode - The source or current lower bound of the range.
  6243. * @param {Node} inHighNode - The source or current upper bound of the range.
  6244. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6245. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6246. * @returns {RemapNode}
  6247. */
  6248. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6249. addMethodChaining( 'remap', remap );
  6250. addMethodChaining( 'remapClamp', remapClamp );
  6251. /**
  6252. * This class can be used to implement basic expressions in shader code.
  6253. * Basic examples for that are `return`, `continue` or `discard` statements.
  6254. *
  6255. * @augments Node
  6256. */
  6257. class ExpressionNode extends Node {
  6258. static get type() {
  6259. return 'ExpressionNode';
  6260. }
  6261. /**
  6262. * Constructs a new expression node.
  6263. *
  6264. * @param {string} [snippet=''] - The native code snippet.
  6265. * @param {string} [nodeType='void'] - The node type.
  6266. */
  6267. constructor( snippet = '', nodeType = 'void' ) {
  6268. super( nodeType );
  6269. /**
  6270. * The native code snippet.
  6271. *
  6272. * @type {string}
  6273. * @default ''
  6274. */
  6275. this.snippet = snippet;
  6276. }
  6277. generate( builder, output ) {
  6278. const type = this.getNodeType( builder );
  6279. const snippet = this.snippet;
  6280. if ( type === 'void' ) {
  6281. builder.addLineFlowCode( snippet, this );
  6282. } else {
  6283. return builder.format( `( ${ snippet } )`, type, output );
  6284. }
  6285. }
  6286. }
  6287. /**
  6288. * TSL function for creating an expression node.
  6289. *
  6290. * @tsl
  6291. * @function
  6292. * @param {string} [snippet=''] - The native code snippet.
  6293. * @param {string} [nodeType='void'] - The node type.
  6294. * @returns {ExpressionNode}
  6295. */
  6296. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6297. /**
  6298. * Represents a `discard` shader operation in TSL.
  6299. *
  6300. * @tsl
  6301. * @function
  6302. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6303. * @return {Node} The `discard` expression.
  6304. */
  6305. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6306. /**
  6307. * Represents a `return` shader operation in TSL.
  6308. *
  6309. * @tsl
  6310. * @function
  6311. * @return {ExpressionNode} The `return` expression.
  6312. */
  6313. const Return = () => expression( 'return' ).append();
  6314. addMethodChaining( 'discard', Discard );
  6315. /**
  6316. * Normally, tone mapping and color conversion happens automatically
  6317. * before outputting pixel too the default (screen) framebuffer. In certain
  6318. * post processing setups this happens to late because certain effects
  6319. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6320. * to apply tone mapping and color space conversion at an arbitrary point
  6321. * in the effect chain.
  6322. *
  6323. * When applying tone mapping and color space conversion manually with this node,
  6324. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6325. *
  6326. * ```js
  6327. * const postProcessing = new PostProcessing( renderer );
  6328. * postProcessing.outputColorTransform = false;
  6329. *
  6330. * const scenePass = pass( scene, camera );
  6331. * const outputPass = renderOutput( scenePass );
  6332. *
  6333. * postProcessing.outputNode = outputPass;
  6334. * ```
  6335. *
  6336. * @augments TempNode
  6337. */
  6338. class RenderOutputNode extends TempNode {
  6339. static get type() {
  6340. return 'RenderOutputNode';
  6341. }
  6342. /**
  6343. * Constructs a new render output node.
  6344. *
  6345. * @param {Node} colorNode - The color node to process.
  6346. * @param {number} toneMapping - The tone mapping type.
  6347. * @param {string} outputColorSpace - The output color space.
  6348. */
  6349. constructor( colorNode, toneMapping, outputColorSpace ) {
  6350. super( 'vec4' );
  6351. /**
  6352. * The color node to process.
  6353. *
  6354. * @type {Node}
  6355. */
  6356. this.colorNode = colorNode;
  6357. /**
  6358. * The tone mapping type.
  6359. *
  6360. * @type {?number}
  6361. */
  6362. this.toneMapping = toneMapping;
  6363. /**
  6364. * The output color space.
  6365. *
  6366. * @type {?string}
  6367. */
  6368. this.outputColorSpace = outputColorSpace;
  6369. /**
  6370. * This flag can be used for type testing.
  6371. *
  6372. * @type {boolean}
  6373. * @readonly
  6374. * @default true
  6375. */
  6376. this.isRenderOutputNode = true;
  6377. }
  6378. setup( { context } ) {
  6379. let outputNode = this.colorNode || context.color;
  6380. // tone mapping
  6381. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6382. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6383. if ( toneMapping !== NoToneMapping ) {
  6384. outputNode = outputNode.toneMapping( toneMapping );
  6385. }
  6386. // working to output color space
  6387. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6388. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6389. }
  6390. return outputNode;
  6391. }
  6392. }
  6393. /**
  6394. * TSL function for creating a posterize node.
  6395. *
  6396. * @tsl
  6397. * @function
  6398. * @param {Node} color - The color node to process.
  6399. * @param {?number} [toneMapping=null] - The tone mapping type.
  6400. * @param {?string} [outputColorSpace=null] - The output color space.
  6401. * @returns {RenderOutputNode}
  6402. */
  6403. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6404. addMethodChaining( 'renderOutput', renderOutput );
  6405. // Non-PURE exports list, side-effects are required here.
  6406. // TSL Base Syntax
  6407. function addNodeElement( name/*, nodeElement*/ ) {
  6408. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6409. }
  6410. /**
  6411. * Base class for representing shader attributes as nodes.
  6412. *
  6413. * @augments Node
  6414. */
  6415. class AttributeNode extends Node {
  6416. static get type() {
  6417. return 'AttributeNode';
  6418. }
  6419. /**
  6420. * Constructs a new attribute node.
  6421. *
  6422. * @param {string} attributeName - The name of the attribute.
  6423. * @param {?string} nodeType - The node type.
  6424. */
  6425. constructor( attributeName, nodeType = null ) {
  6426. super( nodeType );
  6427. /**
  6428. * `AttributeNode` sets this property to `true` by default.
  6429. *
  6430. * @type {boolean}
  6431. * @default true
  6432. */
  6433. this.global = true;
  6434. this._attributeName = attributeName;
  6435. }
  6436. getHash( builder ) {
  6437. return this.getAttributeName( builder );
  6438. }
  6439. getNodeType( builder ) {
  6440. let nodeType = this.nodeType;
  6441. if ( nodeType === null ) {
  6442. const attributeName = this.getAttributeName( builder );
  6443. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6444. const attribute = builder.geometry.getAttribute( attributeName );
  6445. nodeType = builder.getTypeFromAttribute( attribute );
  6446. } else {
  6447. nodeType = 'float';
  6448. }
  6449. }
  6450. return nodeType;
  6451. }
  6452. /**
  6453. * Sets the attribute name to the given value. The method can be
  6454. * overwritten in derived classes if the final name must be computed
  6455. * analytically.
  6456. *
  6457. * @param {string} attributeName - The name of the attribute.
  6458. * @return {AttributeNode} A reference to this node.
  6459. */
  6460. setAttributeName( attributeName ) {
  6461. this._attributeName = attributeName;
  6462. return this;
  6463. }
  6464. /**
  6465. * Returns the attribute name of this node. The method can be
  6466. * overwritten in derived classes if the final name must be computed
  6467. * analytically.
  6468. *
  6469. * @param {NodeBuilder} builder - The current node builder.
  6470. * @return {string} The attribute name.
  6471. */
  6472. getAttributeName( /*builder*/ ) {
  6473. return this._attributeName;
  6474. }
  6475. generate( builder ) {
  6476. const attributeName = this.getAttributeName( builder );
  6477. const nodeType = this.getNodeType( builder );
  6478. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6479. if ( geometryAttribute === true ) {
  6480. const attribute = builder.geometry.getAttribute( attributeName );
  6481. const attributeType = builder.getTypeFromAttribute( attribute );
  6482. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6483. if ( builder.shaderStage === 'vertex' ) {
  6484. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6485. } else {
  6486. const nodeVarying = varying( this );
  6487. return nodeVarying.build( builder, nodeType );
  6488. }
  6489. } else {
  6490. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6491. return builder.generateConst( nodeType );
  6492. }
  6493. }
  6494. serialize( data ) {
  6495. super.serialize( data );
  6496. data.global = this.global;
  6497. data._attributeName = this._attributeName;
  6498. }
  6499. deserialize( data ) {
  6500. super.deserialize( data );
  6501. this.global = data.global;
  6502. this._attributeName = data._attributeName;
  6503. }
  6504. }
  6505. /**
  6506. * TSL function for creating an attribute node.
  6507. *
  6508. * @tsl
  6509. * @function
  6510. * @param {string} name - The name of the attribute.
  6511. * @param {?string} nodeType - The node type.
  6512. * @returns {AttributeNode}
  6513. */
  6514. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6515. /**
  6516. * TSL function for creating an uv attribute node with the given index.
  6517. *
  6518. * @tsl
  6519. * @function
  6520. * @param {number} [index=0] - The uv index.
  6521. * @return {AttributeNode<vec2>} The uv attribute node.
  6522. */
  6523. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6524. /**
  6525. * A node that represents the dimensions of a texture. The texture size is
  6526. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6527. * or `textureSize()`.
  6528. *
  6529. * @augments Node
  6530. */
  6531. class TextureSizeNode extends Node {
  6532. static get type() {
  6533. return 'TextureSizeNode';
  6534. }
  6535. /**
  6536. * Constructs a new texture size node.
  6537. *
  6538. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6539. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6540. */
  6541. constructor( textureNode, levelNode = null ) {
  6542. super( 'uvec2' );
  6543. /**
  6544. * This flag can be used for type testing.
  6545. *
  6546. * @type {boolean}
  6547. * @readonly
  6548. * @default true
  6549. */
  6550. this.isTextureSizeNode = true;
  6551. /**
  6552. * A texture node which size should be retrieved.
  6553. *
  6554. * @type {TextureNode}
  6555. */
  6556. this.textureNode = textureNode;
  6557. /**
  6558. * A level node which defines the requested mip.
  6559. *
  6560. * @type {Node<int>}
  6561. * @default null
  6562. */
  6563. this.levelNode = levelNode;
  6564. }
  6565. generate( builder, output ) {
  6566. const textureProperty = this.textureNode.build( builder, 'property' );
  6567. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6568. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6569. }
  6570. }
  6571. /**
  6572. * TSL function for creating a texture size node.
  6573. *
  6574. * @tsl
  6575. * @function
  6576. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6577. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6578. * @returns {TextureSizeNode}
  6579. */
  6580. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6581. /**
  6582. * A special type of uniform node that computes the
  6583. * maximum mipmap level for a given texture node.
  6584. *
  6585. * ```js
  6586. * const level = maxMipLevel( textureNode );
  6587. * ```
  6588. *
  6589. * @augments UniformNode
  6590. */
  6591. class MaxMipLevelNode extends UniformNode {
  6592. static get type() {
  6593. return 'MaxMipLevelNode';
  6594. }
  6595. /**
  6596. * Constructs a new max mip level node.
  6597. *
  6598. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6599. */
  6600. constructor( textureNode ) {
  6601. super( 0 );
  6602. /**
  6603. * The texture node to compute the max mip level for.
  6604. *
  6605. * @private
  6606. * @type {TextureNode}
  6607. */
  6608. this._textureNode = textureNode;
  6609. /**
  6610. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6611. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6612. *
  6613. * @type {string}
  6614. * @default 'frame'
  6615. */
  6616. this.updateType = NodeUpdateType.FRAME;
  6617. }
  6618. /**
  6619. * The texture node to compute the max mip level for.
  6620. *
  6621. * @readonly
  6622. * @type {TextureNode}
  6623. */
  6624. get textureNode() {
  6625. return this._textureNode;
  6626. }
  6627. /**
  6628. * The texture.
  6629. *
  6630. * @readonly
  6631. * @type {Texture}
  6632. */
  6633. get texture() {
  6634. return this._textureNode.value;
  6635. }
  6636. update() {
  6637. const texture = this.texture;
  6638. const images = texture.images;
  6639. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6640. if ( image && image.width !== undefined ) {
  6641. const { width, height } = image;
  6642. this.value = Math.log2( Math.max( width, height ) );
  6643. }
  6644. }
  6645. }
  6646. /**
  6647. * TSL function for creating a max mip level node.
  6648. *
  6649. * @tsl
  6650. * @function
  6651. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6652. * @returns {MaxMipLevelNode}
  6653. */
  6654. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6655. /**
  6656. * This type of uniform node represents a 2D texture.
  6657. *
  6658. * @augments UniformNode
  6659. */
  6660. class TextureNode extends UniformNode {
  6661. static get type() {
  6662. return 'TextureNode';
  6663. }
  6664. /**
  6665. * Constructs a new texture node.
  6666. *
  6667. * @param {Texture} value - The texture.
  6668. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  6669. * @param {?Node<int>} [levelNode=null] - The level node.
  6670. * @param {?Node<float>} [biasNode=null] - The bias node.
  6671. */
  6672. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6673. super( value );
  6674. /**
  6675. * This flag can be used for type testing.
  6676. *
  6677. * @type {boolean}
  6678. * @readonly
  6679. * @default true
  6680. */
  6681. this.isTextureNode = true;
  6682. /**
  6683. * Represents the texture coordinates.
  6684. *
  6685. * @type {?Node<vec2|vec3>}
  6686. * @default null
  6687. */
  6688. this.uvNode = uvNode;
  6689. /**
  6690. * Represents the mip level that should be selected.
  6691. *
  6692. * @type {?Node<int>}
  6693. * @default null
  6694. */
  6695. this.levelNode = levelNode;
  6696. /**
  6697. * Represents the bias to be applied during level-of-detail computation.
  6698. *
  6699. * @type {?Node<float>}
  6700. * @default null
  6701. */
  6702. this.biasNode = biasNode;
  6703. /**
  6704. * Represents a reference value a texture sample is compared to.
  6705. *
  6706. * @type {?Node<float>}
  6707. * @default null
  6708. */
  6709. this.compareNode = null;
  6710. /**
  6711. * When using texture arrays, the depth node defines the layer to select.
  6712. *
  6713. * @type {?Node<int>}
  6714. * @default null
  6715. */
  6716. this.depthNode = null;
  6717. /**
  6718. * When defined, a texture is sampled using explicit gradients.
  6719. *
  6720. * @type {?Array<Node<vec2>>}
  6721. * @default null
  6722. */
  6723. this.gradNode = null;
  6724. /**
  6725. * Whether texture values should be sampled or fetched.
  6726. *
  6727. * @type {boolean}
  6728. * @default true
  6729. */
  6730. this.sampler = true;
  6731. /**
  6732. * Whether the uv transformation matrix should be
  6733. * automatically updated or not. Use `setUpdateMatrix()`
  6734. * if you want to change the value of the property.
  6735. *
  6736. * @type {boolean}
  6737. * @default false
  6738. */
  6739. this.updateMatrix = false;
  6740. /**
  6741. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6742. * sets the value to `frame` when the uv transformation matrix should
  6743. * automatically be updated.
  6744. *
  6745. * @type {string}
  6746. * @default 'none'
  6747. */
  6748. this.updateType = NodeUpdateType.NONE;
  6749. /**
  6750. * The reference node.
  6751. *
  6752. * @type {?Node}
  6753. * @default null
  6754. */
  6755. this.referenceNode = null;
  6756. /**
  6757. * The texture value is stored in a private property.
  6758. *
  6759. * @private
  6760. * @type {Texture}
  6761. */
  6762. this._value = value;
  6763. /**
  6764. * The uniform node that represents the uv transformation matrix.
  6765. *
  6766. * @private
  6767. * @type {?UniformNode<mat3>}
  6768. */
  6769. this._matrixUniform = null;
  6770. this.setUpdateMatrix( uvNode === null );
  6771. }
  6772. set value( value ) {
  6773. if ( this.referenceNode ) {
  6774. this.referenceNode.value = value;
  6775. } else {
  6776. this._value = value;
  6777. }
  6778. }
  6779. /**
  6780. * The texture value.
  6781. *
  6782. * @type {Texture}
  6783. */
  6784. get value() {
  6785. return this.referenceNode ? this.referenceNode.value : this._value;
  6786. }
  6787. /**
  6788. * Overwritten since the uniform hash is defined by the texture's UUID.
  6789. *
  6790. * @param {NodeBuilder} builder - The current node builder.
  6791. * @return {string} The uniform hash.
  6792. */
  6793. getUniformHash( /*builder*/ ) {
  6794. return this.value.uuid;
  6795. }
  6796. /**
  6797. * Overwritten since the node type is inferred from the texture type.
  6798. *
  6799. * @param {NodeBuilder} builder - The current node builder.
  6800. * @return {string} The node type.
  6801. */
  6802. getNodeType( /*builder*/ ) {
  6803. if ( this.value.isDepthTexture === true ) return 'float';
  6804. if ( this.value.type === UnsignedIntType ) {
  6805. return 'uvec4';
  6806. } else if ( this.value.type === IntType ) {
  6807. return 'ivec4';
  6808. }
  6809. return 'vec4';
  6810. }
  6811. /**
  6812. * Overwrites the default implementation to return a fixed value `'texture'`.
  6813. *
  6814. * @param {NodeBuilder} builder - The current node builder.
  6815. * @return {string} The input type.
  6816. */
  6817. getInputType( /*builder*/ ) {
  6818. return 'texture';
  6819. }
  6820. /**
  6821. * Returns a default uvs based on the current texture's channel.
  6822. *
  6823. * @return {AttributeNode<vec2>} The default uvs.
  6824. */
  6825. getDefaultUV() {
  6826. return uv( this.value.channel );
  6827. }
  6828. /**
  6829. * Overwritten to always return the texture reference of the node.
  6830. *
  6831. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6832. * @return {Texture} The texture reference.
  6833. */
  6834. updateReference( /*state*/ ) {
  6835. return this.value;
  6836. }
  6837. /**
  6838. * Transforms the given uv node with the texture transformation matrix.
  6839. *
  6840. * @param {Node} uvNode - The uv node to transform.
  6841. * @return {Node} The transformed uv node.
  6842. */
  6843. getTransformedUV( uvNode ) {
  6844. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6845. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6846. }
  6847. /**
  6848. * Defines whether the uv transformation matrix should automatically be updated or not.
  6849. *
  6850. * @param {boolean} value - The update toggle.
  6851. * @return {TextureNode} A reference to this node.
  6852. */
  6853. setUpdateMatrix( value ) {
  6854. this.updateMatrix = value;
  6855. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6856. return this;
  6857. }
  6858. /**
  6859. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6860. * to modify the uv node for correct sampling.
  6861. *
  6862. * @param {NodeBuilder} builder - The current node builder.
  6863. * @param {Node} uvNode - The uv node to setup.
  6864. * @return {Node} The updated uv node.
  6865. */
  6866. setupUV( builder, uvNode ) {
  6867. const texture = this.value;
  6868. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6869. if ( this.sampler ) {
  6870. uvNode = uvNode.flipY();
  6871. } else {
  6872. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6873. }
  6874. }
  6875. return uvNode;
  6876. }
  6877. /**
  6878. * Setups texture node by preparing the internal nodes for code generation.
  6879. *
  6880. * @param {NodeBuilder} builder - The current node builder.
  6881. */
  6882. setup( builder ) {
  6883. const properties = builder.getNodeProperties( this );
  6884. properties.referenceNode = this.referenceNode;
  6885. //
  6886. const texture = this.value;
  6887. if ( ! texture || texture.isTexture !== true ) {
  6888. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6889. }
  6890. //
  6891. let uvNode = this.uvNode;
  6892. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6893. uvNode = builder.context.getUV( this );
  6894. }
  6895. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6896. if ( this.updateMatrix === true ) {
  6897. uvNode = this.getTransformedUV( uvNode );
  6898. }
  6899. uvNode = this.setupUV( builder, uvNode );
  6900. //
  6901. let levelNode = this.levelNode;
  6902. if ( levelNode === null && builder.context.getTextureLevel ) {
  6903. levelNode = builder.context.getTextureLevel( this );
  6904. }
  6905. //
  6906. properties.uvNode = uvNode;
  6907. properties.levelNode = levelNode;
  6908. properties.biasNode = this.biasNode;
  6909. properties.compareNode = this.compareNode;
  6910. properties.gradNode = this.gradNode;
  6911. properties.depthNode = this.depthNode;
  6912. }
  6913. /**
  6914. * Generates the uv code snippet.
  6915. *
  6916. * @param {NodeBuilder} builder - The current node builder.
  6917. * @param {Node} uvNode - The uv node to generate code for.
  6918. * @return {string} The generated code snippet.
  6919. */
  6920. generateUV( builder, uvNode ) {
  6921. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6922. }
  6923. /**
  6924. * Generates the snippet for the texture sampling.
  6925. *
  6926. * @param {NodeBuilder} builder - The current node builder.
  6927. * @param {string} textureProperty - The texture property.
  6928. * @param {string} uvSnippet - The uv snippet.
  6929. * @param {?string} levelSnippet - The level snippet.
  6930. * @param {?string} biasSnippet - The bias snippet.
  6931. * @param {?string} depthSnippet - The depth snippet.
  6932. * @param {?string} compareSnippet - The compare snippet.
  6933. * @param {?Array<string>} gradSnippet - The grad snippet.
  6934. * @return {string} The generated code snippet.
  6935. */
  6936. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6937. const texture = this.value;
  6938. let snippet;
  6939. if ( levelSnippet ) {
  6940. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6941. } else if ( biasSnippet ) {
  6942. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6943. } else if ( gradSnippet ) {
  6944. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6945. } else if ( compareSnippet ) {
  6946. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6947. } else if ( this.sampler === false ) {
  6948. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6949. } else {
  6950. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6951. }
  6952. return snippet;
  6953. }
  6954. /**
  6955. * Generates the code snippet of the texture node.
  6956. *
  6957. * @param {NodeBuilder} builder - The current node builder.
  6958. * @param {string} output - The current output.
  6959. * @return {string} The generated code snippet.
  6960. */
  6961. generate( builder, output ) {
  6962. const texture = this.value;
  6963. const properties = builder.getNodeProperties( this );
  6964. const textureProperty = super.generate( builder, 'property' );
  6965. if ( output === 'sampler' ) {
  6966. return textureProperty + '_sampler';
  6967. } else if ( builder.isReference( output ) ) {
  6968. return textureProperty;
  6969. } else {
  6970. const nodeData = builder.getDataFromNode( this );
  6971. let propertyName = nodeData.propertyName;
  6972. if ( propertyName === undefined ) {
  6973. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6974. const uvSnippet = this.generateUV( builder, uvNode );
  6975. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6976. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6977. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6978. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6979. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6980. const nodeVar = builder.getVarFromNode( this );
  6981. propertyName = builder.getPropertyName( nodeVar );
  6982. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6983. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6984. nodeData.snippet = snippet;
  6985. nodeData.propertyName = propertyName;
  6986. }
  6987. let snippet = propertyName;
  6988. const nodeType = this.getNodeType( builder );
  6989. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6990. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6991. }
  6992. return builder.format( snippet, nodeType, output );
  6993. }
  6994. }
  6995. /**
  6996. * Sets the sampler value.
  6997. *
  6998. * @param {boolean} value - The sampler value to set.
  6999. * @return {TextureNode} A reference to this texture node.
  7000. */
  7001. setSampler( value ) {
  7002. this.sampler = value;
  7003. return this;
  7004. }
  7005. /**
  7006. * Returns the sampler value.
  7007. *
  7008. * @return {boolean} The sampler value.
  7009. */
  7010. getSampler() {
  7011. return this.sampler;
  7012. }
  7013. // @TODO: Move to TSL
  7014. /**
  7015. * @function
  7016. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7017. *
  7018. * @param {Node} uvNode - The uv node.
  7019. * @return {TextureNode} A texture node representing the texture sample.
  7020. */
  7021. uv( uvNode ) { // @deprecated, r172
  7022. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7023. return this.sample( uvNode );
  7024. }
  7025. /**
  7026. * Samples the texture with the given uv node.
  7027. *
  7028. * @param {Node} uvNode - The uv node.
  7029. * @return {TextureNode} A texture node representing the texture sample.
  7030. */
  7031. sample( uvNode ) {
  7032. const textureNode = this.clone();
  7033. textureNode.uvNode = nodeObject( uvNode );
  7034. textureNode.referenceNode = this.getSelf();
  7035. return nodeObject( textureNode );
  7036. }
  7037. /**
  7038. * Samples a blurred version of the texture by defining an internal bias.
  7039. *
  7040. * @param {Node<float>} amountNode - How blurred the texture should be.
  7041. * @return {TextureNode} A texture node representing the texture sample.
  7042. */
  7043. blur( amountNode ) {
  7044. const textureNode = this.clone();
  7045. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7046. textureNode.referenceNode = this.getSelf();
  7047. return nodeObject( textureNode );
  7048. }
  7049. /**
  7050. * Samples a specific mip of the texture.
  7051. *
  7052. * @param {Node<int>} levelNode - The mip level to sample.
  7053. * @return {TextureNode} A texture node representing the texture sample.
  7054. */
  7055. level( levelNode ) {
  7056. const textureNode = this.clone();
  7057. textureNode.levelNode = nodeObject( levelNode );
  7058. textureNode.referenceNode = this.getSelf();
  7059. return nodeObject( textureNode );
  7060. }
  7061. /**
  7062. * Returns the texture size of the requested level.
  7063. *
  7064. * @param {Node<int>} levelNode - The level to compute the size for.
  7065. * @return {TextureSizeNode} The texture size.
  7066. */
  7067. size( levelNode ) {
  7068. return textureSize( this, levelNode );
  7069. }
  7070. /**
  7071. * Samples the texture with the given bias.
  7072. *
  7073. * @param {Node<float>} biasNode - The bias node.
  7074. * @return {TextureNode} A texture node representing the texture sample.
  7075. */
  7076. bias( biasNode ) {
  7077. const textureNode = this.clone();
  7078. textureNode.biasNode = nodeObject( biasNode );
  7079. textureNode.referenceNode = this.getSelf();
  7080. return nodeObject( textureNode );
  7081. }
  7082. /**
  7083. * Samples the texture by executing a compare operation.
  7084. *
  7085. * @param {Node<float>} compareNode - The node that defines the compare value.
  7086. * @return {TextureNode} A texture node representing the texture sample.
  7087. */
  7088. compare( compareNode ) {
  7089. const textureNode = this.clone();
  7090. textureNode.compareNode = nodeObject( compareNode );
  7091. textureNode.referenceNode = this.getSelf();
  7092. return nodeObject( textureNode );
  7093. }
  7094. /**
  7095. * Samples the texture using an explicit gradient.
  7096. *
  7097. * @param {Node<vec2>} gradNodeX - The gradX node.
  7098. * @param {Node<vec2>} gradNodeY - The gradY node.
  7099. * @return {TextureNode} A texture node representing the texture sample.
  7100. */
  7101. grad( gradNodeX, gradNodeY ) {
  7102. const textureNode = this.clone();
  7103. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7104. textureNode.referenceNode = this.getSelf();
  7105. return nodeObject( textureNode );
  7106. }
  7107. /**
  7108. * Samples the texture by defining a depth node.
  7109. *
  7110. * @param {Node<int>} depthNode - The depth node.
  7111. * @return {TextureNode} A texture node representing the texture sample.
  7112. */
  7113. depth( depthNode ) {
  7114. const textureNode = this.clone();
  7115. textureNode.depthNode = nodeObject( depthNode );
  7116. textureNode.referenceNode = this.getSelf();
  7117. return nodeObject( textureNode );
  7118. }
  7119. // --
  7120. serialize( data ) {
  7121. super.serialize( data );
  7122. data.value = this.value.toJSON( data.meta ).uuid;
  7123. data.sampler = this.sampler;
  7124. data.updateMatrix = this.updateMatrix;
  7125. data.updateType = this.updateType;
  7126. }
  7127. deserialize( data ) {
  7128. super.deserialize( data );
  7129. this.value = data.meta.textures[ data.value ];
  7130. this.sampler = data.sampler;
  7131. this.updateMatrix = data.updateMatrix;
  7132. this.updateType = data.updateType;
  7133. }
  7134. /**
  7135. * The update is used to implement the update of the uv transformation matrix.
  7136. */
  7137. update() {
  7138. const texture = this.value;
  7139. const matrixUniform = this._matrixUniform;
  7140. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7141. if ( texture.matrixAutoUpdate === true ) {
  7142. texture.updateMatrix();
  7143. }
  7144. }
  7145. /**
  7146. * Clones the texture node.
  7147. *
  7148. * @return {TextureNode} The cloned texture node.
  7149. */
  7150. clone() {
  7151. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7152. newNode.sampler = this.sampler;
  7153. return newNode;
  7154. }
  7155. }
  7156. /**
  7157. * TSL function for creating a texture node.
  7158. *
  7159. * @tsl
  7160. * @function
  7161. * @param {Texture} value - The texture.
  7162. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7163. * @param {?Node<int>} [levelNode=null] - The level node.
  7164. * @param {?Node<float>} [biasNode=null] - The bias node.
  7165. * @returns {TextureNode}
  7166. */
  7167. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  7168. /**
  7169. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7170. *
  7171. * @tsl
  7172. * @function
  7173. * @param {Texture} value - The texture.
  7174. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7175. * @param {?Node<int>} [levelNode=null] - The level node.
  7176. * @param {?Node<float>} [biasNode=null] - The bias node.
  7177. * @returns {TextureNode}
  7178. */
  7179. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7180. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7181. /**
  7182. * Converts a texture or texture node to a sampler.
  7183. *
  7184. * @tsl
  7185. * @function
  7186. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  7187. * @returns {Node}
  7188. */
  7189. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  7190. /**
  7191. * A special type of uniform node which represents array-like data
  7192. * as uniform buffers. The access usually happens via `element()`
  7193. * which returns an instance of {@link ArrayElementNode}. For example:
  7194. *
  7195. * ```js
  7196. * const bufferNode = buffer( array, 'mat4', count );
  7197. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7198. * ```
  7199. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7200. * since it handles more input types and automatically cares about buffer paddings.
  7201. *
  7202. * @augments UniformNode
  7203. */
  7204. class BufferNode extends UniformNode {
  7205. static get type() {
  7206. return 'BufferNode';
  7207. }
  7208. /**
  7209. * Constructs a new buffer node.
  7210. *
  7211. * @param {Array<number>} value - Array-like buffer data.
  7212. * @param {string} bufferType - The data type of the buffer.
  7213. * @param {number} [bufferCount=0] - The count of buffer elements.
  7214. */
  7215. constructor( value, bufferType, bufferCount = 0 ) {
  7216. super( value, bufferType );
  7217. /**
  7218. * This flag can be used for type testing.
  7219. *
  7220. * @type {boolean}
  7221. * @readonly
  7222. * @default true
  7223. */
  7224. this.isBufferNode = true;
  7225. /**
  7226. * The data type of the buffer.
  7227. *
  7228. * @type {string}
  7229. */
  7230. this.bufferType = bufferType;
  7231. /**
  7232. * The uniform node that holds the value of the reference node.
  7233. *
  7234. * @type {number}
  7235. * @default 0
  7236. */
  7237. this.bufferCount = bufferCount;
  7238. }
  7239. /**
  7240. * The data type of the buffer elements.
  7241. *
  7242. * @param {NodeBuilder} builder - The current node builder.
  7243. * @return {string} The element type.
  7244. */
  7245. getElementType( builder ) {
  7246. return this.getNodeType( builder );
  7247. }
  7248. /**
  7249. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7250. *
  7251. * @param {NodeBuilder} builder - The current node builder.
  7252. * @return {string} The input type.
  7253. */
  7254. getInputType( /*builder*/ ) {
  7255. return 'buffer';
  7256. }
  7257. }
  7258. /**
  7259. * TSL function for creating a buffer node.
  7260. *
  7261. * @tsl
  7262. * @function
  7263. * @param {Array} value - Array-like buffer data.
  7264. * @param {string} type - The data type of a buffer element.
  7265. * @param {number} count - The count of buffer elements.
  7266. * @returns {BufferNode}
  7267. */
  7268. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7269. /**
  7270. * Represents the element access on uniform array nodes.
  7271. *
  7272. * @augments ArrayElementNode
  7273. */
  7274. class UniformArrayElementNode extends ArrayElementNode {
  7275. static get type() {
  7276. return 'UniformArrayElementNode';
  7277. }
  7278. /**
  7279. * Constructs a new buffer node.
  7280. *
  7281. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7282. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7283. */
  7284. constructor( uniformArrayNode, indexNode ) {
  7285. super( uniformArrayNode, indexNode );
  7286. /**
  7287. * This flag can be used for type testing.
  7288. *
  7289. * @type {boolean}
  7290. * @readonly
  7291. * @default true
  7292. */
  7293. this.isArrayBufferElementNode = true;
  7294. }
  7295. generate( builder ) {
  7296. const snippet = super.generate( builder );
  7297. const type = this.getNodeType();
  7298. const paddedType = this.node.getPaddedType();
  7299. return builder.format( snippet, paddedType, type );
  7300. }
  7301. }
  7302. /**
  7303. * Similar to {@link BufferNode} this module represents array-like data as
  7304. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7305. * data types in the array (e.g `three.js` primitives) and automatically
  7306. * manage buffer padding. It should be the first choice when working with
  7307. * uniforms buffers.
  7308. * ```js
  7309. * const tintColors = uniformArray( [
  7310. * new Color( 1, 0, 0 ),
  7311. * new Color( 0, 1, 0 ),
  7312. * new Color( 0, 0, 1 )
  7313. * ], 'color' );
  7314. *
  7315. * const redColor = tintColors.element( 0 );
  7316. *
  7317. * @augments BufferNode
  7318. */
  7319. class UniformArrayNode extends BufferNode {
  7320. static get type() {
  7321. return 'UniformArrayNode';
  7322. }
  7323. /**
  7324. * Constructs a new uniform array node.
  7325. *
  7326. * @param {Array<any>} value - Array holding the buffer data.
  7327. * @param {?string} [elementType=null] - The data type of a buffer element.
  7328. */
  7329. constructor( value, elementType = null ) {
  7330. super( null );
  7331. /**
  7332. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7333. * hold number primitives as well as three.js objects like vectors, matrices
  7334. * or colors.
  7335. *
  7336. * @type {Array<any>}
  7337. */
  7338. this.array = value;
  7339. /**
  7340. * The data type of an array element.
  7341. *
  7342. * @type {string}
  7343. */
  7344. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7345. /**
  7346. * The padded type. Uniform buffers must conform to a certain buffer layout
  7347. * so a separate type is computed to ensure correct buffer size.
  7348. *
  7349. * @type {string}
  7350. */
  7351. this.paddedType = this.getPaddedType();
  7352. /**
  7353. * Overwritten since uniform array nodes are updated per render.
  7354. *
  7355. * @type {string}
  7356. * @default 'render'
  7357. */
  7358. this.updateType = NodeUpdateType.RENDER;
  7359. /**
  7360. * This flag can be used for type testing.
  7361. *
  7362. * @type {boolean}
  7363. * @readonly
  7364. * @default true
  7365. */
  7366. this.isArrayBufferNode = true;
  7367. }
  7368. /**
  7369. * This method is overwritten since the node type is inferred from the
  7370. * {@link UniformArrayNode#paddedType}.
  7371. *
  7372. * @param {NodeBuilder} builder - The current node builder.
  7373. * @return {string} The node type.
  7374. */
  7375. getNodeType( /*builder*/ ) {
  7376. return this.paddedType;
  7377. }
  7378. /**
  7379. * The data type of the array elements.
  7380. *
  7381. * @param {NodeBuilder} builder - The current node builder.
  7382. * @return {string} The element type.
  7383. */
  7384. getElementType() {
  7385. return this.elementType;
  7386. }
  7387. /**
  7388. * Returns the padded type based on the element type.
  7389. *
  7390. * @return {string} The padded type.
  7391. */
  7392. getPaddedType() {
  7393. const elementType = this.elementType;
  7394. let paddedType = 'vec4';
  7395. if ( elementType === 'mat2' ) {
  7396. paddedType = 'mat2';
  7397. } else if ( /mat/.test( elementType ) === true ) {
  7398. paddedType = 'mat4';
  7399. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7400. paddedType = 'ivec4';
  7401. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7402. paddedType = 'uvec4';
  7403. }
  7404. return paddedType;
  7405. }
  7406. /**
  7407. * The update makes sure to correctly transfer the data from the (complex) objects
  7408. * in the array to the internal, correctly padded value buffer.
  7409. *
  7410. * @param {NodeFrame} frame - A reference to the current node frame.
  7411. */
  7412. update( /*frame*/ ) {
  7413. const { array, value } = this;
  7414. const elementType = this.elementType;
  7415. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7416. for ( let i = 0; i < array.length; i ++ ) {
  7417. const index = i * 4;
  7418. value[ index ] = array[ i ];
  7419. }
  7420. } else if ( elementType === 'color' ) {
  7421. for ( let i = 0; i < array.length; i ++ ) {
  7422. const index = i * 4;
  7423. const vector = array[ i ];
  7424. value[ index ] = vector.r;
  7425. value[ index + 1 ] = vector.g;
  7426. value[ index + 2 ] = vector.b || 0;
  7427. //value[ index + 3 ] = vector.a || 0;
  7428. }
  7429. } else if ( elementType === 'mat2' ) {
  7430. for ( let i = 0; i < array.length; i ++ ) {
  7431. const index = i * 4;
  7432. const matrix = array[ i ];
  7433. value[ index ] = matrix.elements[ 0 ];
  7434. value[ index + 1 ] = matrix.elements[ 1 ];
  7435. value[ index + 2 ] = matrix.elements[ 2 ];
  7436. value[ index + 3 ] = matrix.elements[ 3 ];
  7437. }
  7438. } else if ( elementType === 'mat3' ) {
  7439. for ( let i = 0; i < array.length; i ++ ) {
  7440. const index = i * 16;
  7441. const matrix = array[ i ];
  7442. value[ index ] = matrix.elements[ 0 ];
  7443. value[ index + 1 ] = matrix.elements[ 1 ];
  7444. value[ index + 2 ] = matrix.elements[ 2 ];
  7445. value[ index + 4 ] = matrix.elements[ 3 ];
  7446. value[ index + 5 ] = matrix.elements[ 4 ];
  7447. value[ index + 6 ] = matrix.elements[ 5 ];
  7448. value[ index + 8 ] = matrix.elements[ 6 ];
  7449. value[ index + 9 ] = matrix.elements[ 7 ];
  7450. value[ index + 10 ] = matrix.elements[ 8 ];
  7451. value[ index + 15 ] = 1;
  7452. }
  7453. } else if ( elementType === 'mat4' ) {
  7454. for ( let i = 0; i < array.length; i ++ ) {
  7455. const index = i * 16;
  7456. const matrix = array[ i ];
  7457. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7458. value[ index + i ] = matrix.elements[ i ];
  7459. }
  7460. }
  7461. } else {
  7462. for ( let i = 0; i < array.length; i ++ ) {
  7463. const index = i * 4;
  7464. const vector = array[ i ];
  7465. value[ index ] = vector.x;
  7466. value[ index + 1 ] = vector.y;
  7467. value[ index + 2 ] = vector.z || 0;
  7468. value[ index + 3 ] = vector.w || 0;
  7469. }
  7470. }
  7471. }
  7472. /**
  7473. * Implement the value buffer creation based on the array data.
  7474. *
  7475. * @param {NodeBuilder} builder - A reference to the current node builder.
  7476. * @return {null}
  7477. */
  7478. setup( builder ) {
  7479. const length = this.array.length;
  7480. const elementType = this.elementType;
  7481. let arrayType = Float32Array;
  7482. const paddedType = this.paddedType;
  7483. const paddedElementLength = builder.getTypeLength( paddedType );
  7484. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7485. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7486. this.value = new arrayType( length * paddedElementLength );
  7487. this.bufferCount = length;
  7488. this.bufferType = paddedType;
  7489. return super.setup( builder );
  7490. }
  7491. /**
  7492. * Overwrites the default `element()` method to provide element access
  7493. * based on {@link UniformArrayNode}.
  7494. *
  7495. * @param {IndexNode} indexNode - The index node.
  7496. * @return {UniformArrayElementNode}
  7497. */
  7498. element( indexNode ) {
  7499. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7500. }
  7501. }
  7502. /**
  7503. * TSL function for creating an uniform array node.
  7504. *
  7505. * @tsl
  7506. * @function
  7507. * @param {Array<any>} values - Array-like data.
  7508. * @param {?string} nodeType - The data type of the array elements.
  7509. * @returns {UniformArrayNode}
  7510. */
  7511. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7512. /**
  7513. * @tsl
  7514. * @function
  7515. * @deprecated since r168. Use {@link uniformArray} instead.
  7516. *
  7517. * @param {Array<any>} values - Array-like data.
  7518. * @param {string} nodeType - The data type of the array elements.
  7519. * @returns {UniformArrayNode}
  7520. */
  7521. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7522. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7523. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7524. };
  7525. /**
  7526. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7527. *
  7528. * @tsl
  7529. * @type {UniformNode<uint>}
  7530. */
  7531. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7532. /**
  7533. * TSL object that represents the `near` value of the camera used for the current render.
  7534. *
  7535. * @tsl
  7536. * @type {UniformNode<float>}
  7537. */
  7538. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7539. /**
  7540. * TSL object that represents the `far` value of the camera used for the current render.
  7541. *
  7542. * @tsl
  7543. * @type {UniformNode<float>}
  7544. */
  7545. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7546. /**
  7547. * TSL object that represents the projection matrix of the camera used for the current render.
  7548. *
  7549. * @tsl
  7550. * @type {UniformNode<mat4>}
  7551. */
  7552. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7553. let cameraProjectionMatrix;
  7554. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7555. const matrices = [];
  7556. for ( const subCamera of camera.cameras ) {
  7557. matrices.push( subCamera.projectionMatrix );
  7558. }
  7559. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7560. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7561. } else {
  7562. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7563. }
  7564. return cameraProjectionMatrix;
  7565. } ).once() )();
  7566. /**
  7567. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7568. *
  7569. * @tsl
  7570. * @type {UniformNode<mat4>}
  7571. */
  7572. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7573. /**
  7574. * TSL object that represents the view matrix of the camera used for the current render.
  7575. *
  7576. * @tsl
  7577. * @type {UniformNode<mat4>}
  7578. */
  7579. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7580. let cameraViewMatrix;
  7581. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7582. const matrices = [];
  7583. for ( const subCamera of camera.cameras ) {
  7584. matrices.push( subCamera.matrixWorldInverse );
  7585. }
  7586. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7587. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7588. } else {
  7589. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7590. }
  7591. return cameraViewMatrix;
  7592. } ).once() )();
  7593. /**
  7594. * TSL object that represents the world matrix of the camera used for the current render.
  7595. *
  7596. * @tsl
  7597. * @type {UniformNode<mat4>}
  7598. */
  7599. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7600. /**
  7601. * TSL object that represents the normal matrix of the camera used for the current render.
  7602. *
  7603. * @tsl
  7604. * @type {UniformNode<mat3>}
  7605. */
  7606. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7607. /**
  7608. * TSL object that represents the position in world space of the camera used for the current render.
  7609. *
  7610. * @tsl
  7611. * @type {UniformNode<vec3>}
  7612. */
  7613. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7614. /**
  7615. * This node can be used to access transformation related metrics of 3D objects.
  7616. * Depending on the selected scope, a different metric is represented as a uniform
  7617. * in the shader. The following scopes are supported:
  7618. *
  7619. * - `POSITION`: The object's position in world space.
  7620. * - `VIEW_POSITION`: The object's position in view/camera space.
  7621. * - `DIRECTION`: The object's direction in world space.
  7622. * - `SCALE`: The object's scale in world space.
  7623. * - `WORLD_MATRIX`: The object's matrix in world space.
  7624. *
  7625. * @augments Node
  7626. */
  7627. class Object3DNode extends Node {
  7628. static get type() {
  7629. return 'Object3DNode';
  7630. }
  7631. /**
  7632. * Constructs a new object 3D node.
  7633. *
  7634. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7635. * @param {?Object3D} [object3d=null] - The 3D object.
  7636. */
  7637. constructor( scope, object3d = null ) {
  7638. super();
  7639. /**
  7640. * The node reports a different type of transformation depending on the scope.
  7641. *
  7642. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7643. */
  7644. this.scope = scope;
  7645. /**
  7646. * The 3D object.
  7647. *
  7648. * @type {?Object3D}
  7649. * @default null
  7650. */
  7651. this.object3d = object3d;
  7652. /**
  7653. * Overwritten since this type of node is updated per object.
  7654. *
  7655. * @type {string}
  7656. * @default 'object'
  7657. */
  7658. this.updateType = NodeUpdateType.OBJECT;
  7659. /**
  7660. * Holds the value of the node as a uniform.
  7661. *
  7662. * @private
  7663. * @type {UniformNode}
  7664. */
  7665. this._uniformNode = new UniformNode( null );
  7666. }
  7667. /**
  7668. * Overwritten since the node type is inferred from the scope.
  7669. *
  7670. * @return {string} The node type.
  7671. */
  7672. getNodeType() {
  7673. const scope = this.scope;
  7674. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7675. return 'mat4';
  7676. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7677. return 'vec3';
  7678. }
  7679. }
  7680. /**
  7681. * Updates the uniform value depending on the scope.
  7682. *
  7683. * @param {NodeFrame} frame - The current node frame.
  7684. */
  7685. update( frame ) {
  7686. const object = this.object3d;
  7687. const uniformNode = this._uniformNode;
  7688. const scope = this.scope;
  7689. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7690. uniformNode.value = object.matrixWorld;
  7691. } else if ( scope === Object3DNode.POSITION ) {
  7692. uniformNode.value = uniformNode.value || new Vector3();
  7693. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7694. } else if ( scope === Object3DNode.SCALE ) {
  7695. uniformNode.value = uniformNode.value || new Vector3();
  7696. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7697. } else if ( scope === Object3DNode.DIRECTION ) {
  7698. uniformNode.value = uniformNode.value || new Vector3();
  7699. object.getWorldDirection( uniformNode.value );
  7700. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7701. const camera = frame.camera;
  7702. uniformNode.value = uniformNode.value || new Vector3();
  7703. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7704. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7705. }
  7706. }
  7707. /**
  7708. * Generates the code snippet of the uniform node. The node type of the uniform
  7709. * node also depends on the selected scope.
  7710. *
  7711. * @param {NodeBuilder} builder - The current node builder.
  7712. * @return {string} The generated code snippet.
  7713. */
  7714. generate( builder ) {
  7715. const scope = this.scope;
  7716. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7717. this._uniformNode.nodeType = 'mat4';
  7718. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7719. this._uniformNode.nodeType = 'vec3';
  7720. }
  7721. return this._uniformNode.build( builder );
  7722. }
  7723. serialize( data ) {
  7724. super.serialize( data );
  7725. data.scope = this.scope;
  7726. }
  7727. deserialize( data ) {
  7728. super.deserialize( data );
  7729. this.scope = data.scope;
  7730. }
  7731. }
  7732. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7733. Object3DNode.POSITION = 'position';
  7734. Object3DNode.SCALE = 'scale';
  7735. Object3DNode.VIEW_POSITION = 'viewPosition';
  7736. Object3DNode.DIRECTION = 'direction';
  7737. /**
  7738. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7739. *
  7740. * @tsl
  7741. * @function
  7742. * @param {?Object3D} [object3d=null] - The 3D object.
  7743. * @returns {Object3DNode<vec3>}
  7744. */
  7745. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7746. /**
  7747. * TSL function for creating an object 3D node that represents the object's world matrix.
  7748. *
  7749. * @tsl
  7750. * @function
  7751. * @param {?Object3D} [object3d=null] - The 3D object.
  7752. * @returns {Object3DNode<mat4>}
  7753. */
  7754. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7755. /**
  7756. * TSL function for creating an object 3D node that represents the object's position in world space.
  7757. *
  7758. * @tsl
  7759. * @function
  7760. * @param {?Object3D} [object3d=null] - The 3D object.
  7761. * @returns {Object3DNode<vec3>}
  7762. */
  7763. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7764. /**
  7765. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7766. *
  7767. * @tsl
  7768. * @function
  7769. * @param {?Object3D} [object3d=null] - The 3D object.
  7770. * @returns {Object3DNode<vec3>}
  7771. */
  7772. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7773. /**
  7774. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7775. *
  7776. * @tsl
  7777. * @function
  7778. * @param {?Object3D} [object3d=null] - The 3D object.
  7779. * @returns {Object3DNode<vec3>}
  7780. */
  7781. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7782. /**
  7783. * This type of node is a specialized version of `Object3DNode`
  7784. * with larger set of model related metrics. Unlike `Object3DNode`,
  7785. * `ModelNode` extracts the reference to the 3D object from the
  7786. * current node frame state.
  7787. *
  7788. * @augments Object3DNode
  7789. */
  7790. class ModelNode extends Object3DNode {
  7791. static get type() {
  7792. return 'ModelNode';
  7793. }
  7794. /**
  7795. * Constructs a new object model node.
  7796. *
  7797. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7798. */
  7799. constructor( scope ) {
  7800. super( scope );
  7801. }
  7802. /**
  7803. * Extracts the model reference from the frame state and then
  7804. * updates the uniform value depending on the scope.
  7805. *
  7806. * @param {NodeFrame} frame - The current node frame.
  7807. */
  7808. update( frame ) {
  7809. this.object3d = frame.object;
  7810. super.update( frame );
  7811. }
  7812. }
  7813. /**
  7814. * TSL object that represents the object's direction in world space.
  7815. *
  7816. * @tsl
  7817. * @type {ModelNode<vec3>}
  7818. */
  7819. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7820. /**
  7821. * TSL object that represents the object's world matrix.
  7822. *
  7823. * @tsl
  7824. * @type {ModelNode<mat4>}
  7825. */
  7826. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7827. /**
  7828. * TSL object that represents the object's position in world space.
  7829. *
  7830. * @tsl
  7831. * @type {ModelNode<vec3>}
  7832. */
  7833. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7834. /**
  7835. * TSL object that represents the object's scale in world space.
  7836. *
  7837. * @tsl
  7838. * @type {ModelNode<vec3>}
  7839. */
  7840. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7841. /**
  7842. * TSL object that represents the object's position in view/camera space.
  7843. *
  7844. * @tsl
  7845. * @type {ModelNode<vec3>}
  7846. */
  7847. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7848. /**
  7849. * TSL object that represents the object's normal matrix.
  7850. *
  7851. * @tsl
  7852. * @type {UniformNode<mat3>}
  7853. */
  7854. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7855. /**
  7856. * TSL object that represents the object's inverse world matrix.
  7857. *
  7858. * @tsl
  7859. * @type {UniformNode<mat4>}
  7860. */
  7861. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7862. /**
  7863. * TSL object that represents the object's model view matrix.
  7864. *
  7865. * @tsl
  7866. * @type {Node<mat4>}
  7867. */
  7868. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7869. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7870. } ).once() )().toVar( 'modelViewMatrix' );
  7871. // GPU Precision
  7872. /**
  7873. * TSL object that represents the object's model view in `mediump` precision.
  7874. *
  7875. * @tsl
  7876. * @type {Node<mat4>}
  7877. */
  7878. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7879. // CPU Precision
  7880. /**
  7881. * TSL object that represents the object's model view in `highp` precision
  7882. * which is achieved by computing the matrix in JS and not in the shader.
  7883. *
  7884. * @tsl
  7885. * @type {Node<mat4>}
  7886. */
  7887. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7888. builder.context.isHighPrecisionModelViewMatrix = true;
  7889. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7890. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7891. } );
  7892. } ).once() )().toVar( 'highpModelViewMatrix' );
  7893. /**
  7894. * TSL object that represents the object's model normal view in `highp` precision
  7895. * which is achieved by computing the matrix in JS and not in the shader.
  7896. *
  7897. * @tsl
  7898. * @type {Node<mat3>}
  7899. */
  7900. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7901. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7902. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7903. if ( isHighPrecisionModelViewMatrix !== true ) {
  7904. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7905. }
  7906. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7907. } );
  7908. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7909. /**
  7910. * TSL object that represents the position attribute of the current rendered object.
  7911. *
  7912. * @tsl
  7913. * @type {AttributeNode<vec3>}
  7914. */
  7915. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7916. /**
  7917. * TSL object that represents the vertex position in local space of the current rendered object.
  7918. *
  7919. * @tsl
  7920. * @type {AttributeNode<vec3>}
  7921. */
  7922. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7923. /**
  7924. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7925. * Used in context of {@link VelocityNode} for rendering motion vectors.
  7926. *
  7927. * @tsl
  7928. * @type {AttributeNode<vec3>}
  7929. */
  7930. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7931. /**
  7932. * TSL object that represents the vertex position in world space of the current rendered object.
  7933. *
  7934. * @tsl
  7935. * @type {VaryingNode<vec3>}
  7936. */
  7937. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7938. /**
  7939. * TSL object that represents the position world direction of the current rendered object.
  7940. *
  7941. * @tsl
  7942. * @type {Node<vec3>}
  7943. */
  7944. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7945. /**
  7946. * TSL object that represents the vertex position in view space of the current rendered object.
  7947. *
  7948. * @tsl
  7949. * @type {VaryingNode<vec3>}
  7950. */
  7951. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7952. return builder.context.setupPositionView();
  7953. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7954. /**
  7955. * TSL object that represents the position view direction of the current rendered object.
  7956. *
  7957. * @tsl
  7958. * @type {VaryingNode<vec3>}
  7959. */
  7960. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7961. /**
  7962. * This node can be used to evaluate whether a primitive is front or back facing.
  7963. *
  7964. * @augments Node
  7965. */
  7966. class FrontFacingNode extends Node {
  7967. static get type() {
  7968. return 'FrontFacingNode';
  7969. }
  7970. /**
  7971. * Constructs a new front facing node.
  7972. */
  7973. constructor() {
  7974. super( 'bool' );
  7975. /**
  7976. * This flag can be used for type testing.
  7977. *
  7978. * @type {boolean}
  7979. * @readonly
  7980. * @default true
  7981. */
  7982. this.isFrontFacingNode = true;
  7983. }
  7984. generate( builder ) {
  7985. const { renderer, material } = builder;
  7986. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7987. if ( material.side === BackSide ) {
  7988. return 'false';
  7989. }
  7990. }
  7991. return builder.getFrontFacing();
  7992. }
  7993. }
  7994. /**
  7995. * TSL object that represents whether a primitive is front or back facing
  7996. *
  7997. * @tsl
  7998. * @type {FrontFacingNode<bool>}
  7999. */
  8000. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8001. /**
  8002. * TSL object that represents the front facing status as a number instead of a bool.
  8003. * `1` means front facing, `-1` means back facing.
  8004. *
  8005. * @tsl
  8006. * @type {Node<float>}
  8007. */
  8008. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8009. /**
  8010. * TSL object that represents the normal attribute of the current rendered object.
  8011. *
  8012. * @tsl
  8013. * @type {Node<vec3>}
  8014. */
  8015. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8016. /**
  8017. * TSL object that represents the vertex normal in local space of the current rendered object.
  8018. *
  8019. * @tsl
  8020. * @type {Node<vec3>}
  8021. */
  8022. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8023. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8024. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  8025. return vec3( 0, 1, 0 );
  8026. }
  8027. return normalGeometry;
  8028. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8029. /**
  8030. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8031. *
  8032. * @tsl
  8033. * @type {Node<vec3>}
  8034. */
  8035. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8036. /**
  8037. * TSL object that represents the vertex normal in view space of the current rendered object.
  8038. *
  8039. * @tsl
  8040. * @type {Node<vec3>}
  8041. */
  8042. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8043. let node;
  8044. if ( builder.material.flatShading === true ) {
  8045. node = normalFlat;
  8046. } else {
  8047. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8048. }
  8049. return node;
  8050. }, 'vec3' ).once() )().toVar( 'normalView' );
  8051. /**
  8052. * TSL object that represents the vertex normal in world space of the current rendered object.
  8053. *
  8054. * @tsl
  8055. * @type {Node<vec3>}
  8056. */
  8057. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  8058. /**
  8059. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8060. *
  8061. * @tsl
  8062. * @type {Node<vec3>}
  8063. */
  8064. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8065. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8066. return builder.context.setupNormal().context( { getUV: null } );
  8067. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  8068. /**
  8069. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8070. *
  8071. * @tsl
  8072. * @type {Node<vec3>}
  8073. */
  8074. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8075. /**
  8076. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8077. *
  8078. * @tsl
  8079. * @type {Node<vec3>}
  8080. */
  8081. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8082. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8083. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  8084. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  8085. /**
  8086. * Transforms the normal with the given matrix.
  8087. *
  8088. * @tsl
  8089. * @function
  8090. * @param {Node<vec3>} normal - The normal.
  8091. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8092. * @return {Node<vec3>} The transformed normal.
  8093. */
  8094. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8095. const m = mat3( matrix );
  8096. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8097. return m.mul( transformedNormal ).xyz;
  8098. } );
  8099. /**
  8100. * Transforms the given normal from local to view space.
  8101. *
  8102. * @tsl
  8103. * @function
  8104. * @param {Node<vec3>} normal - The normal.
  8105. * @param {NodeBuilder} builder - The current node builder.
  8106. * @return {Node<vec3>} The transformed normal.
  8107. */
  8108. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8109. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  8110. if ( modelNormalViewMatrix !== null ) {
  8111. return modelNormalViewMatrix.transformDirection( normal );
  8112. }
  8113. //
  8114. const transformedNormal = modelNormalMatrix.mul( normal );
  8115. return cameraViewMatrix.transformDirection( transformedNormal );
  8116. } );
  8117. /**
  8118. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8119. *
  8120. * @tsl
  8121. * @type {UniformNode<float>}
  8122. */
  8123. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  8124. /**
  8125. * The reflect vector in view space.
  8126. *
  8127. * @tsl
  8128. * @type {Node<vec3>}
  8129. */
  8130. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8131. /**
  8132. * The refract vector in view space.
  8133. *
  8134. * @tsl
  8135. * @type {Node<vec3>}
  8136. */
  8137. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8138. /**
  8139. * Used for sampling cube maps when using cube reflection mapping.
  8140. *
  8141. * @tsl
  8142. * @type {Node<vec3>}
  8143. */
  8144. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8145. /**
  8146. * Used for sampling cube maps when using cube refraction mapping.
  8147. *
  8148. * @tsl
  8149. * @type {Node<vec3>}
  8150. */
  8151. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8152. /**
  8153. * This type of uniform node represents a cube texture.
  8154. *
  8155. * @augments TextureNode
  8156. */
  8157. class CubeTextureNode extends TextureNode {
  8158. static get type() {
  8159. return 'CubeTextureNode';
  8160. }
  8161. /**
  8162. * Constructs a new cube texture node.
  8163. *
  8164. * @param {CubeTexture} value - The cube texture.
  8165. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8166. * @param {?Node<int>} [levelNode=null] - The level node.
  8167. * @param {?Node<float>} [biasNode=null] - The bias node.
  8168. */
  8169. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8170. super( value, uvNode, levelNode, biasNode );
  8171. /**
  8172. * This flag can be used for type testing.
  8173. *
  8174. * @type {boolean}
  8175. * @readonly
  8176. * @default true
  8177. */
  8178. this.isCubeTextureNode = true;
  8179. }
  8180. /**
  8181. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8182. *
  8183. * @param {NodeBuilder} builder - The current node builder.
  8184. * @return {string} The input type.
  8185. */
  8186. getInputType( /*builder*/ ) {
  8187. return 'cubeTexture';
  8188. }
  8189. /**
  8190. * Returns a default uvs based on the mapping type of the cube texture.
  8191. *
  8192. * @return {Node<vec3>} The default uv attribute.
  8193. */
  8194. getDefaultUV() {
  8195. const texture = this.value;
  8196. if ( texture.mapping === CubeReflectionMapping ) {
  8197. return reflectVector;
  8198. } else if ( texture.mapping === CubeRefractionMapping ) {
  8199. return refractVector;
  8200. } else {
  8201. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8202. return vec3( 0, 0, 0 );
  8203. }
  8204. }
  8205. /**
  8206. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8207. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8208. *
  8209. * @param {boolean} value - The update toggle.
  8210. */
  8211. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8212. /**
  8213. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8214. * to modify the uv node for correct sampling.
  8215. *
  8216. * @param {NodeBuilder} builder - The current node builder.
  8217. * @param {Node} uvNode - The uv node to setup.
  8218. * @return {Node} The updated uv node.
  8219. */
  8220. setupUV( builder, uvNode ) {
  8221. const texture = this.value;
  8222. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8223. return vec3( uvNode.x.negate(), uvNode.yz );
  8224. } else {
  8225. return uvNode;
  8226. }
  8227. }
  8228. /**
  8229. * Generates the uv code snippet.
  8230. *
  8231. * @param {NodeBuilder} builder - The current node builder.
  8232. * @param {Node} cubeUV - The uv node to generate code for.
  8233. * @return {string} The generated code snippet.
  8234. */
  8235. generateUV( builder, cubeUV ) {
  8236. return cubeUV.build( builder, 'vec3' );
  8237. }
  8238. }
  8239. /**
  8240. * TSL function for creating a cube texture node.
  8241. *
  8242. * @tsl
  8243. * @function
  8244. * @param {CubeTexture} value - The cube texture.
  8245. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8246. * @param {?Node<int>} [levelNode=null] - The level node.
  8247. * @param {?Node<float>} [biasNode=null] - The bias node.
  8248. * @returns {CubeTextureNode}
  8249. */
  8250. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8251. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8252. /**
  8253. * This class is only relevant if the referenced property is array-like.
  8254. * In this case, `ReferenceElementNode` allows to refer to a specific
  8255. * element inside the data structure via an index.
  8256. *
  8257. * @augments ArrayElementNode
  8258. */
  8259. class ReferenceElementNode extends ArrayElementNode {
  8260. static get type() {
  8261. return 'ReferenceElementNode';
  8262. }
  8263. /**
  8264. * Constructs a new reference element node.
  8265. *
  8266. * @param {?ReferenceNode} referenceNode - The reference node.
  8267. * @param {Node} indexNode - The index node that defines the element access.
  8268. */
  8269. constructor( referenceNode, indexNode ) {
  8270. super( referenceNode, indexNode );
  8271. /**
  8272. * Similar to {@link ReferenceNode#reference}, an additional
  8273. * property references to the current node.
  8274. *
  8275. * @type {?ReferenceNode}
  8276. * @default null
  8277. */
  8278. this.referenceNode = referenceNode;
  8279. /**
  8280. * This flag can be used for type testing.
  8281. *
  8282. * @type {boolean}
  8283. * @readonly
  8284. * @default true
  8285. */
  8286. this.isReferenceElementNode = true;
  8287. }
  8288. /**
  8289. * This method is overwritten since the node type is inferred from
  8290. * the uniform type of the reference node.
  8291. *
  8292. * @return {string} The node type.
  8293. */
  8294. getNodeType() {
  8295. return this.referenceNode.uniformType;
  8296. }
  8297. generate( builder ) {
  8298. const snippet = super.generate( builder );
  8299. const arrayType = this.referenceNode.getNodeType();
  8300. const elementType = this.getNodeType();
  8301. return builder.format( snippet, arrayType, elementType );
  8302. }
  8303. }
  8304. /**
  8305. * This type of node establishes a reference to a property of another object.
  8306. * In this way, the value of the node is automatically linked to the value of
  8307. * referenced object. Reference nodes internally represent the linked value
  8308. * as a uniform.
  8309. *
  8310. * @augments Node
  8311. */
  8312. class ReferenceNode extends Node {
  8313. static get type() {
  8314. return 'ReferenceNode';
  8315. }
  8316. /**
  8317. * Constructs a new reference node.
  8318. *
  8319. * @param {string} property - The name of the property the node refers to.
  8320. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8321. * @param {?Object} [object=null] - The object the property belongs to.
  8322. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8323. */
  8324. constructor( property, uniformType, object = null, count = null ) {
  8325. super();
  8326. /**
  8327. * The name of the property the node refers to.
  8328. *
  8329. * @type {string}
  8330. */
  8331. this.property = property;
  8332. /**
  8333. * The uniform type that should be used to represent the property value.
  8334. *
  8335. * @type {string}
  8336. */
  8337. this.uniformType = uniformType;
  8338. /**
  8339. * The object the property belongs to.
  8340. *
  8341. * @type {?Object}
  8342. * @default null
  8343. */
  8344. this.object = object;
  8345. /**
  8346. * When the linked property is an array, this parameter defines its length.
  8347. *
  8348. * @type {?number}
  8349. * @default null
  8350. */
  8351. this.count = count;
  8352. /**
  8353. * The property name might have dots so nested properties can be referred.
  8354. * The hierarchy of the names is stored inside this array.
  8355. *
  8356. * @type {Array<string>}
  8357. */
  8358. this.properties = property.split( '.' );
  8359. /**
  8360. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8361. * since the final reference might be updated from calling code.
  8362. *
  8363. * @type {?Object}
  8364. * @default null
  8365. */
  8366. this.reference = object;
  8367. /**
  8368. * The uniform node that holds the value of the reference node.
  8369. *
  8370. * @type {UniformNode}
  8371. * @default null
  8372. */
  8373. this.node = null;
  8374. /**
  8375. * The uniform group of the internal uniform.
  8376. *
  8377. * @type {UniformGroupNode}
  8378. * @default null
  8379. */
  8380. this.group = null;
  8381. /**
  8382. * An optional label of the internal uniform node.
  8383. *
  8384. * @type {?string}
  8385. * @default null
  8386. */
  8387. this.name = null;
  8388. /**
  8389. * Overwritten since reference nodes are updated per object.
  8390. *
  8391. * @type {string}
  8392. * @default 'object'
  8393. */
  8394. this.updateType = NodeUpdateType.OBJECT;
  8395. }
  8396. /**
  8397. * When the referred property is array-like, this method can be used
  8398. * to access elements via an index node.
  8399. *
  8400. * @param {IndexNode} indexNode - indexNode.
  8401. * @return {ReferenceElementNode} A reference to an element.
  8402. */
  8403. element( indexNode ) {
  8404. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8405. }
  8406. /**
  8407. * Sets the uniform group for this reference node.
  8408. *
  8409. * @param {UniformGroupNode} group - The uniform group to set.
  8410. * @return {ReferenceNode} A reference to this node.
  8411. */
  8412. setGroup( group ) {
  8413. this.group = group;
  8414. return this;
  8415. }
  8416. /**
  8417. * Sets the label for the internal uniform.
  8418. *
  8419. * @param {string} name - The label to set.
  8420. * @return {ReferenceNode} A reference to this node.
  8421. */
  8422. label( name ) {
  8423. this.name = name;
  8424. return this;
  8425. }
  8426. /**
  8427. * Sets the node type which automatically defines the internal
  8428. * uniform type.
  8429. *
  8430. * @param {string} uniformType - The type to set.
  8431. */
  8432. setNodeType( uniformType ) {
  8433. let node = null;
  8434. if ( this.count !== null ) {
  8435. node = buffer( null, uniformType, this.count );
  8436. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8437. node = uniformArray( null, uniformType );
  8438. } else if ( uniformType === 'texture' ) {
  8439. node = texture( null );
  8440. } else if ( uniformType === 'cubeTexture' ) {
  8441. node = cubeTexture( null );
  8442. } else {
  8443. node = uniform( null, uniformType );
  8444. }
  8445. if ( this.group !== null ) {
  8446. node.setGroup( this.group );
  8447. }
  8448. if ( this.name !== null ) node.label( this.name );
  8449. this.node = node.getSelf();
  8450. }
  8451. /**
  8452. * This method is overwritten since the node type is inferred from
  8453. * the type of the reference node.
  8454. *
  8455. * @param {NodeBuilder} builder - The current node builder.
  8456. * @return {string} The node type.
  8457. */
  8458. getNodeType( builder ) {
  8459. if ( this.node === null ) {
  8460. this.updateReference( builder );
  8461. this.updateValue();
  8462. }
  8463. return this.node.getNodeType( builder );
  8464. }
  8465. /**
  8466. * Returns the property value from the given referred object.
  8467. *
  8468. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8469. * @return {any} The value.
  8470. */
  8471. getValueFromReference( object = this.reference ) {
  8472. const { properties } = this;
  8473. let value = object[ properties[ 0 ] ];
  8474. for ( let i = 1; i < properties.length; i ++ ) {
  8475. value = value[ properties[ i ] ];
  8476. }
  8477. return value;
  8478. }
  8479. /**
  8480. * Allows to update the reference based on the given state. The state is only
  8481. * evaluated {@link ReferenceNode#object} is not set.
  8482. *
  8483. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8484. * @return {Object} The updated reference.
  8485. */
  8486. updateReference( state ) {
  8487. this.reference = this.object !== null ? this.object : state.object;
  8488. return this.reference;
  8489. }
  8490. /**
  8491. * The output of the reference node is the internal uniform node.
  8492. *
  8493. * @param {NodeBuilder} builder - The current node builder.
  8494. * @return {UniformNode} The output node.
  8495. */
  8496. setup( /* builder */ ) {
  8497. this.updateValue();
  8498. return this.node;
  8499. }
  8500. /**
  8501. * Overwritten to to update the internal uniform value.
  8502. *
  8503. * @param {NodeFrame} frame - A reference to the current node frame.
  8504. */
  8505. update( /*frame*/ ) {
  8506. this.updateValue();
  8507. }
  8508. /**
  8509. * Retrieves the value from the referred object property and uses it
  8510. * to updated the internal uniform.
  8511. */
  8512. updateValue() {
  8513. if ( this.node === null ) this.setNodeType( this.uniformType );
  8514. const value = this.getValueFromReference();
  8515. if ( Array.isArray( value ) ) {
  8516. this.node.array = value;
  8517. } else {
  8518. this.node.value = value;
  8519. }
  8520. }
  8521. }
  8522. /**
  8523. * TSL function for creating a reference node.
  8524. *
  8525. * @tsl
  8526. * @function
  8527. * @param {string} name - The name of the property the node refers to.
  8528. * @param {string} type - The uniform type that should be used to represent the property value.
  8529. * @param {Object} object - The object the property belongs to.
  8530. * @returns {ReferenceNode}
  8531. */
  8532. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8533. /**
  8534. * TSL function for creating a reference node. Use this function if you want need a reference
  8535. * to an array-like property that should be represented as a uniform buffer.
  8536. *
  8537. * @tsl
  8538. * @function
  8539. * @param {string} name - The name of the property the node refers to.
  8540. * @param {string} type - The uniform type that should be used to represent the property value.
  8541. * @param {number} count - The number of value inside the array-like object.
  8542. * @param {Object} object - An array-like object the property belongs to.
  8543. * @returns {ReferenceNode}
  8544. */
  8545. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8546. /**
  8547. * This node is a special type of reference node which is intended
  8548. * for linking material properties with node values.
  8549. * ```js
  8550. * const opacityNode = materialReference( 'opacity', 'float', material );
  8551. * ```
  8552. * When changing `material.opacity`, the node value of `opacityNode` will
  8553. * automatically be updated.
  8554. *
  8555. * @augments ReferenceNode
  8556. */
  8557. class MaterialReferenceNode extends ReferenceNode {
  8558. static get type() {
  8559. return 'MaterialReferenceNode';
  8560. }
  8561. /**
  8562. * Constructs a new material reference node.
  8563. *
  8564. * @param {string} property - The name of the property the node refers to.
  8565. * @param {string} inputType - The uniform type that should be used to represent the property value.
  8566. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  8567. * the node refers to the material of the current rendered object.
  8568. */
  8569. constructor( property, inputType, material = null ) {
  8570. super( property, inputType, material );
  8571. /**
  8572. * The material the property belongs to. When no material is set,
  8573. * the node refers to the material of the current rendered object.
  8574. *
  8575. * @type {?Material}
  8576. * @default null
  8577. */
  8578. this.material = material;
  8579. /**
  8580. * This flag can be used for type testing.
  8581. *
  8582. * @type {boolean}
  8583. * @readonly
  8584. * @default true
  8585. */
  8586. this.isMaterialReferenceNode = true;
  8587. }
  8588. /**
  8589. * Updates the reference based on the given state. The state is only evaluated
  8590. * {@link MaterialReferenceNode#material} is not set.
  8591. *
  8592. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8593. * @return {Object} The updated reference.
  8594. */
  8595. updateReference( state ) {
  8596. this.reference = this.material !== null ? this.material : state.material;
  8597. return this.reference;
  8598. }
  8599. }
  8600. /**
  8601. * TSL function for creating a material reference node.
  8602. *
  8603. * @tsl
  8604. * @function
  8605. * @param {string} name - The name of the property the node refers to.
  8606. * @param {string} type - The uniform type that should be used to represent the property value.
  8607. * @param {?Material} [material=null] - The material the property belongs to.
  8608. * When no material is set, the node refers to the material of the current rendered object.
  8609. * @returns {MaterialReferenceNode}
  8610. */
  8611. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8612. /**
  8613. * TSL object that represents the tangent attribute of the current rendered object.
  8614. *
  8615. * @tsl
  8616. * @type {Node<vec4>}
  8617. */
  8618. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8619. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8620. builder.geometry.computeTangents();
  8621. }
  8622. return attribute( 'tangent', 'vec4' );
  8623. } )();
  8624. /**
  8625. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8626. *
  8627. * @tsl
  8628. * @type {Node<vec3>}
  8629. */
  8630. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8631. /**
  8632. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8633. *
  8634. * @tsl
  8635. * @type {Node<vec3>}
  8636. */
  8637. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8638. /**
  8639. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8640. *
  8641. * @tsl
  8642. * @type {Node<vec3>}
  8643. */
  8644. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8645. /**
  8646. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8647. *
  8648. * @tsl
  8649. * @type {Node<vec3>}
  8650. */
  8651. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8652. /**
  8653. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8654. *
  8655. * @tsl
  8656. * @type {Node<vec3>}
  8657. */
  8658. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8659. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8660. /**
  8661. * TSL object that represents the bitangent attribute of the current rendered object.
  8662. *
  8663. * @tsl
  8664. * @type {Node<vec3>}
  8665. */
  8666. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8667. /**
  8668. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8669. *
  8670. * @tsl
  8671. * @type {Node<vec3>}
  8672. */
  8673. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8674. /**
  8675. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8676. *
  8677. * @tsl
  8678. * @type {Node<vec4>}
  8679. */
  8680. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8681. /**
  8682. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8683. *
  8684. * @tsl
  8685. * @type {Node<vec4>}
  8686. */
  8687. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8688. /**
  8689. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8690. *
  8691. * @tsl
  8692. * @type {Node<vec4>}
  8693. */
  8694. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8695. /**
  8696. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8697. *
  8698. * @tsl
  8699. * @type {Node<vec4>}
  8700. */
  8701. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8702. /**
  8703. * TSL object that represents the TBN matrix in view space.
  8704. *
  8705. * @tsl
  8706. * @type {Node<mat3>}
  8707. */
  8708. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8709. /**
  8710. * TSL object that represents the parallax direction.
  8711. *
  8712. * @tsl
  8713. * @type {Node<mat3>}
  8714. */
  8715. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8716. /**
  8717. * TSL function for computing parallax uv coordinates.
  8718. *
  8719. * @tsl
  8720. * @function
  8721. * @param {Node<vec2>} uv - A uv node.
  8722. * @param {Node<vec2>} scale - A scale node.
  8723. * @returns {Node<vec2>} Parallax uv coordinates.
  8724. */
  8725. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8726. /**
  8727. * TSL function for computing bent normals.
  8728. *
  8729. * @tsl
  8730. * @function
  8731. * @returns {Node<vec3>} Bent normals.
  8732. */
  8733. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8734. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8735. let bentNormal = anisotropyB.cross( positionViewDirection );
  8736. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8737. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8738. return bentNormal;
  8739. } )();
  8740. // Normal Mapping Without Precomputed Tangents
  8741. // http://www.thetenthplanet.de/archives/1180
  8742. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8743. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8744. const q0 = eye_pos.dFdx();
  8745. const q1 = eye_pos.dFdy();
  8746. const st0 = uv.dFdx();
  8747. const st1 = uv.dFdy();
  8748. const N = surf_norm; // normalized
  8749. const q1perp = q1.cross( N );
  8750. const q0perp = N.cross( q0 );
  8751. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8752. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8753. const det = T.dot( T ).max( B.dot( B ) );
  8754. const scale = faceDirection.mul( det.inverseSqrt() );
  8755. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8756. } );
  8757. /**
  8758. * This class can be used for applying normals maps to materials.
  8759. *
  8760. * ```js
  8761. * material.normalNode = normalMap( texture( normalTex ) );
  8762. * ```
  8763. *
  8764. * @augments TempNode
  8765. */
  8766. class NormalMapNode extends TempNode {
  8767. static get type() {
  8768. return 'NormalMapNode';
  8769. }
  8770. /**
  8771. * Constructs a new normal map node.
  8772. *
  8773. * @param {Node<vec3>} node - Represents the normal map data.
  8774. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8775. */
  8776. constructor( node, scaleNode = null ) {
  8777. super( 'vec3' );
  8778. /**
  8779. * Represents the normal map data.
  8780. *
  8781. * @type {Node<vec3>}
  8782. */
  8783. this.node = node;
  8784. /**
  8785. * Controls the intensity of the effect.
  8786. *
  8787. * @type {?Node<vec2>}
  8788. * @default null
  8789. */
  8790. this.scaleNode = scaleNode;
  8791. /**
  8792. * The normal map type.
  8793. *
  8794. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8795. * @default TangentSpaceNormalMap
  8796. */
  8797. this.normalMapType = TangentSpaceNormalMap;
  8798. }
  8799. setup( builder ) {
  8800. const { normalMapType, scaleNode } = this;
  8801. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8802. if ( scaleNode !== null ) {
  8803. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8804. }
  8805. let outputNode = null;
  8806. if ( normalMapType === ObjectSpaceNormalMap ) {
  8807. outputNode = transformNormalToView( normalMap );
  8808. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8809. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8810. if ( tangent === true ) {
  8811. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8812. } else {
  8813. outputNode = perturbNormal2Arb( {
  8814. eye_pos: positionView,
  8815. surf_norm: normalView,
  8816. mapN: normalMap,
  8817. uv: uv()
  8818. } );
  8819. }
  8820. }
  8821. return outputNode;
  8822. }
  8823. }
  8824. /**
  8825. * TSL function for creating a normal map node.
  8826. *
  8827. * @tsl
  8828. * @function
  8829. * @param {Node<vec3>} node - Represents the normal map data.
  8830. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8831. * @returns {NormalMapNode}
  8832. */
  8833. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8834. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8835. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8836. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8837. // It's used to preserve the same TextureNode instance
  8838. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8839. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8840. return vec2(
  8841. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8842. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8843. ).mul( bumpScale );
  8844. } );
  8845. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8846. const perturbNormalArb = Fn( ( inputs ) => {
  8847. const { surf_pos, surf_norm, dHdxy } = inputs;
  8848. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8849. const vSigmaX = surf_pos.dFdx().normalize();
  8850. const vSigmaY = surf_pos.dFdy().normalize();
  8851. const vN = surf_norm; // normalized
  8852. const R1 = vSigmaY.cross( vN );
  8853. const R2 = vN.cross( vSigmaX );
  8854. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8855. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8856. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8857. } );
  8858. /**
  8859. * This class can be used for applying bump maps to materials.
  8860. *
  8861. * ```js
  8862. * material.normalNode = bumpMap( texture( bumpTex ) );
  8863. * ```
  8864. *
  8865. * @augments TempNode
  8866. */
  8867. class BumpMapNode extends TempNode {
  8868. static get type() {
  8869. return 'BumpMapNode';
  8870. }
  8871. /**
  8872. * Constructs a new bump map node.
  8873. *
  8874. * @param {Node<float>} textureNode - Represents the bump map data.
  8875. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8876. */
  8877. constructor( textureNode, scaleNode = null ) {
  8878. super( 'vec3' );
  8879. /**
  8880. * Represents the bump map data.
  8881. *
  8882. * @type {Node<float>}
  8883. */
  8884. this.textureNode = textureNode;
  8885. /**
  8886. * Controls the intensity of the bump effect.
  8887. *
  8888. * @type {?Node<float>}
  8889. * @default null
  8890. */
  8891. this.scaleNode = scaleNode;
  8892. }
  8893. setup() {
  8894. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8895. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8896. return perturbNormalArb( {
  8897. surf_pos: positionView,
  8898. surf_norm: normalView,
  8899. dHdxy
  8900. } );
  8901. }
  8902. }
  8903. /**
  8904. * TSL function for creating a bump map node.
  8905. *
  8906. * @tsl
  8907. * @function
  8908. * @param {Node<float>} textureNode - Represents the bump map data.
  8909. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8910. * @returns {BumpMapNode}
  8911. */
  8912. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8913. const _propertyCache = new Map();
  8914. /**
  8915. * This class should simplify the node access to material properties.
  8916. * It internal uses reference nodes to make sure changes to material
  8917. * properties are automatically reflected to predefined TSL objects
  8918. * like e.g. `materialColor`.
  8919. *
  8920. * @augments Node
  8921. */
  8922. class MaterialNode extends Node {
  8923. static get type() {
  8924. return 'MaterialNode';
  8925. }
  8926. /**
  8927. * Constructs a new material node.
  8928. *
  8929. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  8930. */
  8931. constructor( scope ) {
  8932. super();
  8933. /**
  8934. * The scope defines what material property is referred by the node.
  8935. *
  8936. * @type {string}
  8937. */
  8938. this.scope = scope;
  8939. }
  8940. /**
  8941. * Returns a cached reference node for the given property and type.
  8942. *
  8943. * @param {string} property - The name of the material property.
  8944. * @param {string} type - The uniform type of the property.
  8945. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8946. */
  8947. getCache( property, type ) {
  8948. let node = _propertyCache.get( property );
  8949. if ( node === undefined ) {
  8950. node = materialReference( property, type );
  8951. _propertyCache.set( property, node );
  8952. }
  8953. return node;
  8954. }
  8955. /**
  8956. * Returns a float-typed material reference node for the given property name.
  8957. *
  8958. * @param {string} property - The name of the material property.
  8959. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8960. */
  8961. getFloat( property ) {
  8962. return this.getCache( property, 'float' );
  8963. }
  8964. /**
  8965. * Returns a color-typed material reference node for the given property name.
  8966. *
  8967. * @param {string} property - The name of the material property.
  8968. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8969. */
  8970. getColor( property ) {
  8971. return this.getCache( property, 'color' );
  8972. }
  8973. /**
  8974. * Returns a texture-typed material reference node for the given property name.
  8975. *
  8976. * @param {string} property - The name of the material property.
  8977. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8978. */
  8979. getTexture( property ) {
  8980. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8981. }
  8982. /**
  8983. * The node setup is done depending on the selected scope. Multiple material properties
  8984. * might be grouped into a single node composition if they logically belong together.
  8985. *
  8986. * @param {NodeBuilder} builder - The current node builder.
  8987. * @return {Node} The node representing the selected scope.
  8988. */
  8989. setup( builder ) {
  8990. const material = builder.context.material;
  8991. const scope = this.scope;
  8992. let node = null;
  8993. if ( scope === MaterialNode.COLOR ) {
  8994. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8995. if ( material.map && material.map.isTexture === true ) {
  8996. node = colorNode.mul( this.getTexture( 'map' ) );
  8997. } else {
  8998. node = colorNode;
  8999. }
  9000. } else if ( scope === MaterialNode.OPACITY ) {
  9001. const opacityNode = this.getFloat( scope );
  9002. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9003. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9004. } else {
  9005. node = opacityNode;
  9006. }
  9007. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9008. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9009. node = this.getTexture( 'specular' ).r;
  9010. } else {
  9011. node = float( 1 );
  9012. }
  9013. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9014. const specularIntensityNode = this.getFloat( scope );
  9015. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9016. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9017. } else {
  9018. node = specularIntensityNode;
  9019. }
  9020. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9021. const specularColorNode = this.getColor( scope );
  9022. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9023. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9024. } else {
  9025. node = specularColorNode;
  9026. }
  9027. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9028. const roughnessNode = this.getFloat( scope );
  9029. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9030. node = roughnessNode.mul( this.getTexture( scope ).g );
  9031. } else {
  9032. node = roughnessNode;
  9033. }
  9034. } else if ( scope === MaterialNode.METALNESS ) {
  9035. const metalnessNode = this.getFloat( scope );
  9036. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9037. node = metalnessNode.mul( this.getTexture( scope ).b );
  9038. } else {
  9039. node = metalnessNode;
  9040. }
  9041. } else if ( scope === MaterialNode.EMISSIVE ) {
  9042. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9043. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9044. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9045. node = emissiveNode.mul( this.getTexture( scope ) );
  9046. } else {
  9047. node = emissiveNode;
  9048. }
  9049. } else if ( scope === MaterialNode.NORMAL ) {
  9050. if ( material.normalMap ) {
  9051. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9052. node.normalMapType = material.normalMapType;
  9053. } else if ( material.bumpMap ) {
  9054. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9055. } else {
  9056. node = normalView;
  9057. }
  9058. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9059. const clearcoatNode = this.getFloat( scope );
  9060. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9061. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9062. } else {
  9063. node = clearcoatNode;
  9064. }
  9065. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9066. const clearcoatRoughnessNode = this.getFloat( scope );
  9067. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9068. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9069. } else {
  9070. node = clearcoatRoughnessNode;
  9071. }
  9072. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9073. if ( material.clearcoatNormalMap ) {
  9074. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9075. } else {
  9076. node = normalView;
  9077. }
  9078. } else if ( scope === MaterialNode.SHEEN ) {
  9079. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9080. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9081. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9082. } else {
  9083. node = sheenNode;
  9084. }
  9085. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9086. const sheenRoughnessNode = this.getFloat( scope );
  9087. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9088. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9089. } else {
  9090. node = sheenRoughnessNode;
  9091. }
  9092. node = node.clamp( 0.07, 1.0 );
  9093. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9094. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9095. const anisotropyPolar = this.getTexture( scope );
  9096. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9097. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9098. } else {
  9099. node = materialAnisotropyVector;
  9100. }
  9101. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9102. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9103. if ( material.iridescenceThicknessMap ) {
  9104. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9105. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9106. } else {
  9107. node = iridescenceThicknessMaximum;
  9108. }
  9109. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9110. const transmissionNode = this.getFloat( scope );
  9111. if ( material.transmissionMap ) {
  9112. node = transmissionNode.mul( this.getTexture( scope ).r );
  9113. } else {
  9114. node = transmissionNode;
  9115. }
  9116. } else if ( scope === MaterialNode.THICKNESS ) {
  9117. const thicknessNode = this.getFloat( scope );
  9118. if ( material.thicknessMap ) {
  9119. node = thicknessNode.mul( this.getTexture( scope ).g );
  9120. } else {
  9121. node = thicknessNode;
  9122. }
  9123. } else if ( scope === MaterialNode.IOR ) {
  9124. node = this.getFloat( scope );
  9125. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9126. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9127. } else if ( scope === MaterialNode.AO ) {
  9128. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9129. } else {
  9130. const outputType = this.getNodeType( builder );
  9131. node = this.getCache( scope, outputType );
  9132. }
  9133. return node;
  9134. }
  9135. }
  9136. MaterialNode.ALPHA_TEST = 'alphaTest';
  9137. MaterialNode.COLOR = 'color';
  9138. MaterialNode.OPACITY = 'opacity';
  9139. MaterialNode.SHININESS = 'shininess';
  9140. MaterialNode.SPECULAR = 'specular';
  9141. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9142. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9143. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9144. MaterialNode.REFLECTIVITY = 'reflectivity';
  9145. MaterialNode.ROUGHNESS = 'roughness';
  9146. MaterialNode.METALNESS = 'metalness';
  9147. MaterialNode.NORMAL = 'normal';
  9148. MaterialNode.CLEARCOAT = 'clearcoat';
  9149. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9150. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9151. MaterialNode.EMISSIVE = 'emissive';
  9152. MaterialNode.ROTATION = 'rotation';
  9153. MaterialNode.SHEEN = 'sheen';
  9154. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9155. MaterialNode.ANISOTROPY = 'anisotropy';
  9156. MaterialNode.IRIDESCENCE = 'iridescence';
  9157. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9158. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9159. MaterialNode.IOR = 'ior';
  9160. MaterialNode.TRANSMISSION = 'transmission';
  9161. MaterialNode.THICKNESS = 'thickness';
  9162. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9163. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9164. MaterialNode.LINE_SCALE = 'scale';
  9165. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9166. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9167. MaterialNode.LINE_WIDTH = 'linewidth';
  9168. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9169. MaterialNode.POINT_SIZE = 'size';
  9170. MaterialNode.DISPERSION = 'dispersion';
  9171. MaterialNode.LIGHT_MAP = 'light';
  9172. MaterialNode.AO = 'ao';
  9173. /**
  9174. * TSL object that represents alpha test of the current material.
  9175. *
  9176. * @tsl
  9177. * @type {Node<float>}
  9178. */
  9179. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9180. /**
  9181. * TSL object that represents the diffuse color of the current material.
  9182. * The value is composed via `color` * `map`.
  9183. *
  9184. * @tsl
  9185. * @type {Node<vec3>}
  9186. */
  9187. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9188. /**
  9189. * TSL object that represents the shininess of the current material.
  9190. *
  9191. * @tsl
  9192. * @type {Node<float>}
  9193. */
  9194. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9195. /**
  9196. * TSL object that represents the emissive color of the current material.
  9197. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9198. *
  9199. * @tsl
  9200. * @type {Node<vec3>}
  9201. */
  9202. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9203. /**
  9204. * TSL object that represents the opacity of the current material.
  9205. * The value is composed via `opacity` * `alphaMap`.
  9206. *
  9207. * @tsl
  9208. * @type {Node<float>}
  9209. */
  9210. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9211. /**
  9212. * TSL object that represents the specular of the current material.
  9213. *
  9214. * @tsl
  9215. * @type {Node<vec3>}
  9216. */
  9217. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9218. /**
  9219. * TSL object that represents the specular intensity of the current material.
  9220. * The value is composed via `specularIntensity` * `specularMap.a`.
  9221. *
  9222. * @tsl
  9223. * @type {Node<float>}
  9224. */
  9225. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9226. /**
  9227. * TSL object that represents the specular color of the current material.
  9228. * The value is composed via `specularColor` * `specularMap.rgb`.
  9229. *
  9230. * @tsl
  9231. * @type {Node<vec3>}
  9232. */
  9233. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9234. /**
  9235. * TSL object that represents the specular strength of the current material.
  9236. * The value is composed via `specularMap.r`.
  9237. *
  9238. * @tsl
  9239. * @type {Node<float>}
  9240. */
  9241. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9242. /**
  9243. * TSL object that represents the reflectivity of the current material.
  9244. *
  9245. * @tsl
  9246. * @type {Node<float>}
  9247. */
  9248. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9249. /**
  9250. * TSL object that represents the roughness of the current material.
  9251. * The value is composed via `roughness` * `roughnessMap.g`.
  9252. *
  9253. * @tsl
  9254. * @type {Node<float>}
  9255. */
  9256. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9257. /**
  9258. * TSL object that represents the metalness of the current material.
  9259. * The value is composed via `metalness` * `metalnessMap.b`.
  9260. *
  9261. * @tsl
  9262. * @type {Node<float>}
  9263. */
  9264. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9265. /**
  9266. * TSL object that represents the normal of the current material.
  9267. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9268. *
  9269. * @tsl
  9270. * @type {Node<vec3>}
  9271. */
  9272. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9273. /**
  9274. * TSL object that represents the clearcoat of the current material.
  9275. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9276. *
  9277. * @tsl
  9278. * @type {Node<float>}
  9279. */
  9280. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9281. /**
  9282. * TSL object that represents the clearcoat roughness of the current material.
  9283. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9284. *
  9285. * @tsl
  9286. * @type {Node<float>}
  9287. */
  9288. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9289. /**
  9290. * TSL object that represents the clearcoat normal of the current material.
  9291. * The value will be either `clearcoatNormalMap` or `normalView`.
  9292. *
  9293. * @tsl
  9294. * @type {Node<vec3>}
  9295. */
  9296. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9297. /**
  9298. * TSL object that represents the rotation of the current sprite material.
  9299. *
  9300. * @tsl
  9301. * @type {Node<float>}
  9302. */
  9303. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9304. /**
  9305. * TSL object that represents the sheen color of the current material.
  9306. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9307. *
  9308. * @tsl
  9309. * @type {Node<vec3>}
  9310. */
  9311. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9312. /**
  9313. * TSL object that represents the sheen roughness of the current material.
  9314. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9315. *
  9316. * @tsl
  9317. * @type {Node<float>}
  9318. */
  9319. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9320. /**
  9321. * TSL object that represents the anisotropy of the current material.
  9322. *
  9323. * @tsl
  9324. * @type {Node<vec2>}
  9325. */
  9326. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9327. /**
  9328. * TSL object that represents the iridescence of the current material.
  9329. *
  9330. * @tsl
  9331. * @type {Node<float>}
  9332. */
  9333. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9334. /**
  9335. * TSL object that represents the iridescence IOR of the current material.
  9336. *
  9337. * @tsl
  9338. * @type {Node<float>}
  9339. */
  9340. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9341. /**
  9342. * TSL object that represents the iridescence thickness of the current material.
  9343. *
  9344. * @tsl
  9345. * @type {Node<float>}
  9346. */
  9347. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9348. /**
  9349. * TSL object that represents the transmission of the current material.
  9350. * The value is composed via `transmission` * `transmissionMap.r`.
  9351. *
  9352. * @tsl
  9353. * @type {Node<float>}
  9354. */
  9355. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9356. /**
  9357. * TSL object that represents the thickness of the current material.
  9358. * The value is composed via `thickness` * `thicknessMap.g`.
  9359. *
  9360. * @tsl
  9361. * @type {Node<float>}
  9362. */
  9363. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9364. /**
  9365. * TSL object that represents the IOR of the current material.
  9366. *
  9367. * @tsl
  9368. * @type {Node<float>}
  9369. */
  9370. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9371. /**
  9372. * TSL object that represents the attenuation distance of the current material.
  9373. *
  9374. * @tsl
  9375. * @type {Node<float>}
  9376. */
  9377. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9378. /**
  9379. * TSL object that represents the attenuation color of the current material.
  9380. *
  9381. * @tsl
  9382. * @type {Node<vec3>}
  9383. */
  9384. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9385. /**
  9386. * TSL object that represents the scale of the current dashed line material.
  9387. *
  9388. * @tsl
  9389. * @type {Node<float>}
  9390. */
  9391. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9392. /**
  9393. * TSL object that represents the dash size of the current dashed line material.
  9394. *
  9395. * @tsl
  9396. * @type {Node<float>}
  9397. */
  9398. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9399. /**
  9400. * TSL object that represents the gap size of the current dashed line material.
  9401. *
  9402. * @tsl
  9403. * @type {Node<float>}
  9404. */
  9405. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9406. /**
  9407. * TSL object that represents the line width of the current line material.
  9408. *
  9409. * @tsl
  9410. * @type {Node<float>}
  9411. */
  9412. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9413. /**
  9414. * TSL object that represents the dash offset of the current line material.
  9415. *
  9416. * @tsl
  9417. * @type {Node<float>}
  9418. */
  9419. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9420. /**
  9421. * TSL object that represents the point size of the current points material.
  9422. *
  9423. * @tsl
  9424. * @type {Node<float>}
  9425. */
  9426. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9427. /**
  9428. * TSL object that represents the dispersion of the current material.
  9429. *
  9430. * @tsl
  9431. * @type {Node<float>}
  9432. */
  9433. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9434. /**
  9435. * TSL object that represents the light map of the current material.
  9436. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9437. *
  9438. * @tsl
  9439. * @type {Node<vec3>}
  9440. */
  9441. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9442. /**
  9443. * TSL object that represents the ambient occlusion map of the current material.
  9444. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9445. *
  9446. * @tsl
  9447. * @type {Node<float>}
  9448. */
  9449. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9450. /**
  9451. * TSL object that represents the anisotropy vector of the current material.
  9452. *
  9453. * @tsl
  9454. * @type {Node<vec2>}
  9455. */
  9456. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9457. return frame.material;
  9458. } ).onRenderUpdate( function ( { material } ) {
  9459. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9460. } );
  9461. /**
  9462. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9463. *
  9464. * @tsl
  9465. * @type {VaryingNode<vec4>}
  9466. */
  9467. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9468. return builder.context.setupModelViewProjection();
  9469. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9470. /**
  9471. * This class represents shader indices of different types. The following predefined node
  9472. * objects cover frequent use cases:
  9473. *
  9474. * - `vertexIndex`: The index of a vertex within a mesh.
  9475. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9476. * - `drawIndex`: The index of a draw call.
  9477. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9478. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9479. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9480. *
  9481. * @augments Node
  9482. */
  9483. class IndexNode extends Node {
  9484. static get type() {
  9485. return 'IndexNode';
  9486. }
  9487. /**
  9488. * Constructs a new index node.
  9489. *
  9490. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9491. */
  9492. constructor( scope ) {
  9493. super( 'uint' );
  9494. /**
  9495. * The scope of the index node.
  9496. *
  9497. * @type {string}
  9498. */
  9499. this.scope = scope;
  9500. /**
  9501. * This flag can be used for type testing.
  9502. *
  9503. * @type {boolean}
  9504. * @readonly
  9505. * @default true
  9506. */
  9507. this.isIndexNode = true;
  9508. }
  9509. generate( builder ) {
  9510. const nodeType = this.getNodeType( builder );
  9511. const scope = this.scope;
  9512. let propertyName;
  9513. if ( scope === IndexNode.VERTEX ) {
  9514. propertyName = builder.getVertexIndex();
  9515. } else if ( scope === IndexNode.INSTANCE ) {
  9516. propertyName = builder.getInstanceIndex();
  9517. } else if ( scope === IndexNode.DRAW ) {
  9518. propertyName = builder.getDrawIndex();
  9519. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9520. propertyName = builder.getInvocationLocalIndex();
  9521. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9522. propertyName = builder.getInvocationSubgroupIndex();
  9523. } else if ( scope === IndexNode.SUBGROUP ) {
  9524. propertyName = builder.getSubgroupIndex();
  9525. } else {
  9526. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9527. }
  9528. let output;
  9529. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9530. output = propertyName;
  9531. } else {
  9532. const nodeVarying = varying( this );
  9533. output = nodeVarying.build( builder, nodeType );
  9534. }
  9535. return output;
  9536. }
  9537. }
  9538. IndexNode.VERTEX = 'vertex';
  9539. IndexNode.INSTANCE = 'instance';
  9540. IndexNode.SUBGROUP = 'subgroup';
  9541. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9542. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9543. IndexNode.DRAW = 'draw';
  9544. /**
  9545. * TSL object that represents the index of a vertex within a mesh.
  9546. *
  9547. * @tsl
  9548. * @type {IndexNode}
  9549. */
  9550. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9551. /**
  9552. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9553. *
  9554. * @tsl
  9555. * @type {IndexNode}
  9556. */
  9557. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9558. /**
  9559. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9560. *
  9561. * @tsl
  9562. * @type {IndexNode}
  9563. */
  9564. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9565. /**
  9566. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9567. *
  9568. * @tsl
  9569. * @type {IndexNode}
  9570. */
  9571. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9572. /**
  9573. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9574. *
  9575. * @tsl
  9576. * @type {IndexNode}
  9577. */
  9578. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9579. /**
  9580. * TSL object that represents the index of a draw call.
  9581. *
  9582. * @tsl
  9583. * @type {IndexNode}
  9584. */
  9585. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9586. /**
  9587. * This node implements the vertex shader logic which is required
  9588. * when rendering 3D objects via instancing. The code makes sure
  9589. * vertex positions, normals and colors can be modified via instanced
  9590. * data.
  9591. *
  9592. * @augments Node
  9593. */
  9594. class InstanceNode extends Node {
  9595. static get type() {
  9596. return 'InstanceNode';
  9597. }
  9598. /**
  9599. * Constructs a new instance node.
  9600. *
  9601. * @param {number} count - The number of instances.
  9602. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9603. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9604. */
  9605. constructor( count, instanceMatrix, instanceColor ) {
  9606. super( 'void' );
  9607. /**
  9608. * The number of instances.
  9609. *
  9610. * @type {number}
  9611. */
  9612. this.count = count;
  9613. /**
  9614. * Instanced buffer attribute representing the transformation of instances.
  9615. *
  9616. * @type {InstancedBufferAttribute}
  9617. */
  9618. this.instanceMatrix = instanceMatrix;
  9619. /**
  9620. * Instanced buffer attribute representing the color of instances.
  9621. *
  9622. * @type {InstancedBufferAttribute}
  9623. */
  9624. this.instanceColor = instanceColor;
  9625. /**
  9626. * The node that represents the instance matrix data.
  9627. *
  9628. * @type {Node}
  9629. */
  9630. this.instanceMatrixNode = null;
  9631. /**
  9632. * The node that represents the instance color data.
  9633. *
  9634. * @type {Node}
  9635. */
  9636. this.instanceColorNode = null;
  9637. /**
  9638. * The update type is set to `frame` since an update
  9639. * of instanced buffer data must be checked per frame.
  9640. *
  9641. * @type {string}
  9642. * @default 'frame'
  9643. */
  9644. this.updateType = NodeUpdateType.FRAME;
  9645. /**
  9646. * A reference to a buffer that is used by `instanceMatrixNode`.
  9647. *
  9648. * @type {InstancedInterleavedBuffer}
  9649. */
  9650. this.buffer = null;
  9651. /**
  9652. * A reference to a buffer that is used by `instanceColorNode`.
  9653. *
  9654. * @type {InstancedBufferAttribute}
  9655. */
  9656. this.bufferColor = null;
  9657. }
  9658. /**
  9659. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9660. * to predefined node variables for accumulation. That follows the same patterns
  9661. * like with morph and skinning nodes.
  9662. *
  9663. * @param {NodeBuilder} builder - The current node builder.
  9664. */
  9665. setup( builder ) {
  9666. const { count, instanceMatrix, instanceColor } = this;
  9667. let { instanceMatrixNode, instanceColorNode } = this;
  9668. if ( instanceMatrixNode === null ) {
  9669. // 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.
  9670. if ( count <= 1000 ) {
  9671. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9672. } else {
  9673. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9674. this.buffer = buffer;
  9675. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9676. const instanceBuffers = [
  9677. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9678. bufferFn( buffer, 'vec4', 16, 0 ),
  9679. bufferFn( buffer, 'vec4', 16, 4 ),
  9680. bufferFn( buffer, 'vec4', 16, 8 ),
  9681. bufferFn( buffer, 'vec4', 16, 12 )
  9682. ];
  9683. instanceMatrixNode = mat4( ...instanceBuffers );
  9684. }
  9685. this.instanceMatrixNode = instanceMatrixNode;
  9686. }
  9687. if ( instanceColor && instanceColorNode === null ) {
  9688. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9689. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9690. this.bufferColor = buffer;
  9691. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9692. this.instanceColorNode = instanceColorNode;
  9693. }
  9694. // POSITION
  9695. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9696. positionLocal.assign( instancePosition );
  9697. // NORMAL
  9698. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9699. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9700. // ASSIGNS
  9701. normalLocal.assign( instanceNormal );
  9702. }
  9703. // COLOR
  9704. if ( this.instanceColorNode !== null ) {
  9705. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9706. }
  9707. }
  9708. /**
  9709. * Checks if the internal buffers required an update.
  9710. *
  9711. * @param {NodeFrame} frame - The current node frame.
  9712. */
  9713. update( /*frame*/ ) {
  9714. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9715. this.buffer.version = this.instanceMatrix.version;
  9716. }
  9717. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9718. this.bufferColor.version = this.instanceColor.version;
  9719. }
  9720. }
  9721. }
  9722. /**
  9723. * TSL function for creating an instance node.
  9724. *
  9725. * @tsl
  9726. * @function
  9727. * @param {number} count - The number of instances.
  9728. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9729. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9730. * @returns {InstanceNode}
  9731. */
  9732. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9733. /**
  9734. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9735. * It allows an easier setup of the instance node.
  9736. *
  9737. * @augments InstanceNode
  9738. */
  9739. class InstancedMeshNode extends InstanceNode {
  9740. static get type() {
  9741. return 'InstancedMeshNode';
  9742. }
  9743. /**
  9744. * Constructs a new instanced mesh node.
  9745. *
  9746. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9747. */
  9748. constructor( instancedMesh ) {
  9749. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9750. super( count, instanceMatrix, instanceColor );
  9751. /**
  9752. * A reference to the instanced mesh.
  9753. *
  9754. * @type {InstancedMesh}
  9755. */
  9756. this.instancedMesh = instancedMesh;
  9757. }
  9758. }
  9759. /**
  9760. * TSL function for creating an instanced mesh node.
  9761. *
  9762. * @tsl
  9763. * @function
  9764. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9765. * @returns {InstancedMeshNode}
  9766. */
  9767. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9768. /**
  9769. * This node implements the vertex shader logic which is required
  9770. * when rendering 3D objects via batching. `BatchNode` must be used
  9771. * with instances of {@link BatchedMesh}.
  9772. *
  9773. * @augments Node
  9774. */
  9775. class BatchNode extends Node {
  9776. static get type() {
  9777. return 'BatchNode';
  9778. }
  9779. /**
  9780. * Constructs a new batch node.
  9781. *
  9782. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9783. */
  9784. constructor( batchMesh ) {
  9785. super( 'void' );
  9786. /**
  9787. * A reference to batched mesh.
  9788. *
  9789. * @type {BatchedMesh}
  9790. */
  9791. this.batchMesh = batchMesh;
  9792. /**
  9793. * The batching index node.
  9794. *
  9795. * @type {?IndexNode}
  9796. * @default null
  9797. */
  9798. this.batchingIdNode = null;
  9799. }
  9800. /**
  9801. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9802. * to predefined node variables for accumulation. That follows the same patterns
  9803. * like with morph and skinning nodes.
  9804. *
  9805. * @param {NodeBuilder} builder - The current node builder.
  9806. */
  9807. setup( builder ) {
  9808. if ( this.batchingIdNode === null ) {
  9809. if ( builder.getDrawIndex() === null ) {
  9810. this.batchingIdNode = instanceIndex;
  9811. } else {
  9812. this.batchingIdNode = drawIndex;
  9813. }
  9814. }
  9815. const getIndirectIndex = Fn( ( [ id ] ) => {
  9816. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9817. const x = int( id ).modInt( size );
  9818. const y = int( id ).div( size );
  9819. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9820. } ).setLayout( {
  9821. name: 'getIndirectIndex',
  9822. type: 'uint',
  9823. inputs: [
  9824. { name: 'id', type: 'int' }
  9825. ]
  9826. } );
  9827. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9828. const matricesTexture = this.batchMesh._matricesTexture;
  9829. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9830. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9831. const x = j.modInt( size );
  9832. const y = j.div( int( size ) );
  9833. const batchingMatrix = mat4(
  9834. textureLoad( matricesTexture, ivec2( x, y ) ),
  9835. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9836. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9837. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9838. );
  9839. const colorsTexture = this.batchMesh._colorsTexture;
  9840. if ( colorsTexture !== null ) {
  9841. const getBatchingColor = Fn( ( [ id ] ) => {
  9842. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9843. const j = id;
  9844. const x = j.modInt( size );
  9845. const y = j.div( size );
  9846. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9847. } ).setLayout( {
  9848. name: 'getBatchingColor',
  9849. type: 'vec3',
  9850. inputs: [
  9851. { name: 'id', type: 'int' }
  9852. ]
  9853. } );
  9854. const color = getBatchingColor( indirectId );
  9855. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9856. }
  9857. const bm = mat3( batchingMatrix );
  9858. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9859. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9860. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9861. normalLocal.assign( batchingNormal );
  9862. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9863. tangentLocal.mulAssign( bm );
  9864. }
  9865. }
  9866. }
  9867. /**
  9868. * TSL function for creating a batch node.
  9869. *
  9870. * @tsl
  9871. * @function
  9872. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9873. * @returns {BatchNode}
  9874. */
  9875. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9876. const _frameId = new WeakMap();
  9877. /**
  9878. * This node implements the vertex transformation shader logic which is required
  9879. * for skinning/skeletal animation.
  9880. *
  9881. * @augments Node
  9882. */
  9883. class SkinningNode extends Node {
  9884. static get type() {
  9885. return 'SkinningNode';
  9886. }
  9887. /**
  9888. * Constructs a new skinning node.
  9889. *
  9890. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9891. * @param {boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9892. */
  9893. constructor( skinnedMesh, useReference = false ) {
  9894. super( 'void' );
  9895. /**
  9896. * The skinned mesh.
  9897. *
  9898. * @type {SkinnedMesh}
  9899. */
  9900. this.skinnedMesh = skinnedMesh;
  9901. /**
  9902. * Whether to use reference nodes for internal skinned mesh related data or not.
  9903. * TODO: Explain the purpose of the property.
  9904. *
  9905. * @type {boolean}
  9906. */
  9907. this.useReference = useReference;
  9908. /**
  9909. * The update type overwritten since skinning nodes are updated per object.
  9910. *
  9911. * @type {string}
  9912. */
  9913. this.updateType = NodeUpdateType.OBJECT;
  9914. //
  9915. /**
  9916. * The skin index attribute.
  9917. *
  9918. * @type {AttributeNode}
  9919. */
  9920. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9921. /**
  9922. * The skin weight attribute.
  9923. *
  9924. * @type {AttributeNode}
  9925. */
  9926. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9927. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9928. if ( useReference ) {
  9929. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9930. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9931. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9932. } else {
  9933. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9934. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9935. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9936. }
  9937. /**
  9938. * The bind matrix node.
  9939. *
  9940. * @type {Node<mat4>}
  9941. */
  9942. this.bindMatrixNode = bindMatrixNode;
  9943. /**
  9944. * The bind matrix inverse node.
  9945. *
  9946. * @type {Node<mat4>}
  9947. */
  9948. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9949. /**
  9950. * The bind matrices as a uniform buffer node.
  9951. *
  9952. * @type {Node}
  9953. */
  9954. this.boneMatricesNode = boneMatricesNode;
  9955. /**
  9956. * The previous bind matrices as a uniform buffer node.
  9957. * Required for computing motion vectors.
  9958. *
  9959. * @type {?Node}
  9960. * @default null
  9961. */
  9962. this.previousBoneMatricesNode = null;
  9963. }
  9964. /**
  9965. * Transforms the given vertex position via skinning.
  9966. *
  9967. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9968. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9969. * @return {Node<vec3>} The transformed vertex position.
  9970. */
  9971. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9972. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9973. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9974. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9975. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9976. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9977. // POSITION
  9978. const skinVertex = bindMatrixNode.mul( position );
  9979. const skinned = add(
  9980. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9981. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9982. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9983. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9984. );
  9985. return bindMatrixInverseNode.mul( skinned ).xyz;
  9986. }
  9987. /**
  9988. * Transforms the given vertex normal via skinning.
  9989. *
  9990. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9991. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9992. * @return {Node<vec3>} The transformed vertex normal.
  9993. */
  9994. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9995. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9996. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9997. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9998. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9999. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10000. // NORMAL
  10001. let skinMatrix = add(
  10002. skinWeightNode.x.mul( boneMatX ),
  10003. skinWeightNode.y.mul( boneMatY ),
  10004. skinWeightNode.z.mul( boneMatZ ),
  10005. skinWeightNode.w.mul( boneMatW )
  10006. );
  10007. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10008. return skinMatrix.transformDirection( normal ).xyz;
  10009. }
  10010. /**
  10011. * Transforms the given vertex normal via skinning.
  10012. *
  10013. * @param {NodeBuilder} builder - The current node builder.
  10014. * @return {Node<vec3>} The skinned position from the previous frame.
  10015. */
  10016. getPreviousSkinnedPosition( builder ) {
  10017. const skinnedMesh = builder.object;
  10018. if ( this.previousBoneMatricesNode === null ) {
  10019. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10020. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10021. }
  10022. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10023. }
  10024. /**
  10025. * Returns `true` if bone matrices from the previous frame are required.
  10026. *
  10027. * @param {NodeBuilder} builder - The current node builder.
  10028. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10029. */
  10030. needsPreviousBoneMatrices( builder ) {
  10031. const mrt = builder.renderer.getMRT();
  10032. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10033. }
  10034. /**
  10035. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10036. *
  10037. * @param {NodeBuilder} builder - The current node builder.
  10038. */
  10039. setup( builder ) {
  10040. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10041. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10042. }
  10043. const skinPosition = this.getSkinnedPosition();
  10044. positionLocal.assign( skinPosition );
  10045. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10046. const skinNormal = this.getSkinnedNormal();
  10047. normalLocal.assign( skinNormal );
  10048. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10049. tangentLocal.assign( skinNormal );
  10050. }
  10051. }
  10052. }
  10053. /**
  10054. * Generates the code snippet of the skinning node.
  10055. *
  10056. * @param {NodeBuilder} builder - The current node builder.
  10057. * @param {string} output - The current output.
  10058. * @return {string} The generated code snippet.
  10059. */
  10060. generate( builder, output ) {
  10061. if ( output !== 'void' ) {
  10062. return positionLocal.build( builder, output );
  10063. }
  10064. }
  10065. /**
  10066. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10067. *
  10068. * @param {NodeFrame} frame - The current node frame.
  10069. */
  10070. update( frame ) {
  10071. const object = this.useReference ? frame.object : this.skinnedMesh;
  10072. const skeleton = object.skeleton;
  10073. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10074. _frameId.set( skeleton, frame.frameId );
  10075. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10076. skeleton.update();
  10077. }
  10078. }
  10079. /**
  10080. * TSL function for creating a skinning node.
  10081. *
  10082. * @tsl
  10083. * @function
  10084. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10085. * @returns {SkinningNode}
  10086. */
  10087. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10088. /**
  10089. * TSL function for creating a skinning node with reference usage.
  10090. *
  10091. * @tsl
  10092. * @function
  10093. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10094. * @returns {SkinningNode}
  10095. */
  10096. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  10097. /**
  10098. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  10099. * ```js
  10100. * Loop( count, ( { i } ) => {
  10101. *
  10102. * } );
  10103. * ```
  10104. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  10105. * ```js
  10106. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  10107. *
  10108. * } );
  10109. *```
  10110. * Nested loops can be defined in a compacted form:
  10111. * ```js
  10112. * Loop( 10, 5, ( { i, j } ) => {
  10113. *
  10114. * } );
  10115. * ```
  10116. * Loops that should run backwards can be defined like so:
  10117. * ```js
  10118. * Loop( { start: 10 }, () => {} );
  10119. * ```
  10120. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  10121. * @augments Node
  10122. */
  10123. class LoopNode extends Node {
  10124. static get type() {
  10125. return 'LoopNode';
  10126. }
  10127. /**
  10128. * Constructs a new loop node.
  10129. *
  10130. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  10131. */
  10132. constructor( params = [] ) {
  10133. super();
  10134. this.params = params;
  10135. }
  10136. /**
  10137. * Returns a loop variable name based on an index. The pattern is
  10138. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  10139. *
  10140. * @param {number} index - The index.
  10141. * @return {string} The loop variable name.
  10142. */
  10143. getVarName( index ) {
  10144. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  10145. }
  10146. /**
  10147. * Returns properties about this node.
  10148. *
  10149. * @param {NodeBuilder} builder - The current node builder.
  10150. * @return {Object} The node properties.
  10151. */
  10152. getProperties( builder ) {
  10153. const properties = builder.getNodeProperties( this );
  10154. if ( properties.stackNode !== undefined ) return properties;
  10155. //
  10156. const inputs = {};
  10157. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10158. const param = this.params[ i ];
  10159. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  10160. const type = ( param.isNode !== true && param.type ) || 'int';
  10161. inputs[ name ] = expression( name, type );
  10162. }
  10163. const stack = builder.addStack(); // TODO: cache() it
  10164. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  10165. properties.stackNode = stack;
  10166. builder.removeStack();
  10167. return properties;
  10168. }
  10169. /**
  10170. * This method is overwritten since the node type is inferred based on the loop configuration.
  10171. *
  10172. * @param {NodeBuilder} builder - The current node builder.
  10173. * @return {string} The node type.
  10174. */
  10175. getNodeType( builder ) {
  10176. const { returnsNode } = this.getProperties( builder );
  10177. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  10178. }
  10179. setup( builder ) {
  10180. // setup properties
  10181. this.getProperties( builder );
  10182. }
  10183. generate( builder ) {
  10184. const properties = this.getProperties( builder );
  10185. const params = this.params;
  10186. const stackNode = properties.stackNode;
  10187. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  10188. const param = params[ i ];
  10189. let start = null, end = null, name = null, type = null, condition = null, update = null;
  10190. if ( param.isNode ) {
  10191. type = 'int';
  10192. name = this.getVarName( i );
  10193. start = '0';
  10194. end = param.build( builder, type );
  10195. condition = '<';
  10196. } else {
  10197. type = param.type || 'int';
  10198. name = param.name || this.getVarName( i );
  10199. start = param.start;
  10200. end = param.end;
  10201. condition = param.condition;
  10202. update = param.update;
  10203. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  10204. else if ( start && start.isNode ) start = start.build( builder, type );
  10205. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  10206. else if ( end && end.isNode ) end = end.build( builder, type );
  10207. if ( start !== undefined && end === undefined ) {
  10208. start = start + ' - 1';
  10209. end = '0';
  10210. condition = '>=';
  10211. } else if ( end !== undefined && start === undefined ) {
  10212. start = '0';
  10213. condition = '<';
  10214. }
  10215. if ( condition === undefined ) {
  10216. if ( Number( start ) > Number( end ) ) {
  10217. condition = '>=';
  10218. } else {
  10219. condition = '<';
  10220. }
  10221. }
  10222. }
  10223. const internalParam = { start, end};
  10224. //
  10225. const startSnippet = internalParam.start;
  10226. const endSnippet = internalParam.end;
  10227. let declarationSnippet = '';
  10228. let conditionalSnippet = '';
  10229. let updateSnippet = '';
  10230. if ( ! update ) {
  10231. if ( type === 'int' || type === 'uint' ) {
  10232. if ( condition.includes( '<' ) ) update = '++';
  10233. else update = '--';
  10234. } else {
  10235. if ( condition.includes( '<' ) ) update = '+= 1.';
  10236. else update = '-= 1.';
  10237. }
  10238. }
  10239. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  10240. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  10241. updateSnippet += name + ' ' + update;
  10242. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  10243. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  10244. }
  10245. const stackSnippet = stackNode.build( builder, 'void' );
  10246. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  10247. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  10248. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10249. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  10250. }
  10251. builder.addFlowTab();
  10252. return returnsSnippet;
  10253. }
  10254. }
  10255. /**
  10256. * TSL function for creating a loop node.
  10257. *
  10258. * @tsl
  10259. * @function
  10260. * @param {...any} params - A list of parameters.
  10261. * @returns {LoopNode}
  10262. */
  10263. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  10264. /**
  10265. * TSL function for creating a `Continue()` expression.
  10266. *
  10267. * @tsl
  10268. * @function
  10269. * @returns {ExpressionNode}
  10270. */
  10271. const Continue = () => expression( 'continue' ).append();
  10272. /**
  10273. * TSL function for creating a `Break()` expression.
  10274. *
  10275. * @tsl
  10276. * @function
  10277. * @returns {ExpressionNode}
  10278. */
  10279. const Break = () => expression( 'break' ).append();
  10280. // Deprecated
  10281. /**
  10282. * @tsl
  10283. * @function
  10284. * @deprecated since r168. Use {@link Loop} instead.
  10285. *
  10286. * @param {...any} params
  10287. * @returns {LoopNode}
  10288. */
  10289. const loop = ( ...params ) => { // @deprecated, r168
  10290. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  10291. return Loop( ...params );
  10292. };
  10293. const _morphTextures = /*@__PURE__*/ new WeakMap();
  10294. const _morphVec4 = /*@__PURE__*/ new Vector4();
  10295. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  10296. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  10297. const y = texelIndex.div( width );
  10298. const x = texelIndex.sub( y.mul( width ) );
  10299. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  10300. return bufferAttrib.mul( influence );
  10301. } );
  10302. function getEntry( geometry ) {
  10303. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10304. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10305. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10306. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10307. // into an array of data textures. Each layer represents a single morph target.
  10308. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10309. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10310. let entry = _morphTextures.get( geometry );
  10311. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10312. if ( entry !== undefined ) entry.texture.dispose();
  10313. const morphTargets = geometry.morphAttributes.position || [];
  10314. const morphNormals = geometry.morphAttributes.normal || [];
  10315. const morphColors = geometry.morphAttributes.color || [];
  10316. let vertexDataCount = 0;
  10317. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10318. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10319. if ( hasMorphColors === true ) vertexDataCount = 3;
  10320. let width = geometry.attributes.position.count * vertexDataCount;
  10321. let height = 1;
  10322. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10323. if ( width > maxTextureSize ) {
  10324. height = Math.ceil( width / maxTextureSize );
  10325. width = maxTextureSize;
  10326. }
  10327. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10328. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10329. bufferTexture.type = FloatType;
  10330. bufferTexture.needsUpdate = true;
  10331. // fill buffer
  10332. const vertexDataStride = vertexDataCount * 4;
  10333. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10334. const morphTarget = morphTargets[ i ];
  10335. const morphNormal = morphNormals[ i ];
  10336. const morphColor = morphColors[ i ];
  10337. const offset = width * height * 4 * i;
  10338. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10339. const stride = j * vertexDataStride;
  10340. if ( hasMorphPosition === true ) {
  10341. _morphVec4.fromBufferAttribute( morphTarget, j );
  10342. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10343. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10344. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10345. buffer[ offset + stride + 3 ] = 0;
  10346. }
  10347. if ( hasMorphNormals === true ) {
  10348. _morphVec4.fromBufferAttribute( morphNormal, j );
  10349. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10350. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10351. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10352. buffer[ offset + stride + 7 ] = 0;
  10353. }
  10354. if ( hasMorphColors === true ) {
  10355. _morphVec4.fromBufferAttribute( morphColor, j );
  10356. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10357. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10358. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10359. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10360. }
  10361. }
  10362. }
  10363. entry = {
  10364. count: morphTargetsCount,
  10365. texture: bufferTexture,
  10366. stride: vertexDataCount,
  10367. size: new Vector2( width, height )
  10368. };
  10369. _morphTextures.set( geometry, entry );
  10370. function disposeTexture() {
  10371. bufferTexture.dispose();
  10372. _morphTextures.delete( geometry );
  10373. geometry.removeEventListener( 'dispose', disposeTexture );
  10374. }
  10375. geometry.addEventListener( 'dispose', disposeTexture );
  10376. }
  10377. return entry;
  10378. }
  10379. /**
  10380. * This node implements the vertex transformation shader logic which is required
  10381. * for morph target animation.
  10382. *
  10383. * @augments Node
  10384. */
  10385. class MorphNode extends Node {
  10386. static get type() {
  10387. return 'MorphNode';
  10388. }
  10389. /**
  10390. * Constructs a new morph node.
  10391. *
  10392. * @param {Mesh} mesh - The mesh holding the morph targets.
  10393. */
  10394. constructor( mesh ) {
  10395. super( 'void' );
  10396. /**
  10397. * The mesh holding the morph targets.
  10398. *
  10399. * @type {Mesh}
  10400. */
  10401. this.mesh = mesh;
  10402. /**
  10403. * A uniform node which represents the morph base influence value.
  10404. *
  10405. * @type {UniformNode<float>}
  10406. */
  10407. this.morphBaseInfluence = uniform( 1 );
  10408. /**
  10409. * The update type overwritten since morph nodes are updated per object.
  10410. *
  10411. * @type {string}
  10412. */
  10413. this.updateType = NodeUpdateType.OBJECT;
  10414. }
  10415. /**
  10416. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10417. *
  10418. * @param {NodeBuilder} builder - The current node builder.
  10419. */
  10420. setup( builder ) {
  10421. const { geometry } = builder;
  10422. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10423. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10424. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10425. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10426. // nodes
  10427. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10428. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10429. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10430. const width = int( size.width );
  10431. Loop( morphTargetsCount, ( { i } ) => {
  10432. const influence = float( 0 ).toVar();
  10433. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10434. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10435. } else {
  10436. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10437. }
  10438. if ( hasMorphPosition === true ) {
  10439. positionLocal.addAssign( getMorph( {
  10440. bufferMap,
  10441. influence,
  10442. stride,
  10443. width,
  10444. depth: i,
  10445. offset: int( 0 )
  10446. } ) );
  10447. }
  10448. if ( hasMorphNormals === true ) {
  10449. normalLocal.addAssign( getMorph( {
  10450. bufferMap,
  10451. influence,
  10452. stride,
  10453. width,
  10454. depth: i,
  10455. offset: int( 1 )
  10456. } ) );
  10457. }
  10458. } );
  10459. }
  10460. /**
  10461. * Updates the state of the morphed mesh by updating the base influence.
  10462. *
  10463. * @param {NodeFrame} frame - The current node frame.
  10464. */
  10465. update( /*frame*/ ) {
  10466. const morphBaseInfluence = this.morphBaseInfluence;
  10467. if ( this.mesh.geometry.morphTargetsRelative ) {
  10468. morphBaseInfluence.value = 1;
  10469. } else {
  10470. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10471. }
  10472. }
  10473. }
  10474. /**
  10475. * TSL function for creating a morph node.
  10476. *
  10477. * @tsl
  10478. * @function
  10479. * @param {Mesh} mesh - The mesh holding the morph targets.
  10480. * @returns {MorphNode}
  10481. */
  10482. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10483. /**
  10484. * Base class for lighting nodes.
  10485. *
  10486. * @augments Node
  10487. */
  10488. class LightingNode extends Node {
  10489. static get type() {
  10490. return 'LightingNode';
  10491. }
  10492. /**
  10493. * Constructs a new lighting node.
  10494. */
  10495. constructor() {
  10496. super( 'vec3' );
  10497. /**
  10498. * This flag can be used for type testing.
  10499. *
  10500. * @type {boolean}
  10501. * @readonly
  10502. * @default true
  10503. */
  10504. this.isLightingNode = true;
  10505. }
  10506. }
  10507. /**
  10508. * A generic class that can be used by nodes which contribute
  10509. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10510. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10511. *
  10512. * @augments LightingNode
  10513. */
  10514. class AONode extends LightingNode {
  10515. static get type() {
  10516. return 'AONode';
  10517. }
  10518. /**
  10519. * Constructs a new AO node.
  10520. *
  10521. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  10522. */
  10523. constructor( aoNode = null ) {
  10524. super();
  10525. /**
  10526. * The ambient occlusion node.
  10527. *
  10528. * @type {?Node<float>}
  10529. * @default null
  10530. */
  10531. this.aoNode = aoNode;
  10532. }
  10533. setup( builder ) {
  10534. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10535. }
  10536. }
  10537. /**
  10538. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  10539. * by adding lighting specific context data. It represents the runtime context of
  10540. * {@link LightsNode}.
  10541. *
  10542. * @augments ContextNode
  10543. */
  10544. class LightingContextNode extends ContextNode {
  10545. static get type() {
  10546. return 'LightingContextNode';
  10547. }
  10548. /**
  10549. * Constructs a new lighting context node.
  10550. *
  10551. * @param {LightsNode} node - The lights node.
  10552. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  10553. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  10554. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  10555. */
  10556. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10557. super( node );
  10558. /**
  10559. * The current lighting model.
  10560. *
  10561. * @type {?LightingModel}
  10562. * @default null
  10563. */
  10564. this.lightingModel = lightingModel;
  10565. /**
  10566. * A backdrop node.
  10567. *
  10568. * @type {?Node<vec3>}
  10569. * @default null
  10570. */
  10571. this.backdropNode = backdropNode;
  10572. /**
  10573. * A backdrop alpha node.
  10574. *
  10575. * @type {?Node<float>}
  10576. * @default null
  10577. */
  10578. this.backdropAlphaNode = backdropAlphaNode;
  10579. this._value = null;
  10580. }
  10581. /**
  10582. * Returns a lighting context object.
  10583. *
  10584. * @return {{
  10585. * radiance: Node<vec3>,
  10586. * irradiance: Node<vec3>,
  10587. * iblIrradiance: Node<vec3>,
  10588. * ambientOcclusion: Node<float>,
  10589. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10590. * backdrop: Node<vec3>,
  10591. * backdropAlpha: Node<float>
  10592. * }} The lighting context object.
  10593. */
  10594. getContext() {
  10595. const { backdropNode, backdropAlphaNode } = this;
  10596. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10597. directSpecular = vec3().toVar( 'directSpecular' ),
  10598. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10599. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10600. const reflectedLight = {
  10601. directDiffuse,
  10602. directSpecular,
  10603. indirectDiffuse,
  10604. indirectSpecular
  10605. };
  10606. const context = {
  10607. radiance: vec3().toVar( 'radiance' ),
  10608. irradiance: vec3().toVar( 'irradiance' ),
  10609. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10610. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10611. reflectedLight,
  10612. backdrop: backdropNode,
  10613. backdropAlpha: backdropAlphaNode
  10614. };
  10615. return context;
  10616. }
  10617. setup( builder ) {
  10618. this.value = this._value || ( this._value = this.getContext() );
  10619. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10620. return super.setup( builder );
  10621. }
  10622. }
  10623. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10624. /**
  10625. * A generic class that can be used by nodes which contribute
  10626. * irradiance to the scene. E.g. a light map node can be used
  10627. * as input for this module. Used in {@link NodeMaterial}.
  10628. *
  10629. * @augments LightingNode
  10630. */
  10631. class IrradianceNode extends LightingNode {
  10632. static get type() {
  10633. return 'IrradianceNode';
  10634. }
  10635. /**
  10636. * Constructs a new irradiance node.
  10637. *
  10638. * @param {Node<vec3>} node - A node contributing irradiance.
  10639. */
  10640. constructor( node ) {
  10641. super();
  10642. /**
  10643. * A node contributing irradiance.
  10644. *
  10645. * @type {Node<vec3>}
  10646. */
  10647. this.node = node;
  10648. }
  10649. setup( builder ) {
  10650. builder.context.irradiance.addAssign( this.node );
  10651. }
  10652. }
  10653. let screenSizeVec, viewportVec;
  10654. /**
  10655. * This node provides a collection of screen related metrics.
  10656. * Depending on {@link ScreenNode#scope}, the nodes can represent
  10657. * resolution or viewport data as well as fragment or uv coordinates.
  10658. *
  10659. * @augments Node
  10660. */
  10661. class ScreenNode extends Node {
  10662. static get type() {
  10663. return 'ScreenNode';
  10664. }
  10665. /**
  10666. * Constructs a new screen node.
  10667. *
  10668. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10669. */
  10670. constructor( scope ) {
  10671. super();
  10672. /**
  10673. * The node represents different metric depending on which scope is selected.
  10674. *
  10675. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10676. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10677. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10678. * - `ScreenNode.UV`: Normalized coordinates.
  10679. *
  10680. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10681. */
  10682. this.scope = scope;
  10683. /**
  10684. * This flag can be used for type testing.
  10685. *
  10686. * @type {boolean}
  10687. * @readonly
  10688. * @default true
  10689. */
  10690. this.isViewportNode = true;
  10691. }
  10692. /**
  10693. * This method is overwritten since the node type depends on the selected scope.
  10694. *
  10695. * @return {('vec2'|'vec4')} The node type.
  10696. */
  10697. getNodeType() {
  10698. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10699. else return 'vec2';
  10700. }
  10701. /**
  10702. * This method is overwritten since the node's update type depends on the selected scope.
  10703. *
  10704. * @return {NodeUpdateType} The update type.
  10705. */
  10706. getUpdateType() {
  10707. let updateType = NodeUpdateType.NONE;
  10708. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10709. updateType = NodeUpdateType.RENDER;
  10710. }
  10711. this.updateType = updateType;
  10712. return updateType;
  10713. }
  10714. /**
  10715. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10716. * from the current renderer.
  10717. *
  10718. * @param {NodeFrame} frame - A reference to the current node frame.
  10719. */
  10720. update( { renderer } ) {
  10721. const renderTarget = renderer.getRenderTarget();
  10722. if ( this.scope === ScreenNode.VIEWPORT ) {
  10723. if ( renderTarget !== null ) {
  10724. viewportVec.copy( renderTarget.viewport );
  10725. } else {
  10726. renderer.getViewport( viewportVec );
  10727. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10728. }
  10729. } else {
  10730. if ( renderTarget !== null ) {
  10731. screenSizeVec.width = renderTarget.width;
  10732. screenSizeVec.height = renderTarget.height;
  10733. } else {
  10734. renderer.getDrawingBufferSize( screenSizeVec );
  10735. }
  10736. }
  10737. }
  10738. setup( /*builder*/ ) {
  10739. const scope = this.scope;
  10740. let output = null;
  10741. if ( scope === ScreenNode.SIZE ) {
  10742. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10743. } else if ( scope === ScreenNode.VIEWPORT ) {
  10744. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10745. } else {
  10746. output = vec2( screenCoordinate.div( screenSize ) );
  10747. }
  10748. return output;
  10749. }
  10750. generate( builder ) {
  10751. if ( this.scope === ScreenNode.COORDINATE ) {
  10752. let coord = builder.getFragCoord();
  10753. if ( builder.isFlipY() ) {
  10754. // follow webgpu standards
  10755. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10756. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10757. }
  10758. return coord;
  10759. }
  10760. return super.generate( builder );
  10761. }
  10762. }
  10763. ScreenNode.COORDINATE = 'coordinate';
  10764. ScreenNode.VIEWPORT = 'viewport';
  10765. ScreenNode.SIZE = 'size';
  10766. ScreenNode.UV = 'uv';
  10767. // Screen
  10768. /**
  10769. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10770. *
  10771. * @tsl
  10772. * @type {ScreenNode<vec2>}
  10773. */
  10774. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10775. /**
  10776. * TSL object that represents the screen resolution in physical pixel units.
  10777. *
  10778. * @tsl
  10779. * @type {ScreenNode<vec2>}
  10780. */
  10781. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10782. /**
  10783. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10784. *
  10785. * @tsl
  10786. * @type {ScreenNode<vec2>}
  10787. */
  10788. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10789. // Viewport
  10790. /**
  10791. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10792. *
  10793. * @tsl
  10794. * @type {ScreenNode<vec4>}
  10795. */
  10796. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10797. /**
  10798. * TSL object that represents the viewport resolution in physical pixel units.
  10799. *
  10800. * @tsl
  10801. * @type {ScreenNode<vec2>}
  10802. */
  10803. const viewportSize = viewport.zw;
  10804. /**
  10805. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10806. *
  10807. * @tsl
  10808. * @type {ScreenNode<vec2>}
  10809. */
  10810. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10811. /**
  10812. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10813. *
  10814. * @tsl
  10815. * @type {ScreenNode<vec2>}
  10816. */
  10817. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10818. // Deprecated
  10819. /**
  10820. * @deprecated since r169. Use {@link screenSize} instead.
  10821. */
  10822. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10823. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10824. return screenSize;
  10825. }, 'vec2' ).once() )();
  10826. /**
  10827. * @tsl
  10828. * @deprecated since r168. Use {@link screenUV} instead.
  10829. * @type {Node<vec2>}
  10830. */
  10831. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10832. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10833. return screenUV;
  10834. }, 'vec2' ).once() )();
  10835. /**
  10836. * @tsl
  10837. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10838. * @type {Node<vec2>}
  10839. */
  10840. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10841. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10842. return screenUV.flipY();
  10843. }, 'vec2' ).once() )();
  10844. const _size$4 = /*@__PURE__*/ new Vector2();
  10845. /**
  10846. * A special type of texture node which represents the data of the current viewport
  10847. * as a texture. The module extracts data from the current bound framebuffer with
  10848. * a copy operation so no extra render pass is required to produce the texture data
  10849. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10850. * variety of effects like refractive or transmissive materials.
  10851. *
  10852. * @augments TextureNode
  10853. */
  10854. class ViewportTextureNode extends TextureNode {
  10855. static get type() {
  10856. return 'ViewportTextureNode';
  10857. }
  10858. /**
  10859. * Constructs a new viewport texture node.
  10860. *
  10861. * @param {Node} [uvNode=screenUV] - The uv node.
  10862. * @param {?Node} [levelNode=null] - The level node.
  10863. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10864. */
  10865. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10866. if ( framebufferTexture === null ) {
  10867. framebufferTexture = new FramebufferTexture();
  10868. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10869. }
  10870. super( framebufferTexture, uvNode, levelNode );
  10871. /**
  10872. * Whether to generate mipmaps or not.
  10873. *
  10874. * @type {boolean}
  10875. * @default false
  10876. */
  10877. this.generateMipmaps = false;
  10878. /**
  10879. * This flag can be used for type testing.
  10880. *
  10881. * @type {boolean}
  10882. * @readonly
  10883. * @default true
  10884. */
  10885. this.isOutputTextureNode = true;
  10886. /**
  10887. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10888. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10889. *
  10890. * @type {string}
  10891. * @default 'frame'
  10892. */
  10893. this.updateBeforeType = NodeUpdateType.FRAME;
  10894. }
  10895. updateBefore( frame ) {
  10896. const renderer = frame.renderer;
  10897. renderer.getDrawingBufferSize( _size$4 );
  10898. //
  10899. const framebufferTexture = this.value;
  10900. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10901. framebufferTexture.image.width = _size$4.width;
  10902. framebufferTexture.image.height = _size$4.height;
  10903. framebufferTexture.needsUpdate = true;
  10904. }
  10905. //
  10906. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10907. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10908. renderer.copyFramebufferToTexture( framebufferTexture );
  10909. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10910. }
  10911. clone() {
  10912. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10913. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10914. return viewportTextureNode;
  10915. }
  10916. }
  10917. /**
  10918. * TSL function for creating a viewport texture node.
  10919. *
  10920. * @tsl
  10921. * @function
  10922. * @param {Node} [uvNode=screenUV] - The uv node.
  10923. * @param {?Node} [levelNode=null] - The level node.
  10924. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10925. * @returns {ViewportTextureNode}
  10926. */
  10927. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10928. /**
  10929. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10930. *
  10931. * @tsl
  10932. * @function
  10933. * @param {Node} [uvNode=screenUV] - The uv node.
  10934. * @param {?Node} [levelNode=null] - The level node.
  10935. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10936. * @returns {ViewportTextureNode}
  10937. */
  10938. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10939. let sharedDepthbuffer = null;
  10940. /**
  10941. * Represents the depth of the current viewport as a texture. This module
  10942. * can be used in combination with viewport texture to achieve effects
  10943. * that require depth evaluation.
  10944. *
  10945. * @augments ViewportTextureNode
  10946. */
  10947. class ViewportDepthTextureNode extends ViewportTextureNode {
  10948. static get type() {
  10949. return 'ViewportDepthTextureNode';
  10950. }
  10951. /**
  10952. * Constructs a new viewport depth texture node.
  10953. *
  10954. * @param {Node} [uvNode=screenUV] - The uv node.
  10955. * @param {?Node} [levelNode=null] - The level node.
  10956. */
  10957. constructor( uvNode = screenUV, levelNode = null ) {
  10958. if ( sharedDepthbuffer === null ) {
  10959. sharedDepthbuffer = new DepthTexture();
  10960. }
  10961. super( uvNode, levelNode, sharedDepthbuffer );
  10962. }
  10963. }
  10964. /**
  10965. * TSL function for a viewport depth texture node.
  10966. *
  10967. * @tsl
  10968. * @function
  10969. * @param {Node} [uvNode=screenUV] - The uv node.
  10970. * @param {?Node} [levelNode=null] - The level node.
  10971. * @returns {ViewportDepthTextureNode}
  10972. */
  10973. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10974. /**
  10975. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10976. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10977. * fragment or for depth evaluation purposes.
  10978. *
  10979. * @augments Node
  10980. */
  10981. class ViewportDepthNode extends Node {
  10982. static get type() {
  10983. return 'ViewportDepthNode';
  10984. }
  10985. /**
  10986. * Constructs a new viewport depth node.
  10987. *
  10988. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10989. * @param {?Node} [valueNode=null] - The value node.
  10990. */
  10991. constructor( scope, valueNode = null ) {
  10992. super( 'float' );
  10993. /**
  10994. * The node behaves differently depending on which scope is selected.
  10995. *
  10996. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10997. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10998. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10999. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  11000. *
  11001. * @type {('depth'|'depthBase'|'linearDepth')}
  11002. */
  11003. this.scope = scope;
  11004. /**
  11005. * Can be used to define a custom depth value.
  11006. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11007. *
  11008. * @type {?Node}
  11009. * @default null
  11010. */
  11011. this.valueNode = valueNode;
  11012. /**
  11013. * This flag can be used for type testing.
  11014. *
  11015. * @type {boolean}
  11016. * @readonly
  11017. * @default true
  11018. */
  11019. this.isViewportDepthNode = true;
  11020. }
  11021. generate( builder ) {
  11022. const { scope } = this;
  11023. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11024. return builder.getFragDepth();
  11025. }
  11026. return super.generate( builder );
  11027. }
  11028. setup( { camera } ) {
  11029. const { scope } = this;
  11030. const value = this.valueNode;
  11031. let node = null;
  11032. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11033. if ( value !== null ) {
  11034. node = depthBase().assign( value );
  11035. }
  11036. } else if ( scope === ViewportDepthNode.DEPTH ) {
  11037. if ( camera.isPerspectiveCamera ) {
  11038. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  11039. } else {
  11040. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11041. }
  11042. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  11043. if ( value !== null ) {
  11044. if ( camera.isPerspectiveCamera ) {
  11045. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  11046. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  11047. } else {
  11048. node = value;
  11049. }
  11050. } else {
  11051. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11052. }
  11053. }
  11054. return node;
  11055. }
  11056. }
  11057. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  11058. ViewportDepthNode.DEPTH = 'depth';
  11059. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  11060. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  11061. /**
  11062. * TSL function for converting a viewZ value to an orthographic depth value.
  11063. *
  11064. * @tsl
  11065. * @function
  11066. * @param {Node<float>} viewZ - The viewZ node.
  11067. * @param {Node<float>} near - The camera's near value.
  11068. * @param {Node<float>} far - The camera's far value.
  11069. * @returns {Node<float>}
  11070. */
  11071. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  11072. /**
  11073. * TSL function for converting an orthographic depth value to a viewZ value.
  11074. *
  11075. * @tsl
  11076. * @function
  11077. * @param {Node<float>} depth - The orthographic depth.
  11078. * @param {Node<float>} near - The camera's near value.
  11079. * @param {Node<float>} far - The camera's far value.
  11080. * @returns {Node<float>}
  11081. */
  11082. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  11083. /**
  11084. * TSL function for converting a viewZ value to a perspective depth value.
  11085. *
  11086. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  11087. *
  11088. * @tsl
  11089. * @function
  11090. * @param {Node<float>} viewZ - The viewZ node.
  11091. * @param {Node<float>} near - The camera's near value.
  11092. * @param {Node<float>} far - The camera's far value.
  11093. * @returns {Node<float>}
  11094. */
  11095. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  11096. /**
  11097. * TSL function for converting a perspective depth value to a viewZ value.
  11098. *
  11099. * @tsl
  11100. * @function
  11101. * @param {Node<float>} depth - The perspective depth.
  11102. * @param {Node<float>} near - The camera's near value.
  11103. * @param {Node<float>} far - The camera's far value.
  11104. * @returns {Node<float>}
  11105. */
  11106. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  11107. /**
  11108. * TSL function for converting a viewZ value to a logarithmic depth value.
  11109. *
  11110. * @tsl
  11111. * @function
  11112. * @param {Node<float>} viewZ - The viewZ node.
  11113. * @param {Node<float>} near - The camera's near value.
  11114. * @param {Node<float>} far - The camera's far value.
  11115. * @returns {Node<float>}
  11116. */
  11117. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  11118. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  11119. // The final logarithmic depth formula used here is adapted from one described in an
  11120. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  11121. // which was an improvement upon an earlier formula one described in an
  11122. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  11123. // Ulrich's formula is the following:
  11124. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  11125. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  11126. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  11127. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  11128. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  11129. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  11130. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  11131. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  11132. // be used, and ultimately Ulrich's "near plane" version was chosen.
  11133. // Outerra eventually made another improvement to their original "C-constant" variant,
  11134. // but it still does not incorporate the camera near plane (for this version,
  11135. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  11136. // Here we make 4 changes to Ulrich's formula:
  11137. // 1. Clamp the camera near plane so we don't divide by 0.
  11138. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  11139. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  11140. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  11141. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  11142. // so we do the same here, hence the 'viewZ.negate()' call.
  11143. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  11144. near = near.max( 1e-6 ).toVar();
  11145. const numerator = log2( viewZ.negate().div( near ) );
  11146. const denominator = log2( far.div( near ) );
  11147. return numerator.div( denominator );
  11148. };
  11149. /**
  11150. * TSL function for converting a logarithmic depth value to a viewZ value.
  11151. *
  11152. * @tsl
  11153. * @function
  11154. * @param {Node<float>} depth - The logarithmic depth.
  11155. * @param {Node<float>} near - The camera's near value.
  11156. * @param {Node<float>} far - The camera's far value.
  11157. * @returns {Node<float>}
  11158. */
  11159. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  11160. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  11161. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  11162. // a negative viewZ).
  11163. const exponent = depth.mul( log( far.div( near ) ) );
  11164. return float( Math.E ).pow( exponent ).mul( near ).negate();
  11165. };
  11166. /**
  11167. * TSL function for defining a value for the current fragment's depth.
  11168. *
  11169. * @tsl
  11170. * @function
  11171. * @param {Node<float>} value - The depth value to set.
  11172. * @returns {ViewportDepthNode<float>}
  11173. */
  11174. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  11175. /**
  11176. * TSL object that represents the depth value for the current fragment.
  11177. *
  11178. * @tsl
  11179. * @type {ViewportDepthNode}
  11180. */
  11181. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  11182. /**
  11183. * TSL function for converting a perspective depth value to linear depth.
  11184. *
  11185. * @tsl
  11186. * @function
  11187. * @param {Node<float>} value - The perspective depth.
  11188. * @returns {ViewportDepthNode<float>}
  11189. */
  11190. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  11191. /**
  11192. * TSL object that represents the linear (orthographic) depth value of the current fragment
  11193. *
  11194. * @tsl
  11195. * @type {ViewportDepthNode}
  11196. */
  11197. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  11198. depth.assign = ( value ) => depthBase( value );
  11199. /**
  11200. * The node allows to set values for built-in shader variables. That is
  11201. * required for features like hardware-accelerated vertex clipping.
  11202. *
  11203. * @augments Node
  11204. */
  11205. class BuiltinNode extends Node {
  11206. /**
  11207. * Constructs a new builtin node.
  11208. *
  11209. * @param {string} name - The name of the built-in shader variable.
  11210. */
  11211. constructor( name ) {
  11212. super( 'float' );
  11213. /**
  11214. * The name of the built-in shader variable.
  11215. *
  11216. * @type {string}
  11217. */
  11218. this.name = name;
  11219. /**
  11220. * This flag can be used for type testing.
  11221. *
  11222. * @type {boolean}
  11223. * @readonly
  11224. * @default true
  11225. */
  11226. this.isBuiltinNode = true;
  11227. }
  11228. /**
  11229. * Generates the code snippet of the builtin node.
  11230. *
  11231. * @param {NodeBuilder} builder - The current node builder.
  11232. * @return {string} The generated code snippet.
  11233. */
  11234. generate( /* builder */ ) {
  11235. return this.name;
  11236. }
  11237. }
  11238. /**
  11239. * TSL function for creating a builtin node.
  11240. *
  11241. * @tsl
  11242. * @function
  11243. * @param {string} name - The name of the built-in shader variable.
  11244. * @returns {BuiltinNode}
  11245. */
  11246. const builtin = nodeProxy( BuiltinNode );
  11247. /**
  11248. * This node is used in {@link NodeMaterial} to setup the clipping
  11249. * which can happen hardware-accelerated (if supported) and optionally
  11250. * use alpha-to-coverage for anti-aliasing clipped edges.
  11251. *
  11252. * @augments Node
  11253. */
  11254. class ClippingNode extends Node {
  11255. static get type() {
  11256. return 'ClippingNode';
  11257. }
  11258. /**
  11259. * Constructs a new clipping node.
  11260. *
  11261. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  11262. * the selected scope influences the behavior of the node and what type of code is generated.
  11263. */
  11264. constructor( scope = ClippingNode.DEFAULT ) {
  11265. super();
  11266. /**
  11267. * The node's scope. Similar to other nodes, the selected scope influences
  11268. * the behavior of the node and what type of code is generated.
  11269. *
  11270. * @type {('default'|'hardware'|'alphaToCoverage')}
  11271. */
  11272. this.scope = scope;
  11273. }
  11274. /**
  11275. * Setups the node depending on the selected scope.
  11276. *
  11277. * @param {NodeBuilder} builder - The current node builder.
  11278. * @return {Node} The result node.
  11279. */
  11280. setup( builder ) {
  11281. super.setup( builder );
  11282. const clippingContext = builder.clippingContext;
  11283. const { intersectionPlanes, unionPlanes } = clippingContext;
  11284. this.hardwareClipping = builder.material.hardwareClipping;
  11285. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  11286. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  11287. } else if ( this.scope === ClippingNode.HARDWARE ) {
  11288. return this.setupHardwareClipping( unionPlanes, builder );
  11289. } else {
  11290. return this.setupDefault( intersectionPlanes, unionPlanes );
  11291. }
  11292. }
  11293. /**
  11294. * Setups alpha to coverage.
  11295. *
  11296. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11297. * @param {Array<Vector4>} unionPlanes - The union planes.
  11298. * @return {Node} The result node.
  11299. */
  11300. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  11301. return Fn( () => {
  11302. const distanceToPlane = float().toVar( 'distanceToPlane' );
  11303. const distanceGradient = float().toVar( 'distanceToGradient' );
  11304. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  11305. const numUnionPlanes = unionPlanes.length;
  11306. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11307. const clippingPlanes = uniformArray( unionPlanes );
  11308. Loop( numUnionPlanes, ( { i } ) => {
  11309. const plane = clippingPlanes.element( i );
  11310. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11311. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11312. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  11313. } );
  11314. }
  11315. const numIntersectionPlanes = intersectionPlanes.length;
  11316. if ( numIntersectionPlanes > 0 ) {
  11317. const clippingPlanes = uniformArray( intersectionPlanes );
  11318. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11319. Loop( numIntersectionPlanes, ( { i } ) => {
  11320. const plane = clippingPlanes.element( i );
  11321. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11322. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11323. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11324. } );
  11325. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11326. }
  11327. diffuseColor.a.mulAssign( clipOpacity );
  11328. diffuseColor.a.equal( 0.0 ).discard();
  11329. } )();
  11330. }
  11331. /**
  11332. * Setups the default clipping.
  11333. *
  11334. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11335. * @param {Array<Vector4>} unionPlanes - The union planes.
  11336. * @return {Node} The result node.
  11337. */
  11338. setupDefault( intersectionPlanes, unionPlanes ) {
  11339. return Fn( () => {
  11340. const numUnionPlanes = unionPlanes.length;
  11341. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11342. const clippingPlanes = uniformArray( unionPlanes );
  11343. Loop( numUnionPlanes, ( { i } ) => {
  11344. const plane = clippingPlanes.element( i );
  11345. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11346. } );
  11347. }
  11348. const numIntersectionPlanes = intersectionPlanes.length;
  11349. if ( numIntersectionPlanes > 0 ) {
  11350. const clippingPlanes = uniformArray( intersectionPlanes );
  11351. const clipped = bool( true ).toVar( 'clipped' );
  11352. Loop( numIntersectionPlanes, ( { i } ) => {
  11353. const plane = clippingPlanes.element( i );
  11354. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11355. } );
  11356. clipped.discard();
  11357. }
  11358. } )();
  11359. }
  11360. /**
  11361. * Setups hardware clipping.
  11362. *
  11363. * @param {Array<Vector4>} unionPlanes - The union planes.
  11364. * @param {NodeBuilder} builder - The current node builder.
  11365. * @return {Node} The result node.
  11366. */
  11367. setupHardwareClipping( unionPlanes, builder ) {
  11368. const numUnionPlanes = unionPlanes.length;
  11369. builder.enableHardwareClipping( numUnionPlanes );
  11370. return Fn( () => {
  11371. const clippingPlanes = uniformArray( unionPlanes );
  11372. const hw_clip_distances = builtin( builder.getClipDistance() );
  11373. Loop( numUnionPlanes, ( { i } ) => {
  11374. const plane = clippingPlanes.element( i );
  11375. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11376. hw_clip_distances.element( i ).assign( distance );
  11377. } );
  11378. } )();
  11379. }
  11380. }
  11381. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11382. ClippingNode.DEFAULT = 'default';
  11383. ClippingNode.HARDWARE = 'hardware';
  11384. /**
  11385. * TSL function for setting up the default clipping logic.
  11386. *
  11387. * @tsl
  11388. * @function
  11389. * @returns {ClippingNode}
  11390. */
  11391. const clipping = () => nodeObject( new ClippingNode() );
  11392. /**
  11393. * TSL function for setting up alpha to coverage.
  11394. *
  11395. * @tsl
  11396. * @function
  11397. * @returns {ClippingNode}
  11398. */
  11399. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11400. /**
  11401. * TSL function for setting up hardware-based clipping.
  11402. *
  11403. * @tsl
  11404. * @function
  11405. * @returns {ClippingNode}
  11406. */
  11407. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11408. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11409. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11410. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11411. 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 ) ) ) ) ) );
  11412. } );
  11413. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11414. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11415. } );
  11416. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11417. // Find the discretized derivatives of our coordinates
  11418. const maxDeriv = max$1(
  11419. length( dFdx( position.xyz ) ),
  11420. length( dFdy( position.xyz ) )
  11421. );
  11422. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11423. // Find two nearest log-discretized noise scales
  11424. const pixScales = vec2(
  11425. exp2( floor( log2( pixScale ) ) ),
  11426. exp2( ceil( log2( pixScale ) ) )
  11427. );
  11428. // Compute alpha thresholds at our two noise scales
  11429. const alpha = vec2(
  11430. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11431. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11432. );
  11433. // Factor to interpolate lerp with
  11434. const lerpFactor = fract( log2( pixScale ) );
  11435. // Interpolate alpha threshold from noise at two scales
  11436. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11437. // Pass into CDF to compute uniformly distrib threshold
  11438. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11439. const cases = vec3(
  11440. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11441. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11442. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11443. // Find our final, uniformly distributed alpha threshold (ατ)
  11444. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11445. // Avoids ατ == 0. Could also do ατ =1-ατ
  11446. return clamp( threshold, 1.0e-6, 1.0 );
  11447. } ).setLayout( {
  11448. name: 'getAlphaHashThreshold',
  11449. type: 'float',
  11450. inputs: [
  11451. { name: 'position', type: 'vec3' }
  11452. ]
  11453. } );
  11454. /**
  11455. * Base class for all node materials.
  11456. *
  11457. * @augments Material
  11458. */
  11459. class NodeMaterial extends Material {
  11460. static get type() {
  11461. return 'NodeMaterial';
  11462. }
  11463. /**
  11464. * Represents the type of the node material.
  11465. *
  11466. * @type {string}
  11467. */
  11468. get type() {
  11469. return this.constructor.type;
  11470. }
  11471. set type( _value ) { /* */ }
  11472. /**
  11473. * Constructs a new node material.
  11474. */
  11475. constructor() {
  11476. super();
  11477. /**
  11478. * This flag can be used for type testing.
  11479. *
  11480. * @type {boolean}
  11481. * @readonly
  11482. * @default true
  11483. */
  11484. this.isNodeMaterial = true;
  11485. /**
  11486. * Whether this material is affected by fog or not.
  11487. *
  11488. * @type {boolean}
  11489. * @default true
  11490. */
  11491. this.fog = true;
  11492. /**
  11493. * Whether this material is affected by lights or not.
  11494. *
  11495. * @type {boolean}
  11496. * @default false
  11497. */
  11498. this.lights = false;
  11499. /**
  11500. * Whether this material uses hardware clipping or not.
  11501. * This property is managed by the engine and should not be
  11502. * modified by apps.
  11503. *
  11504. * @type {boolean}
  11505. * @default false
  11506. */
  11507. this.hardwareClipping = false;
  11508. /**
  11509. * Node materials which set their `lights` property to `true`
  11510. * are affected by all lights of the scene. Sometimes selective
  11511. * lighting is wanted which means only _some_ lights in the scene
  11512. * affect a material. This can be achieved by creating an instance
  11513. * of {@link LightsNode} with a list of selective
  11514. * lights and assign the node to this property.
  11515. *
  11516. * ```js
  11517. * const customLightsNode = lights( [ light1, light2 ] );
  11518. * material.lightsNode = customLightsNode;
  11519. * ```
  11520. *
  11521. * @type {?LightsNode}
  11522. * @default null
  11523. */
  11524. this.lightsNode = null;
  11525. /**
  11526. * The environment of node materials can be defined by an environment
  11527. * map assigned to the `envMap` property or by `Scene.environment`
  11528. * if the node material is a PBR material. This node property allows to overwrite
  11529. * the default behavior and define the environment with a custom node.
  11530. *
  11531. * ```js
  11532. * material.envNode = pmremTexture( renderTarget.texture );
  11533. * ```
  11534. *
  11535. * @type {?Node<vec3>}
  11536. * @default null
  11537. */
  11538. this.envNode = null;
  11539. /**
  11540. * The lighting of node materials might be influenced by ambient occlusion.
  11541. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11542. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11543. * the default and define the ambient occlusion with a custom node instead.
  11544. *
  11545. * If you don't want to overwrite the diffuse color but modify the existing
  11546. * values instead, use {@link materialAO}.
  11547. *
  11548. * @type {?Node<float>}
  11549. * @default null
  11550. */
  11551. this.aoNode = null;
  11552. /**
  11553. * The diffuse color of node materials is by default inferred from the
  11554. * `color` and `map` properties. This node property allows to overwrite the default
  11555. * and define the diffuse color with a node instead.
  11556. *
  11557. * ```js
  11558. * material.colorNode = color( 0xff0000 ); // define red color
  11559. * ```
  11560. *
  11561. * If you don't want to overwrite the diffuse color but modify the existing
  11562. * values instead, use {@link materialColor}.
  11563. *
  11564. * ```js
  11565. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11566. * ```
  11567. *
  11568. * @type {?Node<vec3>}
  11569. * @default null
  11570. */
  11571. this.colorNode = null;
  11572. /**
  11573. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11574. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11575. * and define the normals with a node instead.
  11576. *
  11577. * If you don't want to overwrite the normals but modify the existing values instead,
  11578. * use {@link materialNormal}.
  11579. *
  11580. * @type {?Node<vec3>}
  11581. * @default null
  11582. */
  11583. this.normalNode = null;
  11584. /**
  11585. * The opacity of node materials is by default inferred from the `opacity`
  11586. * and `alphaMap` properties. This node property allows to overwrite the default
  11587. * and define the opacity with a node instead.
  11588. *
  11589. * If you don't want to overwrite the normals but modify the existing
  11590. * value instead, use {@link materialOpacity}.
  11591. *
  11592. * @type {?Node<float>}
  11593. * @default null
  11594. */
  11595. this.opacityNode = null;
  11596. /**
  11597. * This node can be used to to implement a variety of filter-like effects. The idea is
  11598. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11599. * to create an arbitrary effect and then assign the node composition to this property.
  11600. * Everything behind the object using this material will now be affected by a filter.
  11601. *
  11602. * ```js
  11603. * const material = new NodeMaterial()
  11604. * material.transparent = true;
  11605. *
  11606. * // everything behind the object will be monochromatic
  11607. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  11608. * ```
  11609. *
  11610. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11611. *
  11612. * @type {?Node<vec3>}
  11613. * @default null
  11614. */
  11615. this.backdropNode = null;
  11616. /**
  11617. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11618. *
  11619. * @type {?Node<float>}
  11620. * @default null
  11621. */
  11622. this.backdropAlphaNode = null;
  11623. /**
  11624. * The alpha test of node materials is by default inferred from the `alphaTest`
  11625. * property. This node property allows to overwrite the default and define the
  11626. * alpha test with a node instead.
  11627. *
  11628. * If you don't want to overwrite the alpha test but modify the existing
  11629. * value instead, use {@link materialAlphaTest}.
  11630. *
  11631. * @type {?Node<float>}
  11632. * @default null
  11633. */
  11634. this.alphaTestNode = null;
  11635. /**
  11636. * The local vertex positions are computed based on multiple factors like the
  11637. * attribute data, morphing or skinning. This node property allows to overwrite
  11638. * the default and define local vertex positions with nodes instead.
  11639. *
  11640. * If you don't want to overwrite the vertex positions but modify the existing
  11641. * values instead, use {@link positionLocal}.
  11642. *
  11643. *```js
  11644. * material.positionNode = positionLocal.add( displace );
  11645. * ```
  11646. *
  11647. * @type {?Node<vec3>}
  11648. * @default null
  11649. */
  11650. this.positionNode = null;
  11651. /**
  11652. * This node property is intended for logic which modifies geometry data once or per animation step.
  11653. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11654. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11655. * can be implemented.
  11656. *
  11657. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11658. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11659. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11660. * eventually assigned to `geometryNode`.
  11661. *
  11662. * @type {Function}
  11663. * @default null
  11664. */
  11665. this.geometryNode = null;
  11666. /**
  11667. * Allows to overwrite depth values in the fragment shader.
  11668. *
  11669. * @type {?Node<float>}
  11670. * @default null
  11671. */
  11672. this.depthNode = null;
  11673. /**
  11674. * Allows to overwrite the position used for shadow map rendering which
  11675. * is by default {@link positionWorld}, the vertex position
  11676. * in world space.
  11677. *
  11678. * @type {?Node<float>}
  11679. * @default null
  11680. */
  11681. this.shadowPositionNode = null;
  11682. /**
  11683. * This node can be used to influence how an object using this node material
  11684. * receive shadows.
  11685. *
  11686. * ```js
  11687. * const totalShadows = float( 1 ).toVar();
  11688. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11689. * totalShadows.mulAssign( shadow );
  11690. * //return float( 1 ); // bypass received shadows
  11691. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11692. * } );
  11693. *
  11694. * @type {?Node<vec4>}
  11695. * @default null
  11696. */
  11697. this.receivedShadowNode = null;
  11698. /**
  11699. * This node can be used to influence how an object using this node material
  11700. * casts shadows. To apply a color to shadows, you can simply do:
  11701. *
  11702. * ```js
  11703. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11704. * ```
  11705. *
  11706. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11707. * is also common to use the property with `Fn` function so checks are performed
  11708. * per fragment.
  11709. *
  11710. * ```js
  11711. * materialCustomShadow.castShadowNode = Fn( () => {
  11712. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11713. * return materialColor;
  11714. * } )();
  11715. * ```
  11716. *
  11717. * @type {?Node<vec4>}
  11718. * @default null
  11719. */
  11720. this.castShadowNode = null;
  11721. /**
  11722. * This node can be used to define the final output of the material.
  11723. *
  11724. * TODO: Explain the differences to `fragmentNode`.
  11725. *
  11726. * @type {?Node<vec4>}
  11727. * @default null
  11728. */
  11729. this.outputNode = null;
  11730. /**
  11731. * MRT configuration is done on renderer or pass level. This node allows to
  11732. * overwrite what values are written into MRT targets on material level. This
  11733. * can be useful for implementing selective FX features that should only affect
  11734. * specific objects.
  11735. *
  11736. * @type {?MRTNode}
  11737. * @default null
  11738. */
  11739. this.mrtNode = null;
  11740. /**
  11741. * This node property can be used if you need complete freedom in implementing
  11742. * the fragment shader. Assigning a node will replace the built-in material
  11743. * logic used in the fragment stage.
  11744. *
  11745. * @type {?Node<vec4>}
  11746. * @default null
  11747. */
  11748. this.fragmentNode = null;
  11749. /**
  11750. * This node property can be used if you need complete freedom in implementing
  11751. * the vertex shader. Assigning a node will replace the built-in material logic
  11752. * used in the vertex stage.
  11753. *
  11754. * @type {?Node<vec4>}
  11755. * @default null
  11756. */
  11757. this.vertexNode = null;
  11758. }
  11759. /**
  11760. * Allows to define a custom cache key that influence the material key computation
  11761. * for render objects.
  11762. *
  11763. * @return {string} The custom cache key.
  11764. */
  11765. customProgramCacheKey() {
  11766. return this.type + getCacheKey$1( this );
  11767. }
  11768. /**
  11769. * Builds this material with the given node builder.
  11770. *
  11771. * @param {NodeBuilder} builder - The current node builder.
  11772. */
  11773. build( builder ) {
  11774. this.setup( builder );
  11775. }
  11776. /**
  11777. * Setups a node material observer with the given builder.
  11778. *
  11779. * @param {NodeBuilder} builder - The current node builder.
  11780. * @return {NodeMaterialObserver} The node material observer.
  11781. */
  11782. setupObserver( builder ) {
  11783. return new NodeMaterialObserver( builder );
  11784. }
  11785. /**
  11786. * Setups the vertex and fragment stage of this node material.
  11787. *
  11788. * @param {NodeBuilder} builder - The current node builder.
  11789. */
  11790. setup( builder ) {
  11791. builder.context.setupNormal = () => this.setupNormal( builder );
  11792. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11793. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11794. const renderer = builder.renderer;
  11795. const renderTarget = renderer.getRenderTarget();
  11796. // < VERTEX STAGE >
  11797. builder.addStack();
  11798. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11799. builder.stack.outputNode = vertexNode;
  11800. this.setupHardwareClipping( builder );
  11801. if ( this.geometryNode !== null ) {
  11802. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11803. }
  11804. builder.addFlow( 'vertex', builder.removeStack() );
  11805. // < FRAGMENT STAGE >
  11806. builder.addStack();
  11807. let resultNode;
  11808. const clippingNode = this.setupClipping( builder );
  11809. if ( this.depthWrite === true || this.depthTest === true ) {
  11810. // only write depth if depth buffer is configured
  11811. if ( renderTarget !== null ) {
  11812. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11813. } else {
  11814. if ( renderer.depth === true ) this.setupDepth( builder );
  11815. }
  11816. }
  11817. if ( this.fragmentNode === null ) {
  11818. this.setupDiffuseColor( builder );
  11819. this.setupVariants( builder );
  11820. const outgoingLightNode = this.setupLighting( builder );
  11821. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11822. // force unsigned floats - useful for RenderTargets
  11823. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11824. resultNode = this.setupOutput( builder, basicOutput );
  11825. // OUTPUT NODE
  11826. output.assign( resultNode );
  11827. //
  11828. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11829. // MRT
  11830. if ( renderTarget !== null ) {
  11831. const mrt = renderer.getMRT();
  11832. const materialMRT = this.mrtNode;
  11833. if ( mrt !== null ) {
  11834. resultNode = mrt;
  11835. if ( materialMRT !== null ) {
  11836. resultNode = mrt.merge( materialMRT );
  11837. }
  11838. } else if ( materialMRT !== null ) {
  11839. resultNode = materialMRT;
  11840. }
  11841. }
  11842. } else {
  11843. let fragmentNode = this.fragmentNode;
  11844. if ( fragmentNode.isOutputStructNode !== true ) {
  11845. fragmentNode = vec4( fragmentNode );
  11846. }
  11847. resultNode = this.setupOutput( builder, fragmentNode );
  11848. }
  11849. builder.stack.outputNode = resultNode;
  11850. builder.addFlow( 'fragment', builder.removeStack() );
  11851. // < OBSERVER >
  11852. builder.observer = this.setupObserver( builder );
  11853. }
  11854. /**
  11855. * Setups the clipping node.
  11856. *
  11857. * @param {NodeBuilder} builder - The current node builder.
  11858. * @return {ClippingNode} The clipping node.
  11859. */
  11860. setupClipping( builder ) {
  11861. if ( builder.clippingContext === null ) return null;
  11862. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11863. let result = null;
  11864. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11865. const samples = builder.renderer.samples;
  11866. if ( this.alphaToCoverage && samples > 1 ) {
  11867. // to be added to flow when the color/alpha value has been determined
  11868. result = clippingAlpha();
  11869. } else {
  11870. builder.stack.add( clipping() );
  11871. }
  11872. }
  11873. return result;
  11874. }
  11875. /**
  11876. * Setups the hardware clipping if available on the current device.
  11877. *
  11878. * @param {NodeBuilder} builder - The current node builder.
  11879. */
  11880. setupHardwareClipping( builder ) {
  11881. this.hardwareClipping = false;
  11882. if ( builder.clippingContext === null ) return;
  11883. const candidateCount = builder.clippingContext.unionPlanes.length;
  11884. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11885. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11886. builder.stack.add( hardwareClipping() );
  11887. this.hardwareClipping = true;
  11888. }
  11889. return;
  11890. }
  11891. /**
  11892. * Setups the depth of this material.
  11893. *
  11894. * @param {NodeBuilder} builder - The current node builder.
  11895. */
  11896. setupDepth( builder ) {
  11897. const { renderer, camera } = builder;
  11898. // Depth
  11899. let depthNode = this.depthNode;
  11900. if ( depthNode === null ) {
  11901. const mrt = renderer.getMRT();
  11902. if ( mrt && mrt.has( 'depth' ) ) {
  11903. depthNode = mrt.get( 'depth' );
  11904. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11905. if ( camera.isPerspectiveCamera ) {
  11906. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11907. } else {
  11908. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11909. }
  11910. }
  11911. }
  11912. if ( depthNode !== null ) {
  11913. depth.assign( depthNode ).append();
  11914. }
  11915. }
  11916. /**
  11917. * Setups the position node in view space. This method exists
  11918. * so derived node materials can modify the implementation e.g. sprite materials.
  11919. *
  11920. * @param {NodeBuilder} builder - The current node builder.
  11921. * @return {Node<vec3>} The position in view space.
  11922. */
  11923. setupPositionView( /*builder*/ ) {
  11924. return modelViewMatrix.mul( positionLocal ).xyz;
  11925. }
  11926. /**
  11927. * Setups the position in clip space.
  11928. *
  11929. * @param {NodeBuilder} builder - The current node builder.
  11930. * @return {Node<vec4>} The position in view space.
  11931. */
  11932. setupModelViewProjection( /*builder*/ ) {
  11933. return cameraProjectionMatrix.mul( positionView );
  11934. }
  11935. /**
  11936. * Setups the logic for the vertex stage.
  11937. *
  11938. * @param {NodeBuilder} builder - The current node builder.
  11939. * @return {Node<vec4>} The position in clip space.
  11940. */
  11941. setupVertex( builder ) {
  11942. builder.addStack();
  11943. this.setupPosition( builder );
  11944. builder.context.vertex = builder.removeStack();
  11945. return modelViewProjection;
  11946. }
  11947. /**
  11948. * Setups the computation of the position in local space.
  11949. *
  11950. * @param {NodeBuilder} builder - The current node builder.
  11951. * @return {Node<vec3>} The position in local space.
  11952. */
  11953. setupPosition( builder ) {
  11954. const { object, geometry } = builder;
  11955. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11956. morphReference( object ).append();
  11957. }
  11958. if ( object.isSkinnedMesh === true ) {
  11959. skinningReference( object ).append();
  11960. }
  11961. if ( this.displacementMap ) {
  11962. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11963. const displacementScale = materialReference( 'displacementScale', 'float' );
  11964. const displacementBias = materialReference( 'displacementBias', 'float' );
  11965. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11966. }
  11967. if ( object.isBatchedMesh ) {
  11968. batch( object ).append();
  11969. }
  11970. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11971. instancedMesh( object ).append();
  11972. }
  11973. if ( this.positionNode !== null ) {
  11974. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11975. }
  11976. return positionLocal;
  11977. }
  11978. /**
  11979. * Setups the computation of the material's diffuse color.
  11980. *
  11981. * @param {NodeBuilder} builder - The current node builder.
  11982. * @param {BufferGeometry} geometry - The geometry.
  11983. */
  11984. setupDiffuseColor( { object, geometry } ) {
  11985. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11986. // VERTEX COLORS
  11987. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11988. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11989. }
  11990. // Instanced colors
  11991. if ( object.instanceColor ) {
  11992. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11993. colorNode = instanceColor.mul( colorNode );
  11994. }
  11995. if ( object.isBatchedMesh && object._colorsTexture ) {
  11996. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11997. colorNode = batchColor.mul( colorNode );
  11998. }
  11999. // COLOR
  12000. diffuseColor.assign( colorNode );
  12001. // OPACITY
  12002. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12003. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  12004. // ALPHA TEST
  12005. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  12006. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  12007. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  12008. }
  12009. // ALPHA HASH
  12010. if ( this.alphaHash === true ) {
  12011. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  12012. }
  12013. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  12014. diffuseColor.a.assign( 1.0 );
  12015. }
  12016. }
  12017. /**
  12018. * Abstract interface method that can be implemented by derived materials
  12019. * to setup material-specific node variables.
  12020. *
  12021. * @abstract
  12022. * @param {NodeBuilder} builder - The current node builder.
  12023. */
  12024. setupVariants( /*builder*/ ) {
  12025. // Interface function.
  12026. }
  12027. /**
  12028. * Setups the outgoing light node variable
  12029. *
  12030. * @return {Node<vec3>} The outgoing light node.
  12031. */
  12032. setupOutgoingLight() {
  12033. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  12034. }
  12035. /**
  12036. * Setups the normal node from the material.
  12037. *
  12038. * @return {Node<vec3>} The normal node.
  12039. */
  12040. setupNormal() {
  12041. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  12042. }
  12043. /**
  12044. * Setups the environment node from the material.
  12045. *
  12046. * @param {NodeBuilder} builder - The current node builder.
  12047. * @return {Node<vec4>} The environment node.
  12048. */
  12049. setupEnvironment( /*builder*/ ) {
  12050. let node = null;
  12051. if ( this.envNode ) {
  12052. node = this.envNode;
  12053. } else if ( this.envMap ) {
  12054. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  12055. }
  12056. return node;
  12057. }
  12058. /**
  12059. * Setups the light map node from the material.
  12060. *
  12061. * @param {NodeBuilder} builder - The current node builder.
  12062. * @return {Node<vec3>} The light map node.
  12063. */
  12064. setupLightMap( builder ) {
  12065. let node = null;
  12066. if ( builder.material.lightMap ) {
  12067. node = new IrradianceNode( materialLightMap );
  12068. }
  12069. return node;
  12070. }
  12071. /**
  12072. * Setups the lights node based on the scene, environment and material.
  12073. *
  12074. * @param {NodeBuilder} builder - The current node builder.
  12075. * @return {LightsNode} The lights node.
  12076. */
  12077. setupLights( builder ) {
  12078. const materialLightsNode = [];
  12079. //
  12080. const envNode = this.setupEnvironment( builder );
  12081. if ( envNode && envNode.isLightingNode ) {
  12082. materialLightsNode.push( envNode );
  12083. }
  12084. const lightMapNode = this.setupLightMap( builder );
  12085. if ( lightMapNode && lightMapNode.isLightingNode ) {
  12086. materialLightsNode.push( lightMapNode );
  12087. }
  12088. if ( this.aoNode !== null || builder.material.aoMap ) {
  12089. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  12090. materialLightsNode.push( new AONode( aoNode ) );
  12091. }
  12092. let lightsN = this.lightsNode || builder.lightsNode;
  12093. if ( materialLightsNode.length > 0 ) {
  12094. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  12095. }
  12096. return lightsN;
  12097. }
  12098. /**
  12099. * This method should be implemented by most derived materials
  12100. * since it defines the material's lighting model.
  12101. *
  12102. * @abstract
  12103. * @param {NodeBuilder} builder - The current node builder.
  12104. * @return {LightingModel} The lighting model.
  12105. */
  12106. setupLightingModel( /*builder*/ ) {
  12107. // Interface function.
  12108. }
  12109. /**
  12110. * Setups the outgoing light node.
  12111. *
  12112. * @param {NodeBuilder} builder - The current node builder.
  12113. * @return {Node<vec3>} The outgoing light node.
  12114. */
  12115. setupLighting( builder ) {
  12116. const { material } = builder;
  12117. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  12118. // OUTGOING LIGHT
  12119. const lights = this.lights === true || this.lightsNode !== null;
  12120. const lightsNode = lights ? this.setupLights( builder ) : null;
  12121. let outgoingLightNode = this.setupOutgoingLight( builder );
  12122. if ( lightsNode && lightsNode.getScope().hasLights ) {
  12123. const lightingModel = this.setupLightingModel( builder );
  12124. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  12125. } else if ( backdropNode !== null ) {
  12126. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  12127. }
  12128. // EMISSIVE
  12129. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  12130. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  12131. outgoingLightNode = outgoingLightNode.add( emissive );
  12132. }
  12133. return outgoingLightNode;
  12134. }
  12135. /**
  12136. * Setups the output node.
  12137. *
  12138. * @param {NodeBuilder} builder - The current node builder.
  12139. * @param {Node<vec4>} outputNode - The existing output node.
  12140. * @return {Node<vec4>} The output node.
  12141. */
  12142. setupOutput( builder, outputNode ) {
  12143. // FOG
  12144. if ( this.fog === true ) {
  12145. const fogNode = builder.fogNode;
  12146. if ( fogNode ) {
  12147. output.assign( outputNode );
  12148. outputNode = vec4( fogNode );
  12149. }
  12150. }
  12151. return outputNode;
  12152. }
  12153. /**
  12154. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  12155. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  12156. * defining all material properties of the classic type in the node type.
  12157. *
  12158. * @param {Material} material - The material to copy properties with their values to this node material.
  12159. */
  12160. setDefaultValues( material ) {
  12161. // This approach is to reuse the native refreshUniforms*
  12162. // and turn available the use of features like transmission and environment in core
  12163. for ( const property in material ) {
  12164. const value = material[ property ];
  12165. if ( this[ property ] === undefined ) {
  12166. this[ property ] = value;
  12167. if ( value && value.clone ) this[ property ] = value.clone();
  12168. }
  12169. }
  12170. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  12171. for ( const key in descriptors ) {
  12172. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  12173. descriptors[ key ].get !== undefined ) {
  12174. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  12175. }
  12176. }
  12177. }
  12178. /**
  12179. * Serializes this material to JSON.
  12180. *
  12181. * @param {?(Object|string)} meta - The meta information for serialization.
  12182. * @return {Object} The serialized node.
  12183. */
  12184. toJSON( meta ) {
  12185. const isRoot = ( meta === undefined || typeof meta === 'string' );
  12186. if ( isRoot ) {
  12187. meta = {
  12188. textures: {},
  12189. images: {},
  12190. nodes: {}
  12191. };
  12192. }
  12193. const data = Material.prototype.toJSON.call( this, meta );
  12194. const nodeChildren = getNodeChildren( this );
  12195. data.inputNodes = {};
  12196. for ( const { property, childNode } of nodeChildren ) {
  12197. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  12198. }
  12199. // TODO: Copied from Object3D.toJSON
  12200. function extractFromCache( cache ) {
  12201. const values = [];
  12202. for ( const key in cache ) {
  12203. const data = cache[ key ];
  12204. delete data.metadata;
  12205. values.push( data );
  12206. }
  12207. return values;
  12208. }
  12209. if ( isRoot ) {
  12210. const textures = extractFromCache( meta.textures );
  12211. const images = extractFromCache( meta.images );
  12212. const nodes = extractFromCache( meta.nodes );
  12213. if ( textures.length > 0 ) data.textures = textures;
  12214. if ( images.length > 0 ) data.images = images;
  12215. if ( nodes.length > 0 ) data.nodes = nodes;
  12216. }
  12217. return data;
  12218. }
  12219. /**
  12220. * Copies the properties of the given node material to this instance.
  12221. *
  12222. * @param {NodeMaterial} source - The material to copy.
  12223. * @return {NodeMaterial} A reference to this node material.
  12224. */
  12225. copy( source ) {
  12226. this.lightsNode = source.lightsNode;
  12227. this.envNode = source.envNode;
  12228. this.colorNode = source.colorNode;
  12229. this.normalNode = source.normalNode;
  12230. this.opacityNode = source.opacityNode;
  12231. this.backdropNode = source.backdropNode;
  12232. this.backdropAlphaNode = source.backdropAlphaNode;
  12233. this.alphaTestNode = source.alphaTestNode;
  12234. this.positionNode = source.positionNode;
  12235. this.geometryNode = source.geometryNode;
  12236. this.depthNode = source.depthNode;
  12237. this.shadowPositionNode = source.shadowPositionNode;
  12238. this.receivedShadowNode = source.receivedShadowNode;
  12239. this.castShadowNode = source.castShadowNode;
  12240. this.outputNode = source.outputNode;
  12241. this.mrtNode = source.mrtNode;
  12242. this.fragmentNode = source.fragmentNode;
  12243. this.vertexNode = source.vertexNode;
  12244. return super.copy( source );
  12245. }
  12246. }
  12247. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  12248. /**
  12249. * Node material version of `LineBasicMaterial`.
  12250. *
  12251. * @augments NodeMaterial
  12252. */
  12253. class LineBasicNodeMaterial extends NodeMaterial {
  12254. static get type() {
  12255. return 'LineBasicNodeMaterial';
  12256. }
  12257. /**
  12258. * Constructs a new line basic node material.
  12259. *
  12260. * @param {?Object} parameters - The configuration parameter.
  12261. */
  12262. constructor( parameters ) {
  12263. super();
  12264. /**
  12265. * This flag can be used for type testing.
  12266. *
  12267. * @type {boolean}
  12268. * @readonly
  12269. * @default true
  12270. */
  12271. this.isLineBasicNodeMaterial = true;
  12272. this.setDefaultValues( _defaultValues$d );
  12273. this.setValues( parameters );
  12274. }
  12275. }
  12276. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  12277. /**
  12278. * Node material version of `LineDashedMaterial`.
  12279. *
  12280. * @augments NodeMaterial
  12281. */
  12282. class LineDashedNodeMaterial extends NodeMaterial {
  12283. static get type() {
  12284. return 'LineDashedNodeMaterial';
  12285. }
  12286. /**
  12287. * Constructs a new line dashed node material.
  12288. *
  12289. * @param {?Object} parameters - The configuration parameter.
  12290. */
  12291. constructor( parameters ) {
  12292. super();
  12293. /**
  12294. * This flag can be used for type testing.
  12295. *
  12296. * @type {boolean}
  12297. * @readonly
  12298. * @default true
  12299. */
  12300. this.isLineDashedNodeMaterial = true;
  12301. this.setDefaultValues( _defaultValues$c );
  12302. /**
  12303. * The dash offset.
  12304. *
  12305. * @type {number}
  12306. * @default 0
  12307. */
  12308. this.dashOffset = 0;
  12309. /**
  12310. * The offset of dash materials is by default inferred from the `dashOffset`
  12311. * property. This node property allows to overwrite the default
  12312. * and define the offset with a node instead.
  12313. *
  12314. * If you don't want to overwrite the offset but modify the existing
  12315. * value instead, use {@link materialLineDashOffset}.
  12316. *
  12317. * @type {?Node<float>}
  12318. * @default null
  12319. */
  12320. this.offsetNode = null;
  12321. /**
  12322. * The scale of dash materials is by default inferred from the `scale`
  12323. * property. This node property allows to overwrite the default
  12324. * and define the scale with a node instead.
  12325. *
  12326. * If you don't want to overwrite the scale but modify the existing
  12327. * value instead, use {@link materialLineScale}.
  12328. *
  12329. * @type {?Node<float>}
  12330. * @default null
  12331. */
  12332. this.dashScaleNode = null;
  12333. /**
  12334. * The dash size of dash materials is by default inferred from the `dashSize`
  12335. * property. This node property allows to overwrite the default
  12336. * and define the dash size with a node instead.
  12337. *
  12338. * If you don't want to overwrite the dash size but modify the existing
  12339. * value instead, use {@link materialLineDashSize}.
  12340. *
  12341. * @type {?Node<float>}
  12342. * @default null
  12343. */
  12344. this.dashSizeNode = null;
  12345. /**
  12346. * The gap size of dash materials is by default inferred from the `gapSize`
  12347. * property. This node property allows to overwrite the default
  12348. * and define the gap size with a node instead.
  12349. *
  12350. * If you don't want to overwrite the gap size but modify the existing
  12351. * value instead, use {@link materialLineGapSize}.
  12352. *
  12353. * @type {?Node<float>}
  12354. * @default null
  12355. */
  12356. this.gapSizeNode = null;
  12357. this.setValues( parameters );
  12358. }
  12359. /**
  12360. * Setups the dash specific node variables.
  12361. *
  12362. * @param {NodeBuilder} builder - The current node builder.
  12363. */
  12364. setupVariants( /* builder */ ) {
  12365. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12366. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12367. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12368. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12369. dashSize.assign( dashSizeNode );
  12370. gapSize.assign( gapSizeNode );
  12371. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12372. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12373. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12374. }
  12375. }
  12376. let _sharedFramebuffer = null;
  12377. /**
  12378. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12379. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12380. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12381. *
  12382. * @augments ViewportTextureNode
  12383. */
  12384. class ViewportSharedTextureNode extends ViewportTextureNode {
  12385. static get type() {
  12386. return 'ViewportSharedTextureNode';
  12387. }
  12388. /**
  12389. * Constructs a new viewport shared texture node.
  12390. *
  12391. * @param {Node} [uvNode=screenUV] - The uv node.
  12392. * @param {?Node} [levelNode=null] - The level node.
  12393. */
  12394. constructor( uvNode = screenUV, levelNode = null ) {
  12395. if ( _sharedFramebuffer === null ) {
  12396. _sharedFramebuffer = new FramebufferTexture();
  12397. }
  12398. super( uvNode, levelNode, _sharedFramebuffer );
  12399. }
  12400. updateReference() {
  12401. return this;
  12402. }
  12403. }
  12404. /**
  12405. * TSL function for creating a shared viewport texture node.
  12406. *
  12407. * @tsl
  12408. * @function
  12409. * @param {Node} [uvNode=screenUV] - The uv node.
  12410. * @param {?Node} [levelNode=null] - The level node.
  12411. * @returns {ViewportSharedTextureNode}
  12412. */
  12413. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12414. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12415. /**
  12416. * This node material can be used to render lines with a size larger than one
  12417. * by representing them as instanced meshes.
  12418. *
  12419. * @augments NodeMaterial
  12420. */
  12421. class Line2NodeMaterial extends NodeMaterial {
  12422. static get type() {
  12423. return 'Line2NodeMaterial';
  12424. }
  12425. /**
  12426. * Constructs a new node material for wide line rendering.
  12427. *
  12428. * @param {?Object} parameters - The configuration parameter.
  12429. */
  12430. constructor( parameters = {} ) {
  12431. super();
  12432. /**
  12433. * This flag can be used for type testing.
  12434. *
  12435. * @type {boolean}
  12436. * @readonly
  12437. * @default true
  12438. */
  12439. this.isLine2NodeMaterial = true;
  12440. this.setDefaultValues( _defaultValues$b );
  12441. /**
  12442. * Whether vertex colors should be used or not.
  12443. *
  12444. * @type {boolean}
  12445. * @default false
  12446. */
  12447. this.useColor = parameters.vertexColors;
  12448. /**
  12449. * The dash offset.
  12450. *
  12451. * @type {number}
  12452. * @default 0
  12453. */
  12454. this.dashOffset = 0;
  12455. /**
  12456. * The line width.
  12457. *
  12458. * @type {number}
  12459. * @default 0
  12460. */
  12461. this.lineWidth = 1;
  12462. /**
  12463. * Defines the lines color.
  12464. *
  12465. * @type {?Node<vec3>}
  12466. * @default null
  12467. */
  12468. this.lineColorNode = null;
  12469. /**
  12470. * Defines the offset.
  12471. *
  12472. * @type {?Node<float>}
  12473. * @default null
  12474. */
  12475. this.offsetNode = null;
  12476. /**
  12477. * Defines the dash scale.
  12478. *
  12479. * @type {?Node<float>}
  12480. * @default null
  12481. */
  12482. this.dashScaleNode = null;
  12483. /**
  12484. * Defines the dash size.
  12485. *
  12486. * @type {?Node<float>}
  12487. * @default null
  12488. */
  12489. this.dashSizeNode = null;
  12490. /**
  12491. * Defines the gap size.
  12492. *
  12493. * @type {?Node<float>}
  12494. * @default null
  12495. */
  12496. this.gapSizeNode = null;
  12497. /**
  12498. * Blending is set to `NoBlending` since transparency
  12499. * is not supported, yet.
  12500. *
  12501. * @type {number}
  12502. * @default 0
  12503. */
  12504. this.blending = NoBlending;
  12505. this._useDash = parameters.dashed;
  12506. this._useAlphaToCoverage = true;
  12507. this._useWorldUnits = false;
  12508. this.setValues( parameters );
  12509. }
  12510. /**
  12511. * Setups the vertex and fragment stage of this node material.
  12512. *
  12513. * @param {NodeBuilder} builder - The current node builder.
  12514. */
  12515. setup( builder ) {
  12516. const { renderer } = builder;
  12517. const useAlphaToCoverage = this._useAlphaToCoverage;
  12518. const useColor = this.useColor;
  12519. const useDash = this._useDash;
  12520. const useWorldUnits = this._useWorldUnits;
  12521. const trimSegment = Fn( ( { start, end } ) => {
  12522. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12523. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12524. const nearEstimate = b.mul( -0.5 ).div( a );
  12525. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12526. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12527. } ).setLayout( {
  12528. name: 'trimSegment',
  12529. type: 'vec4',
  12530. inputs: [
  12531. { name: 'start', type: 'vec4' },
  12532. { name: 'end', type: 'vec4' }
  12533. ]
  12534. } );
  12535. this.vertexNode = Fn( () => {
  12536. const instanceStart = attribute( 'instanceStart' );
  12537. const instanceEnd = attribute( 'instanceEnd' );
  12538. // camera space
  12539. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12540. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12541. if ( useDash ) {
  12542. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12543. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12544. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12545. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12546. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12547. lineDistance = lineDistance.add( offsetNode );
  12548. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12549. }
  12550. if ( useWorldUnits ) {
  12551. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12552. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12553. }
  12554. const aspect = viewport.z.div( viewport.w );
  12555. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12556. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12557. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12558. // perhaps there is a more elegant solution -- WestLangley
  12559. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12560. If( perspective, () => {
  12561. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12562. end.assign( trimSegment( { start: start, end: end } ) );
  12563. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12564. start.assign( trimSegment( { start: end, end: start } ) );
  12565. } );
  12566. } );
  12567. // clip space
  12568. const clipStart = cameraProjectionMatrix.mul( start );
  12569. const clipEnd = cameraProjectionMatrix.mul( end );
  12570. // ndc space
  12571. const ndcStart = clipStart.xyz.div( clipStart.w );
  12572. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12573. // direction
  12574. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12575. // account for clip-space aspect ratio
  12576. dir.x.assign( dir.x.mul( aspect ) );
  12577. dir.assign( dir.normalize() );
  12578. const clip = vec4().toVar();
  12579. if ( useWorldUnits ) {
  12580. // get the offset direction as perpendicular to the view vector
  12581. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12582. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12583. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12584. const worldFwd = worldDir.cross( worldUp );
  12585. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12586. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12587. // height offset
  12588. const hw = materialLineWidth.mul( 0.5 );
  12589. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12590. // don't extend the line if we're rendering dashes because we
  12591. // won't be rendering the endcaps
  12592. if ( ! useDash ) {
  12593. // cap extension
  12594. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12595. // add width to the box
  12596. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12597. // endcaps
  12598. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12599. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12600. } );
  12601. }
  12602. // project the worldpos
  12603. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12604. // shift the depth of the projected points so the line
  12605. // segments overlap neatly
  12606. const clipPose = vec3().toVar();
  12607. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12608. clip.z.assign( clipPose.z.mul( clip.w ) );
  12609. } else {
  12610. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12611. // undo aspect ratio adjustment
  12612. dir.x.assign( dir.x.div( aspect ) );
  12613. offset.x.assign( offset.x.div( aspect ) );
  12614. // sign flip
  12615. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12616. // endcaps
  12617. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12618. offset.assign( offset.sub( dir ) );
  12619. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12620. offset.assign( offset.add( dir ) );
  12621. } );
  12622. // adjust for linewidth
  12623. offset.assign( offset.mul( materialLineWidth ) );
  12624. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12625. offset.assign( offset.div( viewport.w ) );
  12626. // select end
  12627. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12628. // back to clip space
  12629. offset.assign( offset.mul( clip.w ) );
  12630. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12631. }
  12632. return clip;
  12633. } )();
  12634. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12635. const p13 = p1.sub( p3 );
  12636. const p43 = p4.sub( p3 );
  12637. const p21 = p2.sub( p1 );
  12638. const d1343 = p13.dot( p43 );
  12639. const d4321 = p43.dot( p21 );
  12640. const d1321 = p13.dot( p21 );
  12641. const d4343 = p43.dot( p43 );
  12642. const d2121 = p21.dot( p21 );
  12643. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12644. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12645. const mua = numer.div( denom ).clamp();
  12646. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12647. return vec2( mua, mub );
  12648. } );
  12649. this.colorNode = Fn( () => {
  12650. const vUv = uv();
  12651. if ( useDash ) {
  12652. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12653. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12654. dashSize.assign( dashSizeNode );
  12655. gapSize.assign( gapSizeNode );
  12656. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12657. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12658. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12659. }
  12660. const alpha = float( 1 ).toVar( 'alpha' );
  12661. if ( useWorldUnits ) {
  12662. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12663. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12664. // Find the closest points on the view ray and the line segment
  12665. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12666. const lineDir = worldEnd.sub( worldStart );
  12667. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12668. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12669. const p2 = rayEnd.mul( params.y );
  12670. const delta = p1.sub( p2 );
  12671. const len = delta.length();
  12672. const norm = len.div( materialLineWidth );
  12673. if ( ! useDash ) {
  12674. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12675. const dnorm = norm.fwidth();
  12676. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12677. } else {
  12678. norm.greaterThan( 0.5 ).discard();
  12679. }
  12680. }
  12681. } else {
  12682. // round endcaps
  12683. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12684. const a = vUv.x;
  12685. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12686. const len2 = a.mul( a ).add( b.mul( b ) );
  12687. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12688. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12689. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12690. } );
  12691. } else {
  12692. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12693. const a = vUv.x;
  12694. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12695. const len2 = a.mul( a ).add( b.mul( b ) );
  12696. len2.greaterThan( 1.0 ).discard();
  12697. } );
  12698. }
  12699. }
  12700. let lineColorNode;
  12701. if ( this.lineColorNode ) {
  12702. lineColorNode = this.lineColorNode;
  12703. } else {
  12704. if ( useColor ) {
  12705. const instanceColorStart = attribute( 'instanceColorStart' );
  12706. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12707. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12708. lineColorNode = instanceColor.mul( materialColor );
  12709. } else {
  12710. lineColorNode = materialColor;
  12711. }
  12712. }
  12713. return vec4( lineColorNode, alpha );
  12714. } )();
  12715. if ( this.transparent ) {
  12716. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12717. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12718. }
  12719. super.setup( builder );
  12720. }
  12721. /**
  12722. * Whether the lines should sized in world units or not.
  12723. * When set to `false` the unit is pixel.
  12724. *
  12725. * @type {boolean}
  12726. * @default false
  12727. */
  12728. get worldUnits() {
  12729. return this._useWorldUnits;
  12730. }
  12731. set worldUnits( value ) {
  12732. if ( this._useWorldUnits !== value ) {
  12733. this._useWorldUnits = value;
  12734. this.needsUpdate = true;
  12735. }
  12736. }
  12737. /**
  12738. * Whether the lines should be dashed or not.
  12739. *
  12740. * @type {boolean}
  12741. * @default false
  12742. */
  12743. get dashed() {
  12744. return this._useDash;
  12745. }
  12746. set dashed( value ) {
  12747. if ( this._useDash !== value ) {
  12748. this._useDash = value;
  12749. this.needsUpdate = true;
  12750. }
  12751. }
  12752. /**
  12753. * Whether alpha to coverage should be used or not.
  12754. *
  12755. * @type {boolean}
  12756. * @default true
  12757. */
  12758. get alphaToCoverage() {
  12759. return this._useAlphaToCoverage;
  12760. }
  12761. set alphaToCoverage( value ) {
  12762. if ( this._useAlphaToCoverage !== value ) {
  12763. this._useAlphaToCoverage = value;
  12764. this.needsUpdate = true;
  12765. }
  12766. }
  12767. }
  12768. /**
  12769. * Packs a direction vector into a color value.
  12770. *
  12771. * @tsl
  12772. * @function
  12773. * @param {Node<vec3>} node - The direction to pack.
  12774. * @return {Node<vec3>} The color.
  12775. */
  12776. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12777. /**
  12778. * Unpacks a color value into a direction vector.
  12779. *
  12780. * @tsl
  12781. * @function
  12782. * @param {Node<vec3>} node - The color to unpack.
  12783. * @return {Node<vec3>} The direction.
  12784. */
  12785. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12786. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12787. /**
  12788. * Node material version of `MeshNormalMaterial`.
  12789. *
  12790. * @augments NodeMaterial
  12791. */
  12792. class MeshNormalNodeMaterial extends NodeMaterial {
  12793. static get type() {
  12794. return 'MeshNormalNodeMaterial';
  12795. }
  12796. /**
  12797. * Constructs a new mesh normal node material.
  12798. *
  12799. * @param {?Object} parameters - The configuration parameter.
  12800. */
  12801. constructor( parameters ) {
  12802. super();
  12803. /**
  12804. * This flag can be used for type testing.
  12805. *
  12806. * @type {boolean}
  12807. * @readonly
  12808. * @default true
  12809. */
  12810. this.isMeshNormalNodeMaterial = true;
  12811. this.setDefaultValues( _defaultValues$a );
  12812. this.setValues( parameters );
  12813. }
  12814. /**
  12815. * Overwrites the default implementation by computing the diffuse color
  12816. * based on the normal data.
  12817. */
  12818. setupDiffuseColor() {
  12819. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12820. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12821. }
  12822. }
  12823. /**
  12824. * Can be used to compute texture coordinates for projecting an
  12825. * equirectangular texture onto a mesh for using it as the scene's
  12826. * background.
  12827. *
  12828. * ```js
  12829. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12830. * ```
  12831. *
  12832. * @augments TempNode
  12833. */
  12834. class EquirectUVNode extends TempNode {
  12835. static get type() {
  12836. return 'EquirectUVNode';
  12837. }
  12838. /**
  12839. * Constructs a new equirect uv node.
  12840. *
  12841. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12842. */
  12843. constructor( dirNode = positionWorldDirection ) {
  12844. super( 'vec2' );
  12845. /**
  12846. * A direction vector for sampling why is by default `positionWorldDirection`.
  12847. *
  12848. * @type {Node<vec3>}
  12849. */
  12850. this.dirNode = dirNode;
  12851. }
  12852. setup() {
  12853. const dir = this.dirNode;
  12854. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12855. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12856. return vec2( u, v );
  12857. }
  12858. }
  12859. /**
  12860. * TSL function for creating an equirect uv node.
  12861. *
  12862. * @tsl
  12863. * @function
  12864. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12865. * @returns {EquirectUVNode}
  12866. */
  12867. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12868. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12869. /**
  12870. * This class represents a cube render target. It is a special version
  12871. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12872. *
  12873. * @augments WebGLCubeRenderTarget
  12874. */
  12875. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12876. constructor( size = 1, options = {} ) {
  12877. super( size, options );
  12878. this.isCubeRenderTarget = true;
  12879. }
  12880. /**
  12881. * Converts the given equirectangular texture to a cube map.
  12882. *
  12883. * @param {Renderer} renderer - The renderer.
  12884. * @param {Texture} texture - The equirectangular texture.
  12885. * @return {CubeRenderTarget} A reference to this cube render target.
  12886. */
  12887. fromEquirectangularTexture( renderer, texture$1 ) {
  12888. const currentMinFilter = texture$1.minFilter;
  12889. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12890. texture$1.generateMipmaps = true;
  12891. this.texture.type = texture$1.type;
  12892. this.texture.colorSpace = texture$1.colorSpace;
  12893. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12894. this.texture.minFilter = texture$1.minFilter;
  12895. this.texture.magFilter = texture$1.magFilter;
  12896. const geometry = new BoxGeometry( 5, 5, 5 );
  12897. const uvNode = equirectUV( positionWorldDirection );
  12898. const material = new NodeMaterial();
  12899. material.colorNode = texture( texture$1, uvNode, 0 );
  12900. material.side = BackSide;
  12901. material.blending = NoBlending;
  12902. const mesh = new Mesh( geometry, material );
  12903. const scene = new Scene();
  12904. scene.add( mesh );
  12905. // Avoid blurred poles
  12906. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12907. const camera = new CubeCamera( 1, 10, this );
  12908. const currentMRT = renderer.getMRT();
  12909. renderer.setMRT( null );
  12910. camera.update( renderer, scene );
  12911. renderer.setMRT( currentMRT );
  12912. texture$1.minFilter = currentMinFilter;
  12913. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12914. mesh.geometry.dispose();
  12915. mesh.material.dispose();
  12916. return this;
  12917. }
  12918. }
  12919. const _cache$1 = new WeakMap();
  12920. /**
  12921. * This node can be used to automatically convert environment maps in the
  12922. * equirectangular format into the cube map format.
  12923. *
  12924. * @augments TempNode
  12925. */
  12926. class CubeMapNode extends TempNode {
  12927. static get type() {
  12928. return 'CubeMapNode';
  12929. }
  12930. /**
  12931. * Constructs a new cube map node.
  12932. *
  12933. * @param {Node} envNode - The node representing the environment map.
  12934. */
  12935. constructor( envNode ) {
  12936. super( 'vec3' );
  12937. /**
  12938. * The node representing the environment map.
  12939. *
  12940. * @type {Node}
  12941. */
  12942. this.envNode = envNode;
  12943. /**
  12944. * A reference to the internal cube texture.
  12945. *
  12946. * @private
  12947. * @type {CubeTexture}
  12948. * @default null
  12949. */
  12950. this._cubeTexture = null;
  12951. /**
  12952. * A reference to the internal cube texture node.
  12953. *
  12954. * @private
  12955. * @type {CubeTextureNode}
  12956. */
  12957. this._cubeTextureNode = cubeTexture();
  12958. const defaultTexture = new CubeTexture();
  12959. defaultTexture.isRenderTargetTexture = true;
  12960. /**
  12961. * A default cube texture that acts as a placeholder.
  12962. * It is used when the conversion from equirectangular to cube
  12963. * map has not finished yet for a given texture.
  12964. *
  12965. * @private
  12966. * @type {CubeTexture}
  12967. */
  12968. this._defaultTexture = defaultTexture;
  12969. /**
  12970. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12971. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12972. *
  12973. * @type {string}
  12974. * @default 'render'
  12975. */
  12976. this.updateBeforeType = NodeUpdateType.RENDER;
  12977. }
  12978. updateBefore( frame ) {
  12979. const { renderer, material } = frame;
  12980. const envNode = this.envNode;
  12981. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12982. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12983. if ( texture && texture.isTexture ) {
  12984. const mapping = texture.mapping;
  12985. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12986. // check for converted cubemap map
  12987. if ( _cache$1.has( texture ) ) {
  12988. const cubeMap = _cache$1.get( texture );
  12989. mapTextureMapping( cubeMap, texture.mapping );
  12990. this._cubeTexture = cubeMap;
  12991. } else {
  12992. // create cube map from equirectangular map
  12993. const image = texture.image;
  12994. if ( isEquirectangularMapReady$1( image ) ) {
  12995. const renderTarget = new CubeRenderTarget( image.height );
  12996. renderTarget.fromEquirectangularTexture( renderer, texture );
  12997. mapTextureMapping( renderTarget.texture, texture.mapping );
  12998. this._cubeTexture = renderTarget.texture;
  12999. _cache$1.set( texture, renderTarget.texture );
  13000. texture.addEventListener( 'dispose', onTextureDispose );
  13001. } else {
  13002. // default cube texture as fallback when equirectangular texture is not yet loaded
  13003. this._cubeTexture = this._defaultTexture;
  13004. }
  13005. }
  13006. //
  13007. this._cubeTextureNode.value = this._cubeTexture;
  13008. } else {
  13009. // envNode already refers to a cube map
  13010. this._cubeTextureNode = this.envNode;
  13011. }
  13012. }
  13013. }
  13014. }
  13015. setup( builder ) {
  13016. this.updateBefore( builder );
  13017. return this._cubeTextureNode;
  13018. }
  13019. }
  13020. /**
  13021. * Returns true if the given equirectangular image has been fully loaded
  13022. * and is ready for further processing.
  13023. *
  13024. * @private
  13025. * @param {Image} image - The equirectangular image to check.
  13026. * @return {boolean} Whether the image is ready or not.
  13027. */
  13028. function isEquirectangularMapReady$1( image ) {
  13029. if ( image === null || image === undefined ) return false;
  13030. return image.height > 0;
  13031. }
  13032. /**
  13033. * This function is executed when `dispose()` is called on the equirectangular
  13034. * texture. In this case, the generated cube map with its render target
  13035. * is deleted as well.
  13036. *
  13037. * @private
  13038. * @param {Object} event - The event object.
  13039. */
  13040. function onTextureDispose( event ) {
  13041. const texture = event.target;
  13042. texture.removeEventListener( 'dispose', onTextureDispose );
  13043. const renderTarget = _cache$1.get( texture );
  13044. if ( renderTarget !== undefined ) {
  13045. _cache$1.delete( texture );
  13046. renderTarget.dispose();
  13047. }
  13048. }
  13049. /**
  13050. * This function makes sure the generated cube map uses the correct
  13051. * texture mapping that corresponds to the equirectangular original.
  13052. *
  13053. * @private
  13054. * @param {Texture} texture - The cube texture.
  13055. * @param {number} mapping - The original texture mapping.
  13056. */
  13057. function mapTextureMapping( texture, mapping ) {
  13058. if ( mapping === EquirectangularReflectionMapping ) {
  13059. texture.mapping = CubeReflectionMapping;
  13060. } else if ( mapping === EquirectangularRefractionMapping ) {
  13061. texture.mapping = CubeRefractionMapping;
  13062. }
  13063. }
  13064. /**
  13065. * TSL function for creating a cube map node.
  13066. *
  13067. * @tsl
  13068. * @function
  13069. * @param {Node} envNode - The node representing the environment map.
  13070. * @returns {CubeMapNode}
  13071. */
  13072. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  13073. /**
  13074. * Represents a basic model for Image-based lighting (IBL). The environment
  13075. * is defined via environment maps in the equirectangular or cube map format.
  13076. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  13077. * or {@link MeshPhongNodeMaterial}.
  13078. *
  13079. * @augments LightingNode
  13080. */
  13081. class BasicEnvironmentNode extends LightingNode {
  13082. static get type() {
  13083. return 'BasicEnvironmentNode';
  13084. }
  13085. /**
  13086. * Constructs a new basic environment node.
  13087. *
  13088. * @param {Node} [envNode=null] - A node representing the environment.
  13089. */
  13090. constructor( envNode = null ) {
  13091. super();
  13092. /**
  13093. * A node representing the environment.
  13094. *
  13095. * @type {Node}
  13096. * @default null
  13097. */
  13098. this.envNode = envNode;
  13099. }
  13100. setup( builder ) {
  13101. // environment property is used in the finish() method of BasicLightingModel
  13102. builder.context.environment = cubeMapNode( this.envNode );
  13103. }
  13104. }
  13105. /**
  13106. * A specific version of {@link IrradianceNode} that is only relevant
  13107. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  13108. * requires a special scaling factor for the light map.
  13109. *
  13110. * @augments LightingNode
  13111. */
  13112. class BasicLightMapNode extends LightingNode {
  13113. static get type() {
  13114. return 'BasicLightMapNode';
  13115. }
  13116. /**
  13117. * Constructs a new basic light map node.
  13118. *
  13119. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  13120. */
  13121. constructor( lightMapNode = null ) {
  13122. super();
  13123. /**
  13124. * The light map node.
  13125. *
  13126. * @type {?Node<vec3>}
  13127. */
  13128. this.lightMapNode = lightMapNode;
  13129. }
  13130. setup( builder ) {
  13131. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  13132. const RECIPROCAL_PI = float( 1 / Math.PI );
  13133. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  13134. }
  13135. }
  13136. /**
  13137. * Abstract class for implementing lighting models. The module defines
  13138. * multiple methods that concrete lighting models can implement. These
  13139. * methods are executed at different points during the light evaluation
  13140. * process.
  13141. */
  13142. class LightingModel {
  13143. /**
  13144. * This method is intended for setting up lighting model and context data
  13145. * which are later used in the evaluation process.
  13146. *
  13147. * @abstract
  13148. * @param {ContextNode} input - The current node context.
  13149. * @param {StackNode} stack - The current stack.
  13150. * @param {NodeBuilder} builder - The current node builder.
  13151. */
  13152. start( /*input, stack, builder*/ ) { }
  13153. /**
  13154. * This method is intended for executing final tasks like final updates
  13155. * to the outgoing light.
  13156. *
  13157. * @abstract
  13158. * @param {ContextNode} input - The current node context.
  13159. * @param {StackNode} stack - The current stack.
  13160. * @param {NodeBuilder} builder - The current node builder.
  13161. */
  13162. finish( /*input, stack, builder*/ ) { }
  13163. /**
  13164. * This method is intended for implementing the direct light term and
  13165. * executed during the build process of directional, point and spot light nodes.
  13166. *
  13167. * @abstract
  13168. * @param {Object} input - The input data.
  13169. * @param {StackNode} stack - The current stack.
  13170. * @param {NodeBuilder} builder - The current node builder.
  13171. */
  13172. direct( /*input, stack, builder*/ ) { }
  13173. /**
  13174. * This method is intended for implementing the direct light term for
  13175. * rect area light nodes.
  13176. *
  13177. * @abstract
  13178. * @param {Object} input - The input data.
  13179. * @param {StackNode} stack - The current stack.
  13180. * @param {NodeBuilder} builder - The current node builder.
  13181. */
  13182. directRectArea( /*input, stack, builder*/ ) {}
  13183. /**
  13184. * This method is intended for implementing the indirect light term.
  13185. *
  13186. * @abstract
  13187. * @param {ContextNode} input - The current node context.
  13188. * @param {StackNode} stack - The current stack.
  13189. * @param {NodeBuilder} builder - The current node builder.
  13190. */
  13191. indirect( /*input, stack, builder*/ ) { }
  13192. /**
  13193. * This method is intended for implementing the ambient occlusion term.
  13194. * Unlike other methods, this method must be called manually by the lighting
  13195. * model in its indirect term.
  13196. *
  13197. * @abstract
  13198. * @param {ContextNode} input - The current node context.
  13199. * @param {StackNode} stack - The current stack.
  13200. * @param {NodeBuilder} builder - The current node builder.
  13201. */
  13202. ambientOcclusion( /*input, stack, builder*/ ) { }
  13203. }
  13204. /**
  13205. * Represents the lighting model for unlit materials. The only light contribution
  13206. * is baked indirect lighting modulated with ambient occlusion and the material's
  13207. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  13208. *
  13209. * @augments LightingModel
  13210. */
  13211. class BasicLightingModel extends LightingModel {
  13212. /**
  13213. * Constructs a new basic lighting model.
  13214. */
  13215. constructor() {
  13216. super();
  13217. }
  13218. /**
  13219. * Implements the baked indirect lighting with its modulation.
  13220. *
  13221. * @param {ContextNode} context - The current node context.
  13222. * @param {StackNode} stack - The current stack.
  13223. * @param {NodeBuilder} builder - The current node builder.
  13224. */
  13225. indirect( context, stack, builder ) {
  13226. const ambientOcclusion = context.ambientOcclusion;
  13227. const reflectedLight = context.reflectedLight;
  13228. const irradianceLightMap = builder.context.irradianceLightMap;
  13229. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  13230. // accumulation (baked indirect lighting only)
  13231. if ( irradianceLightMap ) {
  13232. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  13233. } else {
  13234. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  13235. }
  13236. // modulation
  13237. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13238. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  13239. }
  13240. /**
  13241. * Implements the environment mapping.
  13242. *
  13243. * @param {ContextNode} context - The current node context.
  13244. * @param {StackNode} stack - The current stack.
  13245. * @param {NodeBuilder} builder - The current node builder.
  13246. */
  13247. finish( context, stack, builder ) {
  13248. const material = builder.material;
  13249. const outgoingLight = context.outgoingLight;
  13250. const envNode = builder.context.environment;
  13251. if ( envNode ) {
  13252. switch ( material.combine ) {
  13253. case MultiplyOperation:
  13254. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  13255. break;
  13256. case MixOperation:
  13257. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  13258. break;
  13259. case AddOperation:
  13260. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  13261. break;
  13262. default:
  13263. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  13264. break;
  13265. }
  13266. }
  13267. }
  13268. }
  13269. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  13270. /**
  13271. * Node material version of `MeshBasicMaterial`.
  13272. *
  13273. * @augments NodeMaterial
  13274. */
  13275. class MeshBasicNodeMaterial extends NodeMaterial {
  13276. static get type() {
  13277. return 'MeshBasicNodeMaterial';
  13278. }
  13279. /**
  13280. * Constructs a new mesh basic node material.
  13281. *
  13282. * @param {?Object} parameters - The configuration parameter.
  13283. */
  13284. constructor( parameters ) {
  13285. super();
  13286. /**
  13287. * This flag can be used for type testing.
  13288. *
  13289. * @type {boolean}
  13290. * @readonly
  13291. * @default true
  13292. */
  13293. this.isMeshBasicNodeMaterial = true;
  13294. /**
  13295. * Although the basic material is by definition unlit, we set
  13296. * this property to `true` since we use a lighting model to compute
  13297. * the outgoing light of the fragment shader.
  13298. *
  13299. * @type {boolean}
  13300. * @default true
  13301. */
  13302. this.lights = true;
  13303. this.setDefaultValues( _defaultValues$9 );
  13304. this.setValues( parameters );
  13305. }
  13306. /**
  13307. * Basic materials are not affected by normal and bump maps so we
  13308. * return by default {@link normalView}.
  13309. *
  13310. * @return {Node<vec3>} The normal node.
  13311. */
  13312. setupNormal() {
  13313. return normalView; // see #28839
  13314. }
  13315. /**
  13316. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13317. * to implement the default environment mapping.
  13318. *
  13319. * @param {NodeBuilder} builder - The current node builder.
  13320. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13321. */
  13322. setupEnvironment( builder ) {
  13323. const envNode = super.setupEnvironment( builder );
  13324. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13325. }
  13326. /**
  13327. * This method must be overwritten since light maps are evaluated
  13328. * with a special scaling factor for basic materials.
  13329. *
  13330. * @param {NodeBuilder} builder - The current node builder.
  13331. * @return {?BasicLightMapNode<vec3>} The light map node.
  13332. */
  13333. setupLightMap( builder ) {
  13334. let node = null;
  13335. if ( builder.material.lightMap ) {
  13336. node = new BasicLightMapNode( materialLightMap );
  13337. }
  13338. return node;
  13339. }
  13340. /**
  13341. * The material overwrites this method because `lights` is set to `true` but
  13342. * we still want to return the diffuse color as the outgoing light.
  13343. *
  13344. * @return {Node<vec3>} The outgoing light node.
  13345. */
  13346. setupOutgoingLight() {
  13347. return diffuseColor.rgb;
  13348. }
  13349. /**
  13350. * Setups the lighting model.
  13351. *
  13352. * @return {BasicLightingModel} The lighting model.
  13353. */
  13354. setupLightingModel() {
  13355. return new BasicLightingModel();
  13356. }
  13357. }
  13358. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13359. // Original approximation by Christophe Schlick '94
  13360. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13361. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13362. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13363. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13364. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13365. } ); // validated
  13366. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13367. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13368. } ); // validated
  13369. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13370. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13371. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13372. } );
  13373. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13374. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13375. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13376. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13377. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13378. const G = G_BlinnPhong_Implicit();
  13379. const D = D_BlinnPhong( { dotNH } );
  13380. return F.mul( G ).mul( D );
  13381. } );
  13382. /**
  13383. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13384. *
  13385. * @augments BasicLightingModel
  13386. */
  13387. class PhongLightingModel extends BasicLightingModel {
  13388. /**
  13389. * Constructs a new phong lighting model.
  13390. *
  13391. * @param {boolean} [specular=true] - Whether specular is supported or not.
  13392. */
  13393. constructor( specular = true ) {
  13394. super();
  13395. /**
  13396. * Whether specular is supported or not. Set this to `false` if you are
  13397. * looking for a Lambert-like material meaning a material for non-shiny
  13398. * surfaces, without specular highlights.
  13399. *
  13400. * @type {boolean}
  13401. * @default true
  13402. */
  13403. this.specular = specular;
  13404. }
  13405. /**
  13406. * Implements the direct lighting. The specular portion is optional an can be controlled
  13407. * with the {@link PhongLightingModel#specular} flag.
  13408. *
  13409. * @param {Object} input - The input data.
  13410. * @param {StackNode} stack - The current stack.
  13411. * @param {NodeBuilder} builder - The current node builder.
  13412. */
  13413. direct( { lightDirection, lightColor, reflectedLight } ) {
  13414. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13415. const irradiance = dotNL.mul( lightColor );
  13416. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13417. if ( this.specular === true ) {
  13418. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13419. }
  13420. }
  13421. /**
  13422. * Implements the indirect lighting.
  13423. *
  13424. * @param {ContextNode} input - The current node context.
  13425. * @param {StackNode} stack - The current stack.
  13426. * @param {NodeBuilder} builder - The current node builder.
  13427. */
  13428. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  13429. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13430. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13431. }
  13432. }
  13433. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13434. /**
  13435. * Node material version of `MeshLambertMaterial`.
  13436. *
  13437. * @augments NodeMaterial
  13438. */
  13439. class MeshLambertNodeMaterial extends NodeMaterial {
  13440. static get type() {
  13441. return 'MeshLambertNodeMaterial';
  13442. }
  13443. /**
  13444. * Constructs a new mesh lambert node material.
  13445. *
  13446. * @param {?Object} parameters - The configuration parameter.
  13447. */
  13448. constructor( parameters ) {
  13449. super();
  13450. /**
  13451. * This flag can be used for type testing.
  13452. *
  13453. * @type {boolean}
  13454. * @readonly
  13455. * @default true
  13456. */
  13457. this.isMeshLambertNodeMaterial = true;
  13458. /**
  13459. * Set to `true` because lambert materials react on lights.
  13460. *
  13461. * @type {boolean}
  13462. * @default true
  13463. */
  13464. this.lights = true;
  13465. this.setDefaultValues( _defaultValues$8 );
  13466. this.setValues( parameters );
  13467. }
  13468. /**
  13469. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13470. * to implement the default environment mapping.
  13471. *
  13472. * @param {NodeBuilder} builder - The current node builder.
  13473. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13474. */
  13475. setupEnvironment( builder ) {
  13476. const envNode = super.setupEnvironment( builder );
  13477. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13478. }
  13479. /**
  13480. * Setups the lighting model.
  13481. *
  13482. * @return {PhongLightingModel} The lighting model.
  13483. */
  13484. setupLightingModel( /*builder*/ ) {
  13485. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13486. }
  13487. }
  13488. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13489. /**
  13490. * Node material version of `MeshPhongMaterial`.
  13491. *
  13492. * @augments NodeMaterial
  13493. */
  13494. class MeshPhongNodeMaterial extends NodeMaterial {
  13495. static get type() {
  13496. return 'MeshPhongNodeMaterial';
  13497. }
  13498. /**
  13499. * Constructs a new mesh lambert node material.
  13500. *
  13501. * @param {?Object} parameters - The configuration parameter.
  13502. */
  13503. constructor( parameters ) {
  13504. super();
  13505. /**
  13506. * This flag can be used for type testing.
  13507. *
  13508. * @type {boolean}
  13509. * @readonly
  13510. * @default true
  13511. */
  13512. this.isMeshPhongNodeMaterial = true;
  13513. /**
  13514. * Set to `true` because phong materials react on lights.
  13515. *
  13516. * @type {boolean}
  13517. * @default true
  13518. */
  13519. this.lights = true;
  13520. /**
  13521. * The shininess of phong materials is by default inferred from the `shininess`
  13522. * property. This node property allows to overwrite the default
  13523. * and define the shininess with a node instead.
  13524. *
  13525. * If you don't want to overwrite the shininess but modify the existing
  13526. * value instead, use {@link materialShininess}.
  13527. *
  13528. * @type {?Node<float>}
  13529. * @default null
  13530. */
  13531. this.shininessNode = null;
  13532. /**
  13533. * The specular color of phong materials is by default inferred from the
  13534. * `specular` property. This node property allows to overwrite the default
  13535. * and define the specular color with a node instead.
  13536. *
  13537. * If you don't want to overwrite the specular color but modify the existing
  13538. * value instead, use {@link materialSpecular}.
  13539. *
  13540. * @type {?Node<vec3>}
  13541. * @default null
  13542. */
  13543. this.specularNode = null;
  13544. this.setDefaultValues( _defaultValues$7 );
  13545. this.setValues( parameters );
  13546. }
  13547. /**
  13548. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13549. * to implement the default environment mapping.
  13550. *
  13551. * @param {NodeBuilder} builder - The current node builder.
  13552. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13553. */
  13554. setupEnvironment( builder ) {
  13555. const envNode = super.setupEnvironment( builder );
  13556. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13557. }
  13558. /**
  13559. * Setups the lighting model.
  13560. *
  13561. * @return {PhongLightingModel} The lighting model.
  13562. */
  13563. setupLightingModel( /*builder*/ ) {
  13564. return new PhongLightingModel();
  13565. }
  13566. /**
  13567. * Setups the phong specific node variables.
  13568. *
  13569. * @param {NodeBuilder} builder - The current node builder.
  13570. */
  13571. setupVariants( /*builder*/ ) {
  13572. // SHININESS
  13573. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13574. shininess.assign( shininessNode );
  13575. // SPECULAR COLOR
  13576. const specularNode = this.specularNode || materialSpecular;
  13577. specularColor.assign( specularNode );
  13578. }
  13579. copy( source ) {
  13580. this.shininessNode = source.shininessNode;
  13581. this.specularNode = source.specularNode;
  13582. return super.copy( source );
  13583. }
  13584. }
  13585. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13586. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13587. return float( 0 );
  13588. }
  13589. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13590. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13591. return geometryRoughness;
  13592. } );
  13593. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13594. const { roughness } = inputs;
  13595. const geometryRoughness = getGeometryRoughness();
  13596. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13597. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13598. roughnessFactor = roughnessFactor.min( 1.0 );
  13599. return roughnessFactor;
  13600. } );
  13601. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13602. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13603. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13604. const a2 = alpha.pow2();
  13605. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13606. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13607. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13608. } ).setLayout( {
  13609. name: 'V_GGX_SmithCorrelated',
  13610. type: 'float',
  13611. inputs: [
  13612. { name: 'alpha', type: 'float' },
  13613. { name: 'dotNL', type: 'float' },
  13614. { name: 'dotNV', type: 'float' }
  13615. ]
  13616. } ); // validated
  13617. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13618. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13619. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13620. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13621. const v = div( 0.5, gv.add( gl ) );
  13622. return v.saturate();
  13623. } ).setLayout( {
  13624. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13625. type: 'float',
  13626. inputs: [
  13627. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13628. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13629. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13630. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13631. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13632. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13633. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13634. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13635. ]
  13636. } );
  13637. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13638. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13639. // alpha is "roughness squared" in Disney’s reparameterization
  13640. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13641. const a2 = alpha.pow2();
  13642. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13643. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13644. } ).setLayout( {
  13645. name: 'D_GGX',
  13646. type: 'float',
  13647. inputs: [
  13648. { name: 'alpha', type: 'float' },
  13649. { name: 'dotNH', type: 'float' }
  13650. ]
  13651. } ); // validated
  13652. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13653. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13654. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13655. const a2 = alphaT.mul( alphaB );
  13656. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13657. const v2 = v.dot( v );
  13658. const w2 = a2.div( v2 );
  13659. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13660. } ).setLayout( {
  13661. name: 'D_GGX_Anisotropic',
  13662. type: 'float',
  13663. inputs: [
  13664. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13665. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13666. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13667. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13668. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13669. ]
  13670. } );
  13671. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13672. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13673. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13674. const normalView = inputs.normalView || transformedNormalView;
  13675. const alpha = roughness.pow2(); // UE4's roughness
  13676. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13677. const dotNL = normalView.dot( lightDirection ).clamp();
  13678. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13679. const dotNH = normalView.dot( halfDir ).clamp();
  13680. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13681. let F = F_Schlick( { f0, f90, dotVH } );
  13682. let V, D;
  13683. if ( defined( USE_IRIDESCENCE ) ) {
  13684. F = iridescence.mix( F, f );
  13685. }
  13686. if ( defined( USE_ANISOTROPY ) ) {
  13687. const dotTL = anisotropyT.dot( lightDirection );
  13688. const dotTV = anisotropyT.dot( positionViewDirection );
  13689. const dotTH = anisotropyT.dot( halfDir );
  13690. const dotBL = anisotropyB.dot( lightDirection );
  13691. const dotBV = anisotropyB.dot( positionViewDirection );
  13692. const dotBH = anisotropyB.dot( halfDir );
  13693. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13694. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13695. } else {
  13696. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13697. D = D_GGX( { alpha, dotNH } );
  13698. }
  13699. return F.mul( V ).mul( D );
  13700. } ); // validated
  13701. // Analytical approximation of the DFG LUT, one half of the
  13702. // split-sum approximation used in indirect specular lighting.
  13703. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13704. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13705. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13706. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13707. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13708. const r = roughness.mul( c0 ).add( c1 );
  13709. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13710. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13711. return fab;
  13712. } ).setLayout( {
  13713. name: 'DFGApprox',
  13714. type: 'vec2',
  13715. inputs: [
  13716. { name: 'roughness', type: 'float' },
  13717. { name: 'dotNV', type: 'vec3' }
  13718. ]
  13719. } );
  13720. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13721. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13722. const fab = DFGApprox( { dotNV, roughness } );
  13723. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13724. } );
  13725. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13726. const x = dotVH.oneMinus().saturate();
  13727. const x2 = x.mul( x );
  13728. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13729. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13730. } ).setLayout( {
  13731. name: 'Schlick_to_F0',
  13732. type: 'vec3',
  13733. inputs: [
  13734. { name: 'f', type: 'vec3' },
  13735. { name: 'f90', type: 'float' },
  13736. { name: 'dotVH', type: 'float' }
  13737. ]
  13738. } );
  13739. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13740. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13741. const alpha = roughness.pow2();
  13742. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13743. const invAlpha = float( 1.0 ).div( alpha );
  13744. const cos2h = dotNH.pow2();
  13745. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13746. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13747. } ).setLayout( {
  13748. name: 'D_Charlie',
  13749. type: 'float',
  13750. inputs: [
  13751. { name: 'roughness', type: 'float' },
  13752. { name: 'dotNH', type: 'float' }
  13753. ]
  13754. } );
  13755. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13756. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13757. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13758. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13759. } ).setLayout( {
  13760. name: 'V_Neubelt',
  13761. type: 'float',
  13762. inputs: [
  13763. { name: 'dotNV', type: 'float' },
  13764. { name: 'dotNL', type: 'float' }
  13765. ]
  13766. } );
  13767. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13768. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13769. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13770. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13771. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13772. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13773. const V = V_Neubelt( { dotNV, dotNL } );
  13774. return sheen.mul( D ).mul( V );
  13775. } );
  13776. // Rect Area Light
  13777. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13778. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13779. // code: https://github.com/selfshadow/ltc_code/
  13780. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13781. const LUT_SIZE = 64.0;
  13782. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13783. const LUT_BIAS = 0.5 / LUT_SIZE;
  13784. const dotNV = N.dot( V ).saturate();
  13785. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13786. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13787. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13788. return uv;
  13789. } ).setLayout( {
  13790. name: 'LTC_Uv',
  13791. type: 'vec2',
  13792. inputs: [
  13793. { name: 'N', type: 'vec3' },
  13794. { name: 'V', type: 'vec3' },
  13795. { name: 'roughness', type: 'float' }
  13796. ]
  13797. } );
  13798. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13799. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13800. // An approximation of the form factor of a horizon-clipped rectangle.
  13801. const l = f.length();
  13802. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13803. } ).setLayout( {
  13804. name: 'LTC_ClippedSphereFormFactor',
  13805. type: 'float',
  13806. inputs: [
  13807. { name: 'f', type: 'vec3' }
  13808. ]
  13809. } );
  13810. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13811. const x = v1.dot( v2 );
  13812. const y = x.abs().toVar();
  13813. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13814. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13815. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13816. const v = a.div( b );
  13817. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13818. return v1.cross( v2 ).mul( theta_sintheta );
  13819. } ).setLayout( {
  13820. name: 'LTC_EdgeVectorFormFactor',
  13821. type: 'vec3',
  13822. inputs: [
  13823. { name: 'v1', type: 'vec3' },
  13824. { name: 'v2', type: 'vec3' }
  13825. ]
  13826. } );
  13827. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13828. // bail if point is on back side of plane of light
  13829. // assumes ccw winding order of light vertices
  13830. const v1 = p1.sub( p0 ).toVar();
  13831. const v2 = p3.sub( p0 ).toVar();
  13832. const lightNormal = v1.cross( v2 );
  13833. const result = vec3().toVar();
  13834. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13835. // construct orthonormal basis around N
  13836. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13837. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13838. // compute transform
  13839. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13840. // transform rect
  13841. // & project rect onto sphere
  13842. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13843. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13844. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13845. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13846. // calculate vector form factor
  13847. const vectorFormFactor = vec3( 0 ).toVar();
  13848. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13849. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13850. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13851. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13852. // adjust for horizon clipping
  13853. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13854. } );
  13855. return result;
  13856. } ).setLayout( {
  13857. name: 'LTC_Evaluate',
  13858. type: 'vec3',
  13859. inputs: [
  13860. { name: 'N', type: 'vec3' },
  13861. { name: 'V', type: 'vec3' },
  13862. { name: 'P', type: 'vec3' },
  13863. { name: 'mInv', type: 'mat3' },
  13864. { name: 'p0', type: 'vec3' },
  13865. { name: 'p1', type: 'vec3' },
  13866. { name: 'p2', type: 'vec3' },
  13867. { name: 'p3', type: 'vec3' }
  13868. ]
  13869. } );
  13870. // Mipped Bicubic Texture Filtering by N8
  13871. // https://www.shadertoy.com/view/Dl2SDW
  13872. const bC = 1.0 / 6.0;
  13873. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13874. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13875. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13876. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13877. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13878. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13879. // h0 and h1 are the two offset functions
  13880. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13881. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13882. const bicubic = ( textureNode, texelSize, lod ) => {
  13883. const uv = textureNode.uvNode;
  13884. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13885. const iuv = floor( uvScaled );
  13886. const fuv = fract( uvScaled );
  13887. const g0x = g0( fuv.x );
  13888. const g1x = g1( fuv.x );
  13889. const h0x = h0( fuv.x );
  13890. const h1x = h1( fuv.x );
  13891. const h0y = h0( fuv.y );
  13892. const h1y = h1( fuv.y );
  13893. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13894. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13895. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13896. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13897. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13898. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13899. return a.add( b );
  13900. };
  13901. /**
  13902. * Applies mipped bicubic texture filtering to the given texture node.
  13903. *
  13904. * @tsl
  13905. * @function
  13906. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13907. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13908. * @return {Node} The filtered texture sample.
  13909. */
  13910. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13911. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13912. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13913. const fLodSizeInv = div( 1.0, fLodSize );
  13914. const cLodSizeInv = div( 1.0, cLodSize );
  13915. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13916. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13917. return fract( lodNode ).mix( fSample, cSample );
  13918. } );
  13919. //
  13920. // Transmission
  13921. //
  13922. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13923. // Direction of refracted light.
  13924. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13925. // Compute rotation-independent scaling of the model matrix.
  13926. const modelScale = vec3(
  13927. length( modelMatrix[ 0 ].xyz ),
  13928. length( modelMatrix[ 1 ].xyz ),
  13929. length( modelMatrix[ 2 ].xyz )
  13930. );
  13931. // The thickness is specified in local space.
  13932. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13933. } ).setLayout( {
  13934. name: 'getVolumeTransmissionRay',
  13935. type: 'vec3',
  13936. inputs: [
  13937. { name: 'n', type: 'vec3' },
  13938. { name: 'v', type: 'vec3' },
  13939. { name: 'thickness', type: 'float' },
  13940. { name: 'ior', type: 'float' },
  13941. { name: 'modelMatrix', type: 'mat4' }
  13942. ]
  13943. } );
  13944. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13945. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13946. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13947. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13948. } ).setLayout( {
  13949. name: 'applyIorToRoughness',
  13950. type: 'float',
  13951. inputs: [
  13952. { name: 'roughness', type: 'float' },
  13953. { name: 'ior', type: 'float' }
  13954. ]
  13955. } );
  13956. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13957. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13958. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13959. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13960. const transmissionSample = vTexture.sample( fragCoord );
  13961. //const transmissionSample = viewportMipTexture( fragCoord );
  13962. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13963. return textureBicubic( transmissionSample, lod );
  13964. } );
  13965. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13966. If( attenuationDistance.notEqual( 0 ), () => {
  13967. // Compute light attenuation using Beer's law.
  13968. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13969. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13970. return transmittance;
  13971. } );
  13972. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13973. return vec3( 1.0 );
  13974. } ).setLayout( {
  13975. name: 'volumeAttenuation',
  13976. type: 'vec3',
  13977. inputs: [
  13978. { name: 'transmissionDistance', type: 'float' },
  13979. { name: 'attenuationColor', type: 'vec3' },
  13980. { name: 'attenuationDistance', type: 'float' }
  13981. ]
  13982. } );
  13983. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13984. let transmittedLight, transmittance;
  13985. if ( dispersion ) {
  13986. transmittedLight = vec4().toVar();
  13987. transmittance = vec3().toVar();
  13988. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13989. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13990. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13991. const ior = iors.element( i );
  13992. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13993. const refractedRayExit = position.add( transmissionRay );
  13994. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13995. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13996. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13997. refractionCoords.addAssign( 1.0 );
  13998. refractionCoords.divAssign( 2.0 );
  13999. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14000. // Sample framebuffer to get pixel the refracted ray hits.
  14001. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  14002. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  14003. transmittedLight.a.addAssign( transmissionSample.a );
  14004. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  14005. } );
  14006. transmittedLight.a.divAssign( 3.0 );
  14007. } else {
  14008. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14009. const refractedRayExit = position.add( transmissionRay );
  14010. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14011. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14012. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14013. refractionCoords.addAssign( 1.0 );
  14014. refractionCoords.divAssign( 2.0 );
  14015. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14016. // Sample framebuffer to get pixel the refracted ray hits.
  14017. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  14018. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  14019. }
  14020. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  14021. const dotNV = n.dot( v ).clamp();
  14022. // Get the specular component.
  14023. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  14024. dotNV,
  14025. specularColor,
  14026. specularF90,
  14027. roughness
  14028. } ) );
  14029. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  14030. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  14031. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  14032. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  14033. } );
  14034. //
  14035. // Iridescence
  14036. //
  14037. // XYZ to linear-sRGB color space
  14038. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  14039. 3.2404542, -0.969266, 0.0556434,
  14040. -1.5371385, 1.8760108, -0.2040259,
  14041. -0.4985314, 0.0415560, 1.0572252
  14042. );
  14043. // Assume air interface for top
  14044. // Note: We don't handle the case fresnel0 == 1
  14045. const Fresnel0ToIor = ( fresnel0 ) => {
  14046. const sqrtF0 = fresnel0.sqrt();
  14047. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  14048. };
  14049. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  14050. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  14051. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  14052. };
  14053. // Fresnel equations for dielectric/dielectric interfaces.
  14054. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  14055. // Evaluation XYZ sensitivity curves in Fourier space
  14056. const evalSensitivity = ( OPD, shift ) => {
  14057. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  14058. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  14059. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  14060. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  14061. 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() );
  14062. 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() );
  14063. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  14064. const rgb = XYZ_TO_REC709.mul( xyz );
  14065. return rgb;
  14066. };
  14067. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  14068. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  14069. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  14070. // Evaluate the cosTheta on the base layer (Snell law)
  14071. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  14072. // Handle TIR:
  14073. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  14074. If( cosTheta2Sq.lessThan( 0 ), () => {
  14075. return vec3( 1.0 );
  14076. } );
  14077. const cosTheta2 = cosTheta2Sq.sqrt();
  14078. // First interface
  14079. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  14080. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  14081. //const R21 = R12;
  14082. const T121 = R12.oneMinus();
  14083. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  14084. const phi21 = float( Math.PI ).sub( phi12 );
  14085. // Second interface
  14086. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  14087. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  14088. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  14089. const phi23 = vec3(
  14090. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14091. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14092. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  14093. );
  14094. // Phase shift
  14095. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  14096. const phi = vec3( phi21 ).add( phi23 );
  14097. // Compound terms
  14098. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  14099. const r123 = R123.sqrt();
  14100. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  14101. // Reflectance term for m = 0 (DC term amplitude)
  14102. const C0 = R12.add( Rs );
  14103. const I = C0.toVar();
  14104. // Reflectance term for m > 0 (pairs of diracs)
  14105. const Cm = Rs.sub( T121 ).toVar();
  14106. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  14107. Cm.mulAssign( r123 );
  14108. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  14109. I.addAssign( Cm.mul( Sm ) );
  14110. } );
  14111. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  14112. return I.max( vec3( 0.0 ) );
  14113. } ).setLayout( {
  14114. name: 'evalIridescence',
  14115. type: 'vec3',
  14116. inputs: [
  14117. { name: 'outsideIOR', type: 'float' },
  14118. { name: 'eta2', type: 'float' },
  14119. { name: 'cosTheta1', type: 'float' },
  14120. { name: 'thinFilmThickness', type: 'float' },
  14121. { name: 'baseF0', type: 'vec3' }
  14122. ]
  14123. } );
  14124. //
  14125. // Sheen
  14126. //
  14127. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  14128. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  14129. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  14130. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  14131. const dotNV = normal.dot( viewDir ).saturate();
  14132. const r2 = roughness.pow2();
  14133. const a = select(
  14134. roughness.lessThan( 0.25 ),
  14135. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  14136. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  14137. );
  14138. const b = select(
  14139. roughness.lessThan( 0.25 ),
  14140. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  14141. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  14142. );
  14143. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  14144. return DG.mul( 1.0 / Math.PI ).saturate();
  14145. } );
  14146. const clearcoatF0 = vec3( 0.04 );
  14147. const clearcoatF90 = float( 1 );
  14148. /**
  14149. * Represents the lighting model for a PBR material.
  14150. *
  14151. * @augments LightingModel
  14152. */
  14153. class PhysicalLightingModel extends LightingModel {
  14154. /**
  14155. * Constructs a new physical lighting model.
  14156. *
  14157. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  14158. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  14159. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  14160. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  14161. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  14162. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  14163. */
  14164. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  14165. super();
  14166. /**
  14167. * Whether clearcoat is supported or not.
  14168. *
  14169. * @type {boolean}
  14170. * @default false
  14171. */
  14172. this.clearcoat = clearcoat;
  14173. /**
  14174. * Whether sheen is supported or not.
  14175. *
  14176. * @type {boolean}
  14177. * @default false
  14178. */
  14179. this.sheen = sheen;
  14180. /**
  14181. * Whether iridescence is supported or not.
  14182. *
  14183. * @type {boolean}
  14184. * @default false
  14185. */
  14186. this.iridescence = iridescence;
  14187. /**
  14188. * Whether anisotropy is supported or not.
  14189. *
  14190. * @type {boolean}
  14191. * @default false
  14192. */
  14193. this.anisotropy = anisotropy;
  14194. /**
  14195. * Whether transmission is supported or not.
  14196. *
  14197. * @type {boolean}
  14198. * @default false
  14199. */
  14200. this.transmission = transmission;
  14201. /**
  14202. * Whether dispersion is supported or not.
  14203. *
  14204. * @type {boolean}
  14205. * @default false
  14206. */
  14207. this.dispersion = dispersion;
  14208. /**
  14209. * The clear coat radiance.
  14210. *
  14211. * @type {?Node}
  14212. * @default null
  14213. */
  14214. this.clearcoatRadiance = null;
  14215. /**
  14216. * The clear coat specular direct.
  14217. *
  14218. * @type {?Node}
  14219. * @default null
  14220. */
  14221. this.clearcoatSpecularDirect = null;
  14222. /**
  14223. * The clear coat specular indirect.
  14224. *
  14225. * @type {?Node}
  14226. * @default null
  14227. */
  14228. this.clearcoatSpecularIndirect = null;
  14229. /**
  14230. * The sheen specular direct.
  14231. *
  14232. * @type {?Node}
  14233. * @default null
  14234. */
  14235. this.sheenSpecularDirect = null;
  14236. /**
  14237. * The sheen specular indirect.
  14238. *
  14239. * @type {?Node}
  14240. * @default null
  14241. */
  14242. this.sheenSpecularIndirect = null;
  14243. /**
  14244. * The iridescence Fresnel.
  14245. *
  14246. * @type {?Node}
  14247. * @default null
  14248. */
  14249. this.iridescenceFresnel = null;
  14250. /**
  14251. * The iridescence F0.
  14252. *
  14253. * @type {?Node}
  14254. * @default null
  14255. */
  14256. this.iridescenceF0 = null;
  14257. }
  14258. /**
  14259. * Depending on what features are requested, the method prepares certain node variables
  14260. * which are later used for lighting computations.
  14261. *
  14262. * @param {ContextNode} context - The current node context.
  14263. */
  14264. start( context ) {
  14265. if ( this.clearcoat === true ) {
  14266. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  14267. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  14268. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  14269. }
  14270. if ( this.sheen === true ) {
  14271. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  14272. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  14273. }
  14274. if ( this.iridescence === true ) {
  14275. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  14276. this.iridescenceFresnel = evalIridescence( {
  14277. outsideIOR: float( 1.0 ),
  14278. eta2: iridescenceIOR,
  14279. cosTheta1: dotNVi,
  14280. thinFilmThickness: iridescenceThickness,
  14281. baseF0: specularColor
  14282. } );
  14283. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  14284. }
  14285. if ( this.transmission === true ) {
  14286. const position = positionWorld;
  14287. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  14288. const n = transformedNormalWorld;
  14289. context.backdrop = getIBLVolumeRefraction(
  14290. n,
  14291. v,
  14292. roughness,
  14293. diffuseColor,
  14294. specularColor,
  14295. specularF90, // specularF90
  14296. position, // positionWorld
  14297. modelWorldMatrix, // modelMatrix
  14298. cameraViewMatrix, // viewMatrix
  14299. cameraProjectionMatrix, // projMatrix
  14300. ior,
  14301. thickness,
  14302. attenuationColor,
  14303. attenuationDistance,
  14304. this.dispersion ? dispersion : null
  14305. );
  14306. context.backdropAlpha = transmission;
  14307. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  14308. }
  14309. }
  14310. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  14311. // Approximates multi-scattering in order to preserve energy.
  14312. // http://www.jcgt.org/published/0008/01/03/
  14313. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  14314. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14315. const fab = DFGApprox( { roughness, dotNV } );
  14316. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  14317. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14318. const Ess = fab.x.add( fab.y );
  14319. const Ems = Ess.oneMinus();
  14320. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  14321. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14322. singleScatter.addAssign( FssEss );
  14323. multiScatter.addAssign( Fms.mul( Ems ) );
  14324. }
  14325. /**
  14326. * Implements the direct light.
  14327. *
  14328. * @param {Object} input - The input data.
  14329. * @param {StackNode} stack - The current stack.
  14330. * @param {NodeBuilder} builder - The current node builder.
  14331. */
  14332. direct( { lightDirection, lightColor, reflectedLight } ) {
  14333. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14334. const irradiance = dotNL.mul( lightColor );
  14335. if ( this.sheen === true ) {
  14336. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14337. }
  14338. if ( this.clearcoat === true ) {
  14339. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14340. const ccIrradiance = dotNLcc.mul( lightColor );
  14341. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14342. }
  14343. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14344. 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 } ) ) );
  14345. }
  14346. /**
  14347. * This method is intended for implementing the direct light term for
  14348. * rect area light nodes.
  14349. *
  14350. * @param {Object} input - The input data.
  14351. * @param {StackNode} stack - The current stack.
  14352. * @param {NodeBuilder} builder - The current node builder.
  14353. */
  14354. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14355. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14356. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14357. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14358. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14359. const N = transformedNormalView;
  14360. const V = positionViewDirection;
  14361. const P = positionView.toVar();
  14362. const uv = LTC_Uv( { N, V, roughness } );
  14363. const t1 = ltc_1.sample( uv ).toVar();
  14364. const t2 = ltc_2.sample( uv ).toVar();
  14365. const mInv = mat3(
  14366. vec3( t1.x, 0, t1.y ),
  14367. vec3( 0, 1, 0 ),
  14368. vec3( t1.z, 0, t1.w )
  14369. ).toVar();
  14370. // LTC Fresnel Approximation by Stephen Hill
  14371. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14372. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14373. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14374. 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 } ) ) );
  14375. }
  14376. /**
  14377. * Implements the indirect lighting.
  14378. *
  14379. * @param {ContextNode} context - The current node context.
  14380. * @param {StackNode} stack - The current stack.
  14381. * @param {NodeBuilder} builder - The current node builder.
  14382. */
  14383. indirect( context, stack, builder ) {
  14384. this.indirectDiffuse( context, stack, builder );
  14385. this.indirectSpecular( context, stack, builder );
  14386. this.ambientOcclusion( context, stack, builder );
  14387. }
  14388. /**
  14389. * Implements the indirect diffuse term.
  14390. *
  14391. * @param {ContextNode} input - The current node context.
  14392. * @param {StackNode} stack - The current stack.
  14393. * @param {NodeBuilder} builder - The current node builder.
  14394. */
  14395. indirectDiffuse( { irradiance, reflectedLight } ) {
  14396. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14397. }
  14398. /**
  14399. * Implements the indirect specular term.
  14400. *
  14401. * @param {ContextNode} input - The current node context.
  14402. * @param {StackNode} stack - The current stack.
  14403. * @param {NodeBuilder} builder - The current node builder.
  14404. */
  14405. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  14406. if ( this.sheen === true ) {
  14407. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14408. sheen,
  14409. IBLSheenBRDF( {
  14410. normal: transformedNormalView,
  14411. viewDir: positionViewDirection,
  14412. roughness: sheenRoughness
  14413. } )
  14414. ) );
  14415. }
  14416. if ( this.clearcoat === true ) {
  14417. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14418. const clearcoatEnv = EnvironmentBRDF( {
  14419. dotNV: dotNVcc,
  14420. specularColor: clearcoatF0,
  14421. specularF90: clearcoatF90,
  14422. roughness: clearcoatRoughness
  14423. } );
  14424. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14425. }
  14426. // Both indirect specular and indirect diffuse light accumulate here
  14427. const singleScattering = vec3().toVar( 'singleScattering' );
  14428. const multiScattering = vec3().toVar( 'multiScattering' );
  14429. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14430. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14431. const totalScattering = singleScattering.add( multiScattering );
  14432. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14433. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14434. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14435. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14436. }
  14437. /**
  14438. * Implements the ambient occlusion term.
  14439. *
  14440. * @param {ContextNode} input - The current node context.
  14441. * @param {StackNode} stack - The current stack.
  14442. * @param {NodeBuilder} builder - The current node builder.
  14443. */
  14444. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  14445. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14446. const aoNV = dotNV.add( ambientOcclusion );
  14447. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  14448. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14449. if ( this.clearcoat === true ) {
  14450. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14451. }
  14452. if ( this.sheen === true ) {
  14453. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14454. }
  14455. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14456. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14457. }
  14458. /**
  14459. * Used for final lighting accumulations depending on the requested features.
  14460. *
  14461. * @param {ContextNode} context - The current node context.
  14462. * @param {StackNode} stack - The current stack.
  14463. * @param {NodeBuilder} builder - The current node builder.
  14464. */
  14465. finish( context ) {
  14466. const { outgoingLight } = context;
  14467. if ( this.clearcoat === true ) {
  14468. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14469. const Fcc = F_Schlick( {
  14470. dotVH: dotNVcc,
  14471. f0: clearcoatF0,
  14472. f90: clearcoatF90
  14473. } );
  14474. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14475. outgoingLight.assign( clearcoatLight );
  14476. }
  14477. if ( this.sheen === true ) {
  14478. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14479. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14480. outgoingLight.assign( sheenLight );
  14481. }
  14482. }
  14483. }
  14484. // These defines must match with PMREMGenerator
  14485. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14486. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14487. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14488. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14489. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14490. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14491. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14492. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14493. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14494. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14495. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14496. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14497. // These shader functions convert between the UV coordinates of a single face of
  14498. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14499. // sampling a textureCube (not generally normalized ).
  14500. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14501. const absDirection = vec3( abs( direction ) ).toVar();
  14502. const face = float( -1 ).toVar();
  14503. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14504. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14505. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14506. } ).Else( () => {
  14507. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14508. } );
  14509. } ).Else( () => {
  14510. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14511. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14512. } ).Else( () => {
  14513. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14514. } );
  14515. } );
  14516. return face;
  14517. } ).setLayout( {
  14518. name: 'getFace',
  14519. type: 'float',
  14520. inputs: [
  14521. { name: 'direction', type: 'vec3' }
  14522. ]
  14523. } );
  14524. // RH coordinate system; PMREM face-indexing convention
  14525. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14526. const uv = vec2().toVar();
  14527. If( face.equal( 0.0 ), () => {
  14528. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14529. } ).ElseIf( face.equal( 1.0 ), () => {
  14530. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14531. } ).ElseIf( face.equal( 2.0 ), () => {
  14532. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14533. } ).ElseIf( face.equal( 3.0 ), () => {
  14534. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14535. } ).ElseIf( face.equal( 4.0 ), () => {
  14536. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14537. } ).Else( () => {
  14538. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14539. } );
  14540. return mul( 0.5, uv.add( 1.0 ) );
  14541. } ).setLayout( {
  14542. name: 'getUV',
  14543. type: 'vec2',
  14544. inputs: [
  14545. { name: 'direction', type: 'vec3' },
  14546. { name: 'face', type: 'float' }
  14547. ]
  14548. } );
  14549. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14550. const mip = float( 0.0 ).toVar();
  14551. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14552. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14553. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14554. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14555. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14556. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14557. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14558. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14559. } ).Else( () => {
  14560. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14561. } );
  14562. return mip;
  14563. } ).setLayout( {
  14564. name: 'roughnessToMip',
  14565. type: 'float',
  14566. inputs: [
  14567. { name: 'roughness', type: 'float' }
  14568. ]
  14569. } );
  14570. // RH coordinate system; PMREM face-indexing convention
  14571. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14572. const uv = uv_immutable.toVar();
  14573. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14574. const direction = vec3( uv, 1.0 ).toVar();
  14575. If( face.equal( 0.0 ), () => {
  14576. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14577. } ).ElseIf( face.equal( 1.0 ), () => {
  14578. direction.assign( direction.xzy );
  14579. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14580. } ).ElseIf( face.equal( 2.0 ), () => {
  14581. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14582. } ).ElseIf( face.equal( 3.0 ), () => {
  14583. direction.assign( direction.zyx );
  14584. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14585. } ).ElseIf( face.equal( 4.0 ), () => {
  14586. direction.assign( direction.xzy );
  14587. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14588. } ).ElseIf( face.equal( 5.0 ), () => {
  14589. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14590. } );
  14591. return direction;
  14592. } ).setLayout( {
  14593. name: 'getDirection',
  14594. type: 'vec3',
  14595. inputs: [
  14596. { name: 'uv', type: 'vec2' },
  14597. { name: 'face', type: 'float' }
  14598. ]
  14599. } );
  14600. //
  14601. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14602. const roughness = float( roughness_immutable );
  14603. const sampleDir = vec3( sampleDir_immutable );
  14604. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14605. const mipF = fract( mip );
  14606. const mipInt = floor( mip );
  14607. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14608. If( mipF.notEqual( 0.0 ), () => {
  14609. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14610. color0.assign( mix( color0, color1, mipF ) );
  14611. } );
  14612. return color0;
  14613. } );
  14614. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14615. const mipInt = float( mipInt_immutable ).toVar();
  14616. const direction = vec3( direction_immutable );
  14617. const face = float( getFace( direction ) ).toVar();
  14618. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14619. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14620. const faceSize = float( exp2( mipInt ) ).toVar();
  14621. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14622. If( face.greaterThan( 2.0 ), () => {
  14623. uv.y.addAssign( faceSize );
  14624. face.subAssign( 3.0 );
  14625. } );
  14626. uv.x.addAssign( face.mul( faceSize ) );
  14627. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14628. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14629. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14630. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14631. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14632. } );
  14633. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14634. const cosTheta = cos( theta );
  14635. // Rodrigues' axis-angle rotation
  14636. const sampleDirection = outputDirection.mul( cosTheta )
  14637. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14638. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14639. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14640. } );
  14641. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14642. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14643. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14644. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14645. } );
  14646. axis.assign( normalize( axis ) );
  14647. const gl_FragColor = vec3().toVar();
  14648. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14649. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14650. If( i.greaterThanEqual( samples ), () => {
  14651. Break();
  14652. } );
  14653. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14654. 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 } ) ) );
  14655. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14656. } );
  14657. return vec4( gl_FragColor, 1 );
  14658. } );
  14659. let _generator = null;
  14660. const _cache = new WeakMap();
  14661. /**
  14662. * Generates the cubeUV size based on the given image height.
  14663. *
  14664. * @private
  14665. * @param {number} imageHeight - The image height.
  14666. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  14667. */
  14668. function _generateCubeUVSize( imageHeight ) {
  14669. const maxMip = Math.log2( imageHeight ) - 2;
  14670. const texelHeight = 1.0 / imageHeight;
  14671. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14672. return { texelWidth, texelHeight, maxMip };
  14673. }
  14674. /**
  14675. * Generates a PMREM from the given texture .
  14676. *
  14677. * @private
  14678. * @param {Texture} texture - The texture to create the PMREM for.
  14679. * @return {Texture} The PMREM.
  14680. */
  14681. function _getPMREMFromTexture( texture ) {
  14682. let cacheTexture = _cache.get( texture );
  14683. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  14684. if ( pmremVersion !== texture.pmremVersion ) {
  14685. const image = texture.image;
  14686. if ( texture.isCubeTexture ) {
  14687. if ( isCubeMapReady( image ) ) {
  14688. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14689. } else {
  14690. return null;
  14691. }
  14692. } else {
  14693. if ( isEquirectangularMapReady( image ) ) {
  14694. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14695. } else {
  14696. return null;
  14697. }
  14698. }
  14699. cacheTexture.pmremVersion = texture.pmremVersion;
  14700. _cache.set( texture, cacheTexture );
  14701. }
  14702. return cacheTexture.texture;
  14703. }
  14704. /**
  14705. * This node represents a PMREM which is a special type of preprocessed
  14706. * environment map intended for PBR materials.
  14707. *
  14708. * ```js
  14709. * const material = new MeshStandardNodeMaterial();
  14710. * material.envNode = pmremTexture( envMap );
  14711. * ```
  14712. *
  14713. * @augments TempNode
  14714. */
  14715. class PMREMNode extends TempNode {
  14716. static get type() {
  14717. return 'PMREMNode';
  14718. }
  14719. /**
  14720. * Constructs a new function overloading node.
  14721. *
  14722. * @param {Texture} value - The input texture.
  14723. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14724. * @param {Node<float>} [levelNode=null] - The level node.
  14725. */
  14726. constructor( value, uvNode = null, levelNode = null ) {
  14727. super( 'vec3' );
  14728. /**
  14729. * Reference to the input texture.
  14730. *
  14731. * @private
  14732. * @type {Texture}
  14733. */
  14734. this._value = value;
  14735. /**
  14736. * Reference to the generated PMREM.
  14737. *
  14738. * @private
  14739. * @type {Texture | null}
  14740. * @default null
  14741. */
  14742. this._pmrem = null;
  14743. /**
  14744. * The uv node.
  14745. *
  14746. * @type {Node<vec2>}
  14747. */
  14748. this.uvNode = uvNode;
  14749. /**
  14750. * The level node.
  14751. *
  14752. * @type {Node<float>}
  14753. */
  14754. this.levelNode = levelNode;
  14755. /**
  14756. * Reference to a PMREM generator.
  14757. *
  14758. * @private
  14759. * @type {PMREMGenerator}
  14760. * @default null
  14761. */
  14762. this._generator = null;
  14763. const defaultTexture = new Texture();
  14764. defaultTexture.isRenderTargetTexture = true;
  14765. /**
  14766. * The texture node holding the generated PMREM.
  14767. *
  14768. * @private
  14769. * @type {TextureNode}
  14770. */
  14771. this._texture = texture( defaultTexture );
  14772. /**
  14773. * A uniform representing the PMREM's width.
  14774. *
  14775. * @private
  14776. * @type {UniformNode<float>}
  14777. */
  14778. this._width = uniform( 0 );
  14779. /**
  14780. * A uniform representing the PMREM's height.
  14781. *
  14782. * @private
  14783. * @type {UniformNode<float>}
  14784. */
  14785. this._height = uniform( 0 );
  14786. /**
  14787. * A uniform representing the PMREM's max Mip.
  14788. *
  14789. * @private
  14790. * @type {UniformNode<float>}
  14791. */
  14792. this._maxMip = uniform( 0 );
  14793. /**
  14794. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14795. *
  14796. * @type {string}
  14797. * @default 'render'
  14798. */
  14799. this.updateBeforeType = NodeUpdateType.RENDER;
  14800. }
  14801. set value( value ) {
  14802. this._value = value;
  14803. this._pmrem = null;
  14804. }
  14805. /**
  14806. * The node's texture value.
  14807. *
  14808. * @type {Texture}
  14809. */
  14810. get value() {
  14811. return this._value;
  14812. }
  14813. /**
  14814. * Uses the given PMREM texture to update internal values.
  14815. *
  14816. * @param {Texture} texture - The PMREM texture.
  14817. */
  14818. updateFromTexture( texture ) {
  14819. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14820. this._texture.value = texture;
  14821. this._width.value = cubeUVSize.texelWidth;
  14822. this._height.value = cubeUVSize.texelHeight;
  14823. this._maxMip.value = cubeUVSize.maxMip;
  14824. }
  14825. updateBefore() {
  14826. let pmrem = this._pmrem;
  14827. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  14828. const texture = this._value;
  14829. if ( pmremVersion !== texture.pmremVersion ) {
  14830. if ( texture.isPMREMTexture === true ) {
  14831. pmrem = texture;
  14832. } else {
  14833. pmrem = _getPMREMFromTexture( texture );
  14834. }
  14835. if ( pmrem !== null ) {
  14836. this._pmrem = pmrem;
  14837. this.updateFromTexture( pmrem );
  14838. }
  14839. }
  14840. }
  14841. setup( builder ) {
  14842. if ( _generator === null ) {
  14843. _generator = builder.createPMREMGenerator();
  14844. }
  14845. //
  14846. this.updateBefore( builder );
  14847. //
  14848. let uvNode = this.uvNode;
  14849. if ( uvNode === null && builder.context.getUV ) {
  14850. uvNode = builder.context.getUV( this );
  14851. }
  14852. //
  14853. const texture = this.value;
  14854. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14855. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14856. }
  14857. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14858. //
  14859. let levelNode = this.levelNode;
  14860. if ( levelNode === null && builder.context.getTextureLevel ) {
  14861. levelNode = builder.context.getTextureLevel( this );
  14862. }
  14863. //
  14864. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14865. }
  14866. }
  14867. /**
  14868. * Returns `true` if the given cube map image has been fully loaded.
  14869. *
  14870. * @private
  14871. * @param {Array<(Image|Object)>} image - The cube map image.
  14872. * @return {boolean} Whether the given cube map is ready or not.
  14873. */
  14874. function isCubeMapReady( image ) {
  14875. if ( image === null || image === undefined ) return false;
  14876. let count = 0;
  14877. const length = 6;
  14878. for ( let i = 0; i < length; i ++ ) {
  14879. if ( image[ i ] !== undefined ) count ++;
  14880. }
  14881. return count === length;
  14882. }
  14883. /**
  14884. * Returns `true` if the given equirectangular image has been fully loaded.
  14885. *
  14886. * @private
  14887. * @param {(Image|Object)} image - The equirectangular image.
  14888. * @return {boolean} Whether the given cube map is ready or not.
  14889. */
  14890. function isEquirectangularMapReady( image ) {
  14891. if ( image === null || image === undefined ) return false;
  14892. return image.height > 0;
  14893. }
  14894. /**
  14895. * TSL function for creating a PMREM node.
  14896. *
  14897. * @tsl
  14898. * @function
  14899. * @param {Texture} value - The input texture.
  14900. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14901. * @param {Node<float>} [levelNode=null] - The level node.
  14902. * @returns {PMREMNode}
  14903. */
  14904. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14905. const _envNodeCache = new WeakMap();
  14906. /**
  14907. * Represents a physical model for Image-based lighting (IBL). The environment
  14908. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14909. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14910. *
  14911. * @augments LightingNode
  14912. */
  14913. class EnvironmentNode extends LightingNode {
  14914. static get type() {
  14915. return 'EnvironmentNode';
  14916. }
  14917. /**
  14918. * Constructs a new environment node.
  14919. *
  14920. * @param {Node} [envNode=null] - A node representing the environment.
  14921. */
  14922. constructor( envNode = null ) {
  14923. super();
  14924. /**
  14925. * A node representing the environment.
  14926. *
  14927. * @type {?Node}
  14928. * @default null
  14929. */
  14930. this.envNode = envNode;
  14931. }
  14932. setup( builder ) {
  14933. const { material } = builder;
  14934. let envNode = this.envNode;
  14935. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14936. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14937. let cacheEnvNode = _envNodeCache.get( value );
  14938. if ( cacheEnvNode === undefined ) {
  14939. cacheEnvNode = pmremTexture( value );
  14940. _envNodeCache.set( value, cacheEnvNode );
  14941. }
  14942. envNode = cacheEnvNode;
  14943. }
  14944. //
  14945. const envMap = material.envMap;
  14946. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14947. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14948. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14949. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14950. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14951. const isolateRadiance = cache( radiance );
  14952. const isolateIrradiance = cache( irradiance );
  14953. //
  14954. builder.context.radiance.addAssign( isolateRadiance );
  14955. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14956. //
  14957. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14958. if ( clearcoatRadiance ) {
  14959. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14960. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14961. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14962. }
  14963. }
  14964. }
  14965. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14966. let reflectVec = null;
  14967. return {
  14968. getUV: () => {
  14969. if ( reflectVec === null ) {
  14970. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14971. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14972. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14973. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14974. }
  14975. return reflectVec;
  14976. },
  14977. getTextureLevel: () => {
  14978. return roughnessNode;
  14979. }
  14980. };
  14981. };
  14982. const createIrradianceContext = ( normalWorldNode ) => {
  14983. return {
  14984. getUV: () => {
  14985. return normalWorldNode;
  14986. },
  14987. getTextureLevel: () => {
  14988. return float( 1.0 );
  14989. }
  14990. };
  14991. };
  14992. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14993. /**
  14994. * Node material version of `MeshStandardMaterial`.
  14995. *
  14996. * @augments NodeMaterial
  14997. */
  14998. class MeshStandardNodeMaterial extends NodeMaterial {
  14999. static get type() {
  15000. return 'MeshStandardNodeMaterial';
  15001. }
  15002. /**
  15003. * Constructs a new mesh standard node material.
  15004. *
  15005. * @param {?Object} parameters - The configuration parameter.
  15006. */
  15007. constructor( parameters ) {
  15008. super();
  15009. /**
  15010. * This flag can be used for type testing.
  15011. *
  15012. * @type {boolean}
  15013. * @readonly
  15014. * @default true
  15015. */
  15016. this.isMeshStandardNodeMaterial = true;
  15017. /**
  15018. * Set to `true` because standard materials react on lights.
  15019. *
  15020. * @type {boolean}
  15021. * @default true
  15022. */
  15023. this.lights = true;
  15024. /**
  15025. * The emissive color of standard materials is by default inferred from the `emissive`,
  15026. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  15027. * overwrite the default and define the emissive color with a node instead.
  15028. *
  15029. * If you don't want to overwrite the emissive color but modify the existing
  15030. * value instead, use {@link materialEmissive}.
  15031. *
  15032. * @type {?Node<vec3>}
  15033. * @default null
  15034. */
  15035. this.emissiveNode = null;
  15036. /**
  15037. * The metalness of standard materials is by default inferred from the `metalness`,
  15038. * and `metalnessMap` properties. This node property allows to
  15039. * overwrite the default and define the metalness with a node instead.
  15040. *
  15041. * If you don't want to overwrite the metalness but modify the existing
  15042. * value instead, use {@link materialMetalness}.
  15043. *
  15044. * @type {?Node<float>}
  15045. * @default null
  15046. */
  15047. this.metalnessNode = null;
  15048. /**
  15049. * The roughness of standard materials is by default inferred from the `roughness`,
  15050. * and `roughnessMap` properties. This node property allows to
  15051. * overwrite the default and define the roughness with a node instead.
  15052. *
  15053. * If you don't want to overwrite the roughness but modify the existing
  15054. * value instead, use {@link materialRoughness}.
  15055. *
  15056. * @type {?Node<float>}
  15057. * @default null
  15058. */
  15059. this.roughnessNode = null;
  15060. this.setDefaultValues( _defaultValues$6 );
  15061. this.setValues( parameters );
  15062. }
  15063. /**
  15064. * Overwritten since this type of material uses {@link EnvironmentNode}
  15065. * to implement the PBR (PMREM based) environment mapping. Besides, the
  15066. * method honors `Scene.environment`.
  15067. *
  15068. * @param {NodeBuilder} builder - The current node builder.
  15069. * @return {?EnvironmentNode<vec3>} The environment node.
  15070. */
  15071. setupEnvironment( builder ) {
  15072. let envNode = super.setupEnvironment( builder );
  15073. if ( envNode === null && builder.environmentNode ) {
  15074. envNode = builder.environmentNode;
  15075. }
  15076. return envNode ? new EnvironmentNode( envNode ) : null;
  15077. }
  15078. /**
  15079. * Setups the lighting model.
  15080. *
  15081. * @return {PhysicalLightingModel} The lighting model.
  15082. */
  15083. setupLightingModel( /*builder*/ ) {
  15084. return new PhysicalLightingModel();
  15085. }
  15086. /**
  15087. * Setups the specular related node variables.
  15088. */
  15089. setupSpecular() {
  15090. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  15091. specularColor.assign( specularColorNode );
  15092. specularF90.assign( 1.0 );
  15093. }
  15094. /**
  15095. * Setups the standard specific node variables.
  15096. *
  15097. * @param {NodeBuilder} builder - The current node builder.
  15098. */
  15099. setupVariants() {
  15100. // METALNESS
  15101. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  15102. metalness.assign( metalnessNode );
  15103. // ROUGHNESS
  15104. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  15105. roughnessNode = getRoughness( { roughness: roughnessNode } );
  15106. roughness.assign( roughnessNode );
  15107. // SPECULAR COLOR
  15108. this.setupSpecular();
  15109. // DIFFUSE COLOR
  15110. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  15111. }
  15112. copy( source ) {
  15113. this.emissiveNode = source.emissiveNode;
  15114. this.metalnessNode = source.metalnessNode;
  15115. this.roughnessNode = source.roughnessNode;
  15116. return super.copy( source );
  15117. }
  15118. }
  15119. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  15120. /**
  15121. * Node material version of `MeshPhysicalMaterial`.
  15122. *
  15123. * @augments MeshStandardNodeMaterial
  15124. */
  15125. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  15126. static get type() {
  15127. return 'MeshPhysicalNodeMaterial';
  15128. }
  15129. /**
  15130. * Constructs a new mesh physical node material.
  15131. *
  15132. * @param {?Object} parameters - The configuration parameter.
  15133. */
  15134. constructor( parameters ) {
  15135. super();
  15136. /**
  15137. * This flag can be used for type testing.
  15138. *
  15139. * @type {boolean}
  15140. * @readonly
  15141. * @default true
  15142. */
  15143. this.isMeshPhysicalNodeMaterial = true;
  15144. /**
  15145. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  15146. * and `clearcoatMap` properties. This node property allows to overwrite the default
  15147. * and define the clearcoat with a node instead.
  15148. *
  15149. * If you don't want to overwrite the clearcoat but modify the existing
  15150. * value instead, use {@link materialClearcoat}.
  15151. *
  15152. * @type {?Node<float>}
  15153. * @default null
  15154. */
  15155. this.clearcoatNode = null;
  15156. /**
  15157. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  15158. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  15159. * and define the clearcoat roughness with a node instead.
  15160. *
  15161. * If you don't want to overwrite the clearcoat roughness but modify the existing
  15162. * value instead, use {@link materialClearcoatRoughness}.
  15163. *
  15164. * @type {?Node<float>}
  15165. * @default null
  15166. */
  15167. this.clearcoatRoughnessNode = null;
  15168. /**
  15169. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  15170. * property. This node property allows to overwrite the default
  15171. * and define the clearcoat normal with a node instead.
  15172. *
  15173. * If you don't want to overwrite the clearcoat normal but modify the existing
  15174. * value instead, use {@link materialClearcoatNormal}.
  15175. *
  15176. * @type {?Node<vec3>}
  15177. * @default null
  15178. */
  15179. this.clearcoatNormalNode = null;
  15180. /**
  15181. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  15182. * and `sheenColorMap` properties. This node property allows to overwrite the default
  15183. * and define the sheen with a node instead.
  15184. *
  15185. * If you don't want to overwrite the sheen but modify the existing
  15186. * value instead, use {@link materialSheen}.
  15187. *
  15188. * @type {?Node<vec3>}
  15189. * @default null
  15190. */
  15191. this.sheenNode = null;
  15192. /**
  15193. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  15194. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  15195. * and define the sheen roughness with a node instead.
  15196. *
  15197. * If you don't want to overwrite the sheen roughness but modify the existing
  15198. * value instead, use {@link materialSheenRoughness}.
  15199. *
  15200. * @type {?Node<float>}
  15201. * @default null
  15202. */
  15203. this.sheenRoughnessNode = null;
  15204. /**
  15205. * The iridescence of physical materials is by default inferred from the `iridescence`
  15206. * property. This node property allows to overwrite the default
  15207. * and define the iridescence with a node instead.
  15208. *
  15209. * If you don't want to overwrite the iridescence but modify the existing
  15210. * value instead, use {@link materialIridescence}.
  15211. *
  15212. * @type {?Node<float>}
  15213. * @default null
  15214. */
  15215. this.iridescenceNode = null;
  15216. /**
  15217. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  15218. * property. This node property allows to overwrite the default
  15219. * and define the iridescence IOR with a node instead.
  15220. *
  15221. * If you don't want to overwrite the iridescence IOR but modify the existing
  15222. * value instead, use {@link materialIridescenceIOR}.
  15223. *
  15224. * @type {?Node<float>}
  15225. * @default null
  15226. */
  15227. this.iridescenceIORNode = null;
  15228. /**
  15229. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  15230. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  15231. * and define the iridescence thickness with a node instead.
  15232. *
  15233. * If you don't want to overwrite the iridescence thickness but modify the existing
  15234. * value instead, use {@link materialIridescenceThickness}.
  15235. *
  15236. * @type {?Node<float>}
  15237. * @default null
  15238. */
  15239. this.iridescenceThicknessNode = null;
  15240. /**
  15241. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  15242. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  15243. * and define the specular intensity with a node instead.
  15244. *
  15245. * If you don't want to overwrite the specular intensity but modify the existing
  15246. * value instead, use {@link materialSpecularIntensity}.
  15247. *
  15248. * @type {?Node<float>}
  15249. * @default null
  15250. */
  15251. this.specularIntensityNode = null;
  15252. /**
  15253. * The specular color of physical materials is by default inferred from the `specularColor`
  15254. * and `specularColorMap` properties. This node property allows to overwrite the default
  15255. * and define the specular color with a node instead.
  15256. *
  15257. * If you don't want to overwrite the specular color but modify the existing
  15258. * value instead, use {@link materialSpecularColor}.
  15259. *
  15260. * @type {?Node<vec3>}
  15261. * @default null
  15262. */
  15263. this.specularColorNode = null;
  15264. /**
  15265. * The ior of physical materials is by default inferred from the `ior`
  15266. * property. This node property allows to overwrite the default
  15267. * and define the ior with a node instead.
  15268. *
  15269. * If you don't want to overwrite the ior but modify the existing
  15270. * value instead, use {@link materialIOR}.
  15271. *
  15272. * @type {?Node<float>}
  15273. * @default null
  15274. */
  15275. this.iorNode = null;
  15276. /**
  15277. * The transmission of physical materials is by default inferred from the `transmission` and
  15278. * `transmissionMap` properties. This node property allows to overwrite the default
  15279. * and define the transmission with a node instead.
  15280. *
  15281. * If you don't want to overwrite the transmission but modify the existing
  15282. * value instead, use {@link materialTransmission}.
  15283. *
  15284. * @type {?Node<float>}
  15285. * @default null
  15286. */
  15287. this.transmissionNode = null;
  15288. /**
  15289. * The thickness of physical materials is by default inferred from the `thickness` and
  15290. * `thicknessMap` properties. This node property allows to overwrite the default
  15291. * and define the thickness with a node instead.
  15292. *
  15293. * If you don't want to overwrite the thickness but modify the existing
  15294. * value instead, use {@link materialThickness}.
  15295. *
  15296. * @type {?Node<float>}
  15297. * @default null
  15298. */
  15299. this.thicknessNode = null;
  15300. /**
  15301. * The attenuation distance of physical materials is by default inferred from the
  15302. * `attenuationDistance` property. This node property allows to overwrite the default
  15303. * and define the attenuation distance with a node instead.
  15304. *
  15305. * If you don't want to overwrite the attenuation distance but modify the existing
  15306. * value instead, use {@link materialAttenuationDistance}.
  15307. *
  15308. * @type {?Node<float>}
  15309. * @default null
  15310. */
  15311. this.attenuationDistanceNode = null;
  15312. /**
  15313. * The attenuation color of physical materials is by default inferred from the
  15314. * `attenuationColor` property. This node property allows to overwrite the default
  15315. * and define the attenuation color with a node instead.
  15316. *
  15317. * If you don't want to overwrite the attenuation color but modify the existing
  15318. * value instead, use {@link materialAttenuationColor}.
  15319. *
  15320. * @type {?Node<vec3>}
  15321. * @default null
  15322. */
  15323. this.attenuationColorNode = null;
  15324. /**
  15325. * The dispersion of physical materials is by default inferred from the
  15326. * `dispersion` property. This node property allows to overwrite the default
  15327. * and define the dispersion with a node instead.
  15328. *
  15329. * If you don't want to overwrite the dispersion but modify the existing
  15330. * value instead, use {@link materialDispersion}.
  15331. *
  15332. * @type {?Node<float>}
  15333. * @default null
  15334. */
  15335. this.dispersionNode = null;
  15336. /**
  15337. * The anisotropy of physical materials is by default inferred from the
  15338. * `anisotropy` property. This node property allows to overwrite the default
  15339. * and define the anisotropy with a node instead.
  15340. *
  15341. * If you don't want to overwrite the anisotropy but modify the existing
  15342. * value instead, use {@link materialAnisotropy}.
  15343. *
  15344. * @type {?Node<float>}
  15345. * @default null
  15346. */
  15347. this.anisotropyNode = null;
  15348. this.setDefaultValues( _defaultValues$5 );
  15349. this.setValues( parameters );
  15350. }
  15351. /**
  15352. * Whether the lighting model should use clearcoat or not.
  15353. *
  15354. * @type {boolean}
  15355. * @default true
  15356. */
  15357. get useClearcoat() {
  15358. return this.clearcoat > 0 || this.clearcoatNode !== null;
  15359. }
  15360. /**
  15361. * Whether the lighting model should use iridescence or not.
  15362. *
  15363. * @type {boolean}
  15364. * @default true
  15365. */
  15366. get useIridescence() {
  15367. return this.iridescence > 0 || this.iridescenceNode !== null;
  15368. }
  15369. /**
  15370. * Whether the lighting model should use sheen or not.
  15371. *
  15372. * @type {boolean}
  15373. * @default true
  15374. */
  15375. get useSheen() {
  15376. return this.sheen > 0 || this.sheenNode !== null;
  15377. }
  15378. /**
  15379. * Whether the lighting model should use anisotropy or not.
  15380. *
  15381. * @type {boolean}
  15382. * @default true
  15383. */
  15384. get useAnisotropy() {
  15385. return this.anisotropy > 0 || this.anisotropyNode !== null;
  15386. }
  15387. /**
  15388. * Whether the lighting model should use transmission or not.
  15389. *
  15390. * @type {boolean}
  15391. * @default true
  15392. */
  15393. get useTransmission() {
  15394. return this.transmission > 0 || this.transmissionNode !== null;
  15395. }
  15396. /**
  15397. * Whether the lighting model should use dispersion or not.
  15398. *
  15399. * @type {boolean}
  15400. * @default true
  15401. */
  15402. get useDispersion() {
  15403. return this.dispersion > 0 || this.dispersionNode !== null;
  15404. }
  15405. /**
  15406. * Setups the specular related node variables.
  15407. */
  15408. setupSpecular() {
  15409. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  15410. ior.assign( iorNode );
  15411. 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 ) );
  15412. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  15413. }
  15414. /**
  15415. * Setups the lighting model.
  15416. *
  15417. * @return {PhysicalLightingModel} The lighting model.
  15418. */
  15419. setupLightingModel( /*builder*/ ) {
  15420. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  15421. }
  15422. /**
  15423. * Setups the physical specific node variables.
  15424. *
  15425. * @param {NodeBuilder} builder - The current node builder.
  15426. */
  15427. setupVariants( builder ) {
  15428. super.setupVariants( builder );
  15429. // CLEARCOAT
  15430. if ( this.useClearcoat ) {
  15431. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  15432. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  15433. clearcoat.assign( clearcoatNode );
  15434. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  15435. }
  15436. // SHEEN
  15437. if ( this.useSheen ) {
  15438. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  15439. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  15440. sheen.assign( sheenNode );
  15441. sheenRoughness.assign( sheenRoughnessNode );
  15442. }
  15443. // IRIDESCENCE
  15444. if ( this.useIridescence ) {
  15445. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  15446. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  15447. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  15448. iridescence.assign( iridescenceNode );
  15449. iridescenceIOR.assign( iridescenceIORNode );
  15450. iridescenceThickness.assign( iridescenceThicknessNode );
  15451. }
  15452. // ANISOTROPY
  15453. if ( this.useAnisotropy ) {
  15454. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  15455. anisotropy.assign( anisotropyV.length() );
  15456. If( anisotropy.equal( 0.0 ), () => {
  15457. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15458. } ).Else( () => {
  15459. anisotropyV.divAssign( vec2( anisotropy ) );
  15460. anisotropy.assign( anisotropy.saturate() );
  15461. } );
  15462. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15463. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15464. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15465. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15466. }
  15467. // TRANSMISSION
  15468. if ( this.useTransmission ) {
  15469. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15470. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15471. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15472. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15473. transmission.assign( transmissionNode );
  15474. thickness.assign( thicknessNode );
  15475. attenuationDistance.assign( attenuationDistanceNode );
  15476. attenuationColor.assign( attenuationColorNode );
  15477. if ( this.useDispersion ) {
  15478. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15479. dispersion.assign( dispersionNode );
  15480. }
  15481. }
  15482. }
  15483. /**
  15484. * Setups the clearcoat normal node.
  15485. *
  15486. * @return {Node<vec3>} The clearcoat normal.
  15487. */
  15488. setupClearcoatNormal() {
  15489. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15490. }
  15491. setup( builder ) {
  15492. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15493. super.setup( builder );
  15494. }
  15495. copy( source ) {
  15496. this.clearcoatNode = source.clearcoatNode;
  15497. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15498. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15499. this.sheenNode = source.sheenNode;
  15500. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15501. this.iridescenceNode = source.iridescenceNode;
  15502. this.iridescenceIORNode = source.iridescenceIORNode;
  15503. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15504. this.specularIntensityNode = source.specularIntensityNode;
  15505. this.specularColorNode = source.specularColorNode;
  15506. this.transmissionNode = source.transmissionNode;
  15507. this.thicknessNode = source.thicknessNode;
  15508. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15509. this.attenuationColorNode = source.attenuationColorNode;
  15510. this.dispersionNode = source.dispersionNode;
  15511. this.anisotropyNode = source.anisotropyNode;
  15512. return super.copy( source );
  15513. }
  15514. }
  15515. /**
  15516. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15517. *
  15518. * @augments PhysicalLightingModel
  15519. */
  15520. class SSSLightingModel extends PhysicalLightingModel {
  15521. /**
  15522. * Constructs a new physical lighting model.
  15523. *
  15524. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15525. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15526. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15527. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15528. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15529. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15530. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  15531. */
  15532. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15533. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15534. /**
  15535. * Whether the lighting model should use SSS or not.
  15536. *
  15537. * @type {boolean}
  15538. * @default false
  15539. */
  15540. this.useSSS = sss;
  15541. }
  15542. /**
  15543. * Extends the default implementation with a SSS term.
  15544. *
  15545. * 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/}
  15546. *
  15547. * @param {Object} input - The input data.
  15548. * @param {StackNode} stack - The current stack.
  15549. * @param {NodeBuilder} builder - The current node builder.
  15550. */
  15551. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15552. if ( this.useSSS === true ) {
  15553. const material = builder.material;
  15554. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15555. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15556. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15557. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15558. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15559. }
  15560. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15561. }
  15562. }
  15563. /**
  15564. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15565. * that implements a Subsurface scattering (SSS) term.
  15566. *
  15567. * @augments MeshPhysicalNodeMaterial
  15568. */
  15569. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15570. static get type() {
  15571. return 'MeshSSSNodeMaterial';
  15572. }
  15573. /**
  15574. * Constructs a new mesh SSS node material.
  15575. *
  15576. * @param {?Object} parameters - The configuration parameter.
  15577. */
  15578. constructor( parameters ) {
  15579. super( parameters );
  15580. /**
  15581. * Represents the thickness color.
  15582. *
  15583. * @type {?Node<vec3>}
  15584. * @default null
  15585. */
  15586. this.thicknessColorNode = null;
  15587. /**
  15588. * Represents the distortion factor.
  15589. *
  15590. * @type {?Node<float>}
  15591. */
  15592. this.thicknessDistortionNode = float( 0.1 );
  15593. /**
  15594. * Represents the thickness ambient factor.
  15595. *
  15596. * @type {?Node<float>}
  15597. */
  15598. this.thicknessAmbientNode = float( 0.0 );
  15599. /**
  15600. * Represents the thickness attenuation.
  15601. *
  15602. * @type {?Node<float>}
  15603. */
  15604. this.thicknessAttenuationNode = float( .1 );
  15605. /**
  15606. * Represents the thickness power.
  15607. *
  15608. * @type {?Node<float>}
  15609. */
  15610. this.thicknessPowerNode = float( 2.0 );
  15611. /**
  15612. * Represents the thickness scale.
  15613. *
  15614. * @type {?Node<float>}
  15615. */
  15616. this.thicknessScaleNode = float( 10.0 );
  15617. }
  15618. /**
  15619. * Whether the lighting model should use SSS or not.
  15620. *
  15621. * @type {boolean}
  15622. * @default true
  15623. */
  15624. get useSSS() {
  15625. return this.thicknessColorNode !== null;
  15626. }
  15627. /**
  15628. * Setups the lighting model.
  15629. *
  15630. * @return {SSSLightingModel} The lighting model.
  15631. */
  15632. setupLightingModel( /*builder*/ ) {
  15633. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15634. }
  15635. copy( source ) {
  15636. this.thicknessColorNode = source.thicknessColorNode;
  15637. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15638. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15639. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15640. this.thicknessPowerNode = source.thicknessPowerNode;
  15641. this.thicknessScaleNode = source.thicknessScaleNode;
  15642. return super.copy( source );
  15643. }
  15644. }
  15645. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15646. // dotNL will be from -1.0 to 1.0
  15647. const dotNL = normal.dot( lightDirection );
  15648. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15649. if ( builder.material.gradientMap ) {
  15650. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15651. return vec3( gradientMap.r );
  15652. } else {
  15653. const fw = coord.fwidth().mul( 0.5 );
  15654. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15655. }
  15656. } );
  15657. /**
  15658. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15659. *
  15660. * @augments LightingModel
  15661. */
  15662. class ToonLightingModel extends LightingModel {
  15663. /**
  15664. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15665. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15666. *
  15667. * @param {Object} input - The input data.
  15668. * @param {StackNode} stack - The current stack.
  15669. * @param {NodeBuilder} builder - The current node builder.
  15670. */
  15671. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15672. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15673. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15674. }
  15675. /**
  15676. * Implements the indirect lighting.
  15677. *
  15678. * @param {ContextNode} input - The current node context.
  15679. * @param {StackNode} stack - The current stack.
  15680. * @param {NodeBuilder} builder - The current node builder.
  15681. */
  15682. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15683. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15684. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15685. }
  15686. }
  15687. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15688. /**
  15689. * Node material version of `MeshToonMaterial`.
  15690. *
  15691. * @augments NodeMaterial
  15692. */
  15693. class MeshToonNodeMaterial extends NodeMaterial {
  15694. static get type() {
  15695. return 'MeshToonNodeMaterial';
  15696. }
  15697. /**
  15698. * Constructs a new mesh toon node material.
  15699. *
  15700. * @param {?Object} parameters - The configuration parameter.
  15701. */
  15702. constructor( parameters ) {
  15703. super();
  15704. /**
  15705. * This flag can be used for type testing.
  15706. *
  15707. * @type {boolean}
  15708. * @readonly
  15709. * @default true
  15710. */
  15711. this.isMeshToonNodeMaterial = true;
  15712. /**
  15713. * Set to `true` because toon materials react on lights.
  15714. *
  15715. * @type {boolean}
  15716. * @default true
  15717. */
  15718. this.lights = true;
  15719. this.setDefaultValues( _defaultValues$4 );
  15720. this.setValues( parameters );
  15721. }
  15722. /**
  15723. * Setups the lighting model.
  15724. *
  15725. * @return {ToonLightingModel} The lighting model.
  15726. */
  15727. setupLightingModel( /*builder*/ ) {
  15728. return new ToonLightingModel();
  15729. }
  15730. }
  15731. /**
  15732. * Can be used to compute texture coordinates for projecting a
  15733. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15734. *
  15735. * @augments TempNode
  15736. */
  15737. class MatcapUVNode extends TempNode {
  15738. static get type() {
  15739. return 'MatcapUVNode';
  15740. }
  15741. /**
  15742. * Constructs a new matcap uv node.
  15743. */
  15744. constructor() {
  15745. super( 'vec2' );
  15746. }
  15747. setup() {
  15748. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15749. const y = positionViewDirection.cross( x );
  15750. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15751. }
  15752. }
  15753. /**
  15754. * TSL function for creating a matcap uv node.
  15755. *
  15756. * @tsl
  15757. * @function
  15758. * @returns {MatcapUVNode}
  15759. */
  15760. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15761. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15762. /**
  15763. * Node material version of `MeshMatcapMaterial`.
  15764. *
  15765. * @augments NodeMaterial
  15766. */
  15767. class MeshMatcapNodeMaterial extends NodeMaterial {
  15768. static get type() {
  15769. return 'MeshMatcapNodeMaterial';
  15770. }
  15771. /**
  15772. * Constructs a new mesh normal node material.
  15773. *
  15774. * @param {?Object} parameters - The configuration parameter.
  15775. */
  15776. constructor( parameters ) {
  15777. super();
  15778. /**
  15779. * This flag can be used for type testing.
  15780. *
  15781. * @type {boolean}
  15782. * @readonly
  15783. * @default true
  15784. */
  15785. this.isMeshMatcapNodeMaterial = true;
  15786. this.setDefaultValues( _defaultValues$3 );
  15787. this.setValues( parameters );
  15788. }
  15789. /**
  15790. * Setups the matcap specific node variables.
  15791. *
  15792. * @param {NodeBuilder} builder - The current node builder.
  15793. */
  15794. setupVariants( builder ) {
  15795. const uv = matcapUV;
  15796. let matcapColor;
  15797. if ( builder.material.matcap ) {
  15798. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15799. } else {
  15800. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15801. }
  15802. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15803. }
  15804. }
  15805. /**
  15806. * Applies a rotation to the given position node.
  15807. *
  15808. * @augments TempNode
  15809. */
  15810. class RotateNode extends TempNode {
  15811. static get type() {
  15812. return 'RotateNode';
  15813. }
  15814. /**
  15815. * Constructs a new rotate node.
  15816. *
  15817. * @param {Node} positionNode - The position node.
  15818. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15819. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15820. */
  15821. constructor( positionNode, rotationNode ) {
  15822. super();
  15823. /**
  15824. * The position node.
  15825. *
  15826. * @type {Node}
  15827. */
  15828. this.positionNode = positionNode;
  15829. /**
  15830. * Represents the rotation that is applied to the position node.
  15831. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15832. *
  15833. * @type {Node}
  15834. */
  15835. this.rotationNode = rotationNode;
  15836. }
  15837. /**
  15838. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15839. *
  15840. * @param {NodeBuilder} builder - The current node builder.
  15841. * @return {string} The node's type.
  15842. */
  15843. getNodeType( builder ) {
  15844. return this.positionNode.getNodeType( builder );
  15845. }
  15846. setup( builder ) {
  15847. const { rotationNode, positionNode } = this;
  15848. const nodeType = this.getNodeType( builder );
  15849. if ( nodeType === 'vec2' ) {
  15850. const cosAngle = rotationNode.cos();
  15851. const sinAngle = rotationNode.sin();
  15852. const rotationMatrix = mat2(
  15853. cosAngle, sinAngle,
  15854. sinAngle.negate(), cosAngle
  15855. );
  15856. return rotationMatrix.mul( positionNode );
  15857. } else {
  15858. const rotation = rotationNode;
  15859. 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 ) );
  15860. 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 ) );
  15861. 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 ) );
  15862. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15863. }
  15864. }
  15865. }
  15866. /**
  15867. * TSL function for creating a rotate node.
  15868. *
  15869. * @tsl
  15870. * @function
  15871. * @param {Node} positionNode - The position node.
  15872. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15873. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15874. * @returns {RotateNode}
  15875. */
  15876. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15877. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15878. /**
  15879. * Node material version of `SpriteMaterial`.
  15880. *
  15881. * @augments NodeMaterial
  15882. */
  15883. class SpriteNodeMaterial extends NodeMaterial {
  15884. static get type() {
  15885. return 'SpriteNodeMaterial';
  15886. }
  15887. /**
  15888. * Constructs a new sprite node material.
  15889. *
  15890. * @param {?Object} parameters - The configuration parameter.
  15891. */
  15892. constructor( parameters ) {
  15893. super();
  15894. /**
  15895. * This flag can be used for type testing.
  15896. *
  15897. * @type {boolean}
  15898. * @readonly
  15899. * @default true
  15900. */
  15901. this.isSpriteNodeMaterial = true;
  15902. this._useSizeAttenuation = true;
  15903. /**
  15904. * This property makes it possible to define the position of the sprite with a
  15905. * node. That can be useful when the material is used with instanced rendering
  15906. * and node data are defined with an instanced attribute node:
  15907. * ```js
  15908. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15909. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15910. * ```
  15911. * Another possibility is to compute the instanced data with a compute shader:
  15912. * ```js
  15913. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15914. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15915. * ```
  15916. *
  15917. * @type {?Node<vec2>}
  15918. * @default null
  15919. */
  15920. this.positionNode = null;
  15921. /**
  15922. * The rotation of sprite materials is by default inferred from the `rotation`,
  15923. * property. This node property allows to overwrite the default and define
  15924. * the rotation with a node instead.
  15925. *
  15926. * If you don't want to overwrite the rotation but modify the existing
  15927. * value instead, use {@link materialRotation}.
  15928. *
  15929. * @type {?Node<float>}
  15930. * @default null
  15931. */
  15932. this.rotationNode = null;
  15933. /**
  15934. * This node property provides an additional way to scale sprites next to
  15935. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15936. * is multiplied with the scale value of this node in the vertex shader.
  15937. *
  15938. * @type {?Node<vec2>}
  15939. * @default null
  15940. */
  15941. this.scaleNode = null;
  15942. /**
  15943. * In Sprites, the transparent property is enabled by default.
  15944. *
  15945. * @type {boolean}
  15946. * @default true
  15947. */
  15948. this.transparent = true;
  15949. this.setDefaultValues( _defaultValues$2 );
  15950. this.setValues( parameters );
  15951. }
  15952. /**
  15953. * Setups the position node in view space. This method implements
  15954. * the sprite specific vertex shader.
  15955. *
  15956. * @param {NodeBuilder} builder - The current node builder.
  15957. * @return {Node<vec3>} The position in view space.
  15958. */
  15959. setupPositionView( builder ) {
  15960. const { object, camera } = builder;
  15961. const sizeAttenuation = this.sizeAttenuation;
  15962. const { positionNode, rotationNode, scaleNode } = this;
  15963. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15964. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15965. if ( scaleNode !== null ) {
  15966. scale = scale.mul( float( scaleNode ) );
  15967. }
  15968. if ( sizeAttenuation === false ) {
  15969. if ( camera.isPerspectiveCamera ) {
  15970. scale = scale.mul( mvPosition.z.negate() );
  15971. } else {
  15972. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15973. scale = scale.mul( orthoScale.mul( 2 ) );
  15974. }
  15975. }
  15976. let alignedPosition = positionGeometry.xy;
  15977. if ( object.center && object.center.isVector2 === true ) {
  15978. const center = reference$1( 'center', 'vec2', object );
  15979. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15980. }
  15981. alignedPosition = alignedPosition.mul( scale );
  15982. const rotation = float( rotationNode || materialRotation );
  15983. const rotatedPosition = rotate( alignedPosition, rotation );
  15984. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15985. }
  15986. copy( source ) {
  15987. this.positionNode = source.positionNode;
  15988. this.rotationNode = source.rotationNode;
  15989. this.scaleNode = source.scaleNode;
  15990. return super.copy( source );
  15991. }
  15992. /**
  15993. * Whether to use size attenuation or not.
  15994. *
  15995. * @type {boolean}
  15996. * @default true
  15997. */
  15998. get sizeAttenuation() {
  15999. return this._useSizeAttenuation;
  16000. }
  16001. set sizeAttenuation( value ) {
  16002. if ( this._useSizeAttenuation !== value ) {
  16003. this._useSizeAttenuation = value;
  16004. this.needsUpdate = true;
  16005. }
  16006. }
  16007. }
  16008. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  16009. /**
  16010. * Node material version of `PointsMaterial`.
  16011. *
  16012. * @augments NodeMaterial
  16013. */
  16014. class PointsNodeMaterial extends SpriteNodeMaterial {
  16015. static get type() {
  16016. return 'PointsNodeMaterial';
  16017. }
  16018. /**
  16019. * Constructs a new points node material.
  16020. *
  16021. * @param {?Object} parameters - The configuration parameter.
  16022. */
  16023. constructor( parameters ) {
  16024. super();
  16025. /**
  16026. * This node property provides an additional way to set the point size.
  16027. *
  16028. * @type {?Node<vec2>}
  16029. * @default null
  16030. */
  16031. this.sizeNode = null;
  16032. /**
  16033. * This flag can be used for type testing.
  16034. *
  16035. * @type {boolean}
  16036. * @readonly
  16037. * @default true
  16038. */
  16039. this.isPointsNodeMaterial = true;
  16040. this.setDefaultValues( _defaultValues$1 );
  16041. this.setValues( parameters );
  16042. }
  16043. setupPositionView() {
  16044. const { positionNode } = this;
  16045. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  16046. }
  16047. setupVertex( builder ) {
  16048. const mvp = super.setupVertex( builder );
  16049. // skip further processing if the material is not a node material
  16050. if ( builder.material.isNodeMaterial !== true ) {
  16051. return mvp;
  16052. }
  16053. // ndc space
  16054. const { rotationNode, scaleNode, sizeNode } = this;
  16055. const alignedPosition = positionGeometry.xy.toVar();
  16056. const aspect = viewport.z.div( viewport.w );
  16057. // rotation
  16058. if ( rotationNode && rotationNode.isNode ) {
  16059. const rotation = float( rotationNode );
  16060. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  16061. }
  16062. // point size
  16063. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  16064. if ( this.sizeAttenuation === true ) {
  16065. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  16066. }
  16067. // scale
  16068. if ( scaleNode && scaleNode.isNode ) {
  16069. pointSize = pointSize.mul( vec2( scaleNode ) );
  16070. }
  16071. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  16072. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  16073. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  16074. // back to clip space
  16075. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  16076. //clipPos.xy += offset;
  16077. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  16078. return mvp;
  16079. }
  16080. /**
  16081. * Whether alpha to coverage should be used or not.
  16082. *
  16083. * @type {boolean}
  16084. * @default true
  16085. */
  16086. get alphaToCoverage() {
  16087. return this._useAlphaToCoverage;
  16088. }
  16089. set alphaToCoverage( value ) {
  16090. if ( this._useAlphaToCoverage !== value ) {
  16091. this._useAlphaToCoverage = value;
  16092. this.needsUpdate = true;
  16093. }
  16094. }
  16095. }
  16096. /**
  16097. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  16098. *
  16099. * @augments LightingModel
  16100. */
  16101. class ShadowMaskModel extends LightingModel {
  16102. /**
  16103. * Constructs a new shadow mask model.
  16104. */
  16105. constructor() {
  16106. super();
  16107. /**
  16108. * The shadow mask node.
  16109. *
  16110. * @type {Node}
  16111. */
  16112. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  16113. }
  16114. /**
  16115. * Only used to save the shadow mask.
  16116. *
  16117. * @param {Object} input - The input data.
  16118. */
  16119. direct( { shadowMask } ) {
  16120. this.shadowNode.mulAssign( shadowMask );
  16121. }
  16122. /**
  16123. * Uses the shadow mask to produce the final color.
  16124. *
  16125. * @param {ContextNode} context - The current node context.
  16126. */
  16127. finish( context ) {
  16128. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  16129. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  16130. }
  16131. }
  16132. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  16133. /**
  16134. * Node material version of `ShadowMaterial`.
  16135. *
  16136. * @augments NodeMaterial
  16137. */
  16138. class ShadowNodeMaterial extends NodeMaterial {
  16139. static get type() {
  16140. return 'ShadowNodeMaterial';
  16141. }
  16142. /**
  16143. * Constructs a new shadow node material.
  16144. *
  16145. * @param {?Object} parameters - The configuration parameter.
  16146. */
  16147. constructor( parameters ) {
  16148. super();
  16149. /**
  16150. * This flag can be used for type testing.
  16151. *
  16152. * @type {boolean}
  16153. * @readonly
  16154. * @default true
  16155. */
  16156. this.isShadowNodeMaterial = true;
  16157. /**
  16158. * Set to `true` because so it's possible to implement
  16159. * the shadow mask effect.
  16160. *
  16161. * @type {boolean}
  16162. * @default true
  16163. */
  16164. this.lights = true;
  16165. this.setDefaultValues( _defaultValues );
  16166. this.setValues( parameters );
  16167. }
  16168. /**
  16169. * Setups the lighting model.
  16170. *
  16171. * @return {ShadowMaskModel} The lighting model.
  16172. */
  16173. setupLightingModel( /*builder*/ ) {
  16174. return new ShadowMaskModel();
  16175. }
  16176. }
  16177. const normal = Fn( ( { texture, uv } ) => {
  16178. const epsilon = 0.0001;
  16179. const ret = vec3().toVar();
  16180. If( uv.x.lessThan( epsilon ), () => {
  16181. ret.assign( vec3( 1, 0, 0 ) );
  16182. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  16183. ret.assign( vec3( 0, 1, 0 ) );
  16184. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  16185. ret.assign( vec3( 0, 0, 1 ) );
  16186. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  16187. ret.assign( vec3( -1, 0, 0 ) );
  16188. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  16189. ret.assign( vec3( 0, -1, 0 ) );
  16190. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  16191. ret.assign( vec3( 0, 0, -1 ) );
  16192. } ).Else( () => {
  16193. const step = 0.01;
  16194. 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 );
  16195. 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 );
  16196. 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 );
  16197. ret.assign( vec3( x, y, z ) );
  16198. } );
  16199. return ret.normalize();
  16200. } );
  16201. /**
  16202. * This type of uniform node represents a 3D texture.
  16203. *
  16204. * @augments TextureNode
  16205. */
  16206. class Texture3DNode extends TextureNode {
  16207. static get type() {
  16208. return 'Texture3DNode';
  16209. }
  16210. /**
  16211. * Constructs a new 3D texture node.
  16212. *
  16213. * @param {Data3DTexture} value - The 3D texture.
  16214. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  16215. * @param {?Node<int>} [levelNode=null] - The level node.
  16216. */
  16217. constructor( value, uvNode = null, levelNode = null ) {
  16218. super( value, uvNode, levelNode );
  16219. /**
  16220. * This flag can be used for type testing.
  16221. *
  16222. * @type {boolean}
  16223. * @readonly
  16224. * @default true
  16225. */
  16226. this.isTexture3DNode = true;
  16227. }
  16228. /**
  16229. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  16230. *
  16231. * @param {NodeBuilder} builder - The current node builder.
  16232. * @return {string} The input type.
  16233. */
  16234. getInputType( /*builder*/ ) {
  16235. return 'texture3D';
  16236. }
  16237. /**
  16238. * Returns a default uv node which is in context of 3D textures a three-dimensional
  16239. * uv node.
  16240. *
  16241. * @return {Node<vec3>} The default uv node.
  16242. */
  16243. getDefaultUV() {
  16244. return vec3( 0.5, 0.5, 0.5 );
  16245. }
  16246. /**
  16247. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  16248. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  16249. *
  16250. * @param {boolean} value - The update toggle.
  16251. */
  16252. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  16253. /**
  16254. * Overwrites the default implementation to return the unmodified uv node.
  16255. *
  16256. * @param {NodeBuilder} builder - The current node builder.
  16257. * @param {Node} uvNode - The uv node to setup.
  16258. * @return {Node} The unmodified uv node.
  16259. */
  16260. setupUV( builder, uvNode ) {
  16261. const texture = this.value;
  16262. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  16263. if ( this.sampler ) {
  16264. uvNode = uvNode.flipY();
  16265. } else {
  16266. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  16267. }
  16268. }
  16269. return uvNode;
  16270. }
  16271. /**
  16272. * Generates the uv code snippet.
  16273. *
  16274. * @param {NodeBuilder} builder - The current node builder.
  16275. * @param {Node} uvNode - The uv node to generate code for.
  16276. * @return {string} The generated code snippet.
  16277. */
  16278. generateUV( builder, uvNode ) {
  16279. return uvNode.build( builder, 'vec3' );
  16280. }
  16281. /**
  16282. * TODO.
  16283. *
  16284. * @param {Node<vec3>} uvNode - The uv node .
  16285. * @return {Node<vec3>} TODO.
  16286. */
  16287. normal( uvNode ) {
  16288. return normal( { texture: this, uv: uvNode } );
  16289. }
  16290. }
  16291. /**
  16292. * TSL function for creating a 3D texture node.
  16293. *
  16294. * @tsl
  16295. * @function
  16296. * @param {Data3DTexture} value - The 3D texture.
  16297. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  16298. * @param {?Node<int>} [levelNode=null] - The level node.
  16299. * @returns {Texture3DNode}
  16300. */
  16301. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  16302. /**
  16303. * Node material intended for volume rendering. The volumetric data are
  16304. * defined with an instance of {@link Data3DTexture}.
  16305. *
  16306. * @augments NodeMaterial
  16307. */
  16308. class VolumeNodeMaterial extends NodeMaterial {
  16309. static get type() {
  16310. return 'VolumeNodeMaterial';
  16311. }
  16312. /**
  16313. * Constructs a new volume node material.
  16314. *
  16315. * @param {?Object} parameters - The configuration parameter.
  16316. */
  16317. constructor( parameters ) {
  16318. super();
  16319. /**
  16320. * This flag can be used for type testing.
  16321. *
  16322. * @type {boolean}
  16323. * @readonly
  16324. * @default true
  16325. */
  16326. this.isVolumeNodeMaterial = true;
  16327. /**
  16328. * The base color of the volume.
  16329. *
  16330. * @type {Color}
  16331. * @default 100
  16332. */
  16333. this.base = new Color( 0xffffff );
  16334. /**
  16335. * A 3D data texture holding the volumetric data.
  16336. *
  16337. * @type {?Data3DTexture}
  16338. * @default null
  16339. */
  16340. this.map = null;
  16341. /**
  16342. * This number of samples for each ray that hits the mesh's surface
  16343. * and travels through the volume.
  16344. *
  16345. * @type {number}
  16346. * @default 100
  16347. */
  16348. this.steps = 100;
  16349. /**
  16350. * Callback for {@link VolumeNodeMaterial#testNode}.
  16351. *
  16352. * @callback testNodeCallback
  16353. * @param {Data3DTexture<float>} map - The 3D texture.
  16354. * @param {Node<float>} mapValue - The sampled value inside the volume.
  16355. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  16356. * @param {Node<vec4>} finalColor - The final color.
  16357. */
  16358. /**
  16359. * The volume rendering of this material works by shooting rays
  16360. * from the camera position through each fragment of the mesh's
  16361. * surface and sample the inner volume in a raymarching fashion
  16362. * multiple times.
  16363. *
  16364. * This node can be used to assign a callback function of type `Fn`
  16365. * that will be executed per sample. The callback receives the
  16366. * texture, the sampled texture value as well as position on the surface
  16367. * where the rays enters the volume. The last parameter is a color
  16368. * that allows the callback to determine the final color.
  16369. *
  16370. * @type {?testNodeCallback}
  16371. * @default null
  16372. */
  16373. this.testNode = null;
  16374. this.setValues( parameters );
  16375. }
  16376. /**
  16377. * Setups the vertex and fragment stage of this node material.
  16378. *
  16379. * @param {NodeBuilder} builder - The current node builder.
  16380. */
  16381. setup( builder ) {
  16382. const map = texture3D( this.map, null, 0 );
  16383. const hitBox = Fn( ( { orig, dir } ) => {
  16384. const box_min = vec3( -0.5 );
  16385. const box_max = vec3( 0.5 );
  16386. const inv_dir = dir.reciprocal();
  16387. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  16388. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  16389. const tmin = min$1( tmin_tmp, tmax_tmp );
  16390. const tmax = max$1( tmin_tmp, tmax_tmp );
  16391. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  16392. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  16393. return vec2( t0, t1 );
  16394. } );
  16395. this.fragmentNode = Fn( () => {
  16396. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  16397. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  16398. const rayDir = vDirection.normalize();
  16399. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  16400. bounds.x.greaterThan( bounds.y ).discard();
  16401. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  16402. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  16403. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  16404. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  16405. delta.divAssign( materialReference( 'steps', 'float' ) );
  16406. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  16407. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  16408. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  16409. if ( this.testNode !== null ) {
  16410. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  16411. } else {
  16412. // default to show surface of mesh
  16413. ac.a.assign( 1 );
  16414. Break();
  16415. }
  16416. p.addAssign( rayDir.mul( delta ) );
  16417. } );
  16418. ac.a.equal( 0 ).discard();
  16419. return vec4( ac );
  16420. } )();
  16421. super.setup( builder );
  16422. }
  16423. }
  16424. /**
  16425. * This module manages the internal animation loop of the renderer.
  16426. *
  16427. * @private
  16428. */
  16429. class Animation {
  16430. /**
  16431. * Constructs a new animation loop management component.
  16432. *
  16433. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16434. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16435. */
  16436. constructor( nodes, info ) {
  16437. /**
  16438. * Renderer component for managing nodes related logic.
  16439. *
  16440. * @type {Nodes}
  16441. */
  16442. this.nodes = nodes;
  16443. /**
  16444. * Renderer component for managing metrics and monitoring data.
  16445. *
  16446. * @type {Info}
  16447. */
  16448. this.info = info;
  16449. /**
  16450. * A reference to the context from `requestAnimationFrame()` can
  16451. * be called (usually `window`).
  16452. *
  16453. * @type {Window|XRSession}
  16454. */
  16455. this._context = self;
  16456. /**
  16457. * The user-defined animation loop.
  16458. *
  16459. * @type {?Function}
  16460. * @default null
  16461. */
  16462. this._animationLoop = null;
  16463. /**
  16464. * The requestId which is returned from the `requestAnimationFrame()` call.
  16465. * Can be used to cancel the stop the animation loop.
  16466. *
  16467. * @type {?number}
  16468. * @default null
  16469. */
  16470. this._requestId = null;
  16471. }
  16472. /**
  16473. * Starts the internal animation loop.
  16474. */
  16475. start() {
  16476. const update = ( time, frame ) => {
  16477. this._requestId = this._context.requestAnimationFrame( update );
  16478. if ( this.info.autoReset === true ) this.info.reset();
  16479. this.nodes.nodeFrame.update();
  16480. this.info.frame = this.nodes.nodeFrame.frameId;
  16481. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16482. };
  16483. update();
  16484. }
  16485. /**
  16486. * Stops the internal animation loop.
  16487. */
  16488. stop() {
  16489. this._context.cancelAnimationFrame( this._requestId );
  16490. this._requestId = null;
  16491. }
  16492. /**
  16493. * Returns the user-level animation loop.
  16494. *
  16495. * @return {Function} The animation loop.
  16496. */
  16497. getAnimationLoop() {
  16498. return this._animationLoop;
  16499. }
  16500. /**
  16501. * Defines the user-level animation loop.
  16502. *
  16503. * @param {Function} callback - The animation loop.
  16504. */
  16505. setAnimationLoop( callback ) {
  16506. this._animationLoop = callback;
  16507. }
  16508. /**
  16509. * Returns the animation context.
  16510. *
  16511. * @return {Window|XRSession} The animation context.
  16512. */
  16513. getContext() {
  16514. return this._context;
  16515. }
  16516. /**
  16517. * Defines the context in which `requestAnimationFrame()` is executed.
  16518. *
  16519. * @param {Window|XRSession} context - The context to set.
  16520. */
  16521. setContext( context ) {
  16522. this._context = context;
  16523. }
  16524. /**
  16525. * Frees all internal resources and stops the animation loop.
  16526. */
  16527. dispose() {
  16528. this.stop();
  16529. }
  16530. }
  16531. /**
  16532. * Data structure for the renderer. It allows defining values
  16533. * with chained, hierarchical keys. Keys are meant to be
  16534. * objects since the module internally works with Weak Maps
  16535. * for performance reasons.
  16536. *
  16537. * @private
  16538. */
  16539. class ChainMap {
  16540. /**
  16541. * Constructs a new Chain Map.
  16542. */
  16543. constructor() {
  16544. /**
  16545. * The root Weak Map.
  16546. *
  16547. * @type {WeakMap}
  16548. */
  16549. this.weakMap = new WeakMap();
  16550. }
  16551. /**
  16552. * Returns the value for the given array of keys.
  16553. *
  16554. * @param {Array<Object>} keys - List of keys.
  16555. * @return {any} The value. Returns `undefined` if no value was found.
  16556. */
  16557. get( keys ) {
  16558. let map = this.weakMap;
  16559. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16560. map = map.get( keys[ i ] );
  16561. if ( map === undefined ) return undefined;
  16562. }
  16563. return map.get( keys[ keys.length - 1 ] );
  16564. }
  16565. /**
  16566. * Sets the value for the given keys.
  16567. *
  16568. * @param {Array<Object>} keys - List of keys.
  16569. * @param {any} value - The value to set.
  16570. * @return {ChainMap} A reference to this Chain Map.
  16571. */
  16572. set( keys, value ) {
  16573. let map = this.weakMap;
  16574. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16575. const key = keys[ i ];
  16576. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16577. map = map.get( key );
  16578. }
  16579. map.set( keys[ keys.length - 1 ], value );
  16580. return this;
  16581. }
  16582. /**
  16583. * Deletes a value for the given keys.
  16584. *
  16585. * @param {Array<Object>} keys - The keys.
  16586. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16587. */
  16588. delete( keys ) {
  16589. let map = this.weakMap;
  16590. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16591. map = map.get( keys[ i ] );
  16592. if ( map === undefined ) return false;
  16593. }
  16594. return map.delete( keys[ keys.length - 1 ] );
  16595. }
  16596. }
  16597. let _id$9 = 0;
  16598. function getKeys( obj ) {
  16599. const keys = Object.keys( obj );
  16600. let proto = Object.getPrototypeOf( obj );
  16601. while ( proto ) {
  16602. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16603. for ( const key in descriptors ) {
  16604. if ( descriptors[ key ] !== undefined ) {
  16605. const descriptor = descriptors[ key ];
  16606. if ( descriptor && typeof descriptor.get === 'function' ) {
  16607. keys.push( key );
  16608. }
  16609. }
  16610. }
  16611. proto = Object.getPrototypeOf( proto );
  16612. }
  16613. return keys;
  16614. }
  16615. /**
  16616. * A render object is the renderer's representation of single entity that gets drawn
  16617. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16618. * scene since render objects also depend from the used material, the current render context
  16619. * and the current scene's lighting.
  16620. *
  16621. * In general, the basic process of the renderer is:
  16622. *
  16623. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16624. * - Process the render lists by calling one or more render commands for each render item.
  16625. * - For each render command, request a render object and perform the draw.
  16626. *
  16627. * The module provides an interface to get data required for the draw command like the actual
  16628. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16629. * creating render objects should only be done when necessary.
  16630. *
  16631. * @private
  16632. */
  16633. class RenderObject {
  16634. /**
  16635. * Constructs a new render object.
  16636. *
  16637. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16638. * @param {Geometries} geometries - Renderer component for managing geometries.
  16639. * @param {Renderer} renderer - The renderer.
  16640. * @param {Object3D} object - The 3D object.
  16641. * @param {Material} material - The 3D object's material.
  16642. * @param {Scene} scene - The scene the 3D object belongs to.
  16643. * @param {Camera} camera - The camera the object should be rendered with.
  16644. * @param {LightsNode} lightsNode - The lights node.
  16645. * @param {RenderContext} renderContext - The render context.
  16646. * @param {ClippingContext} clippingContext - The clipping context.
  16647. */
  16648. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16649. this.id = _id$9 ++;
  16650. /**
  16651. * Renderer component for managing nodes related logic.
  16652. *
  16653. * @type {Nodes}
  16654. * @private
  16655. */
  16656. this._nodes = nodes;
  16657. /**
  16658. * Renderer component for managing geometries.
  16659. *
  16660. * @type {Geometries}
  16661. * @private
  16662. */
  16663. this._geometries = geometries;
  16664. /**
  16665. * The renderer.
  16666. *
  16667. * @type {Renderer}
  16668. */
  16669. this.renderer = renderer;
  16670. /**
  16671. * The 3D object.
  16672. *
  16673. * @type {Object3D}
  16674. */
  16675. this.object = object;
  16676. /**
  16677. * The 3D object's material.
  16678. *
  16679. * @type {Material}
  16680. */
  16681. this.material = material;
  16682. /**
  16683. * The scene the 3D object belongs to.
  16684. *
  16685. * @type {Scene}
  16686. */
  16687. this.scene = scene;
  16688. /**
  16689. * The camera the 3D object should be rendered with.
  16690. *
  16691. * @type {Camera}
  16692. */
  16693. this.camera = camera;
  16694. /**
  16695. * The lights node.
  16696. *
  16697. * @type {LightsNode}
  16698. */
  16699. this.lightsNode = lightsNode;
  16700. /**
  16701. * The render context.
  16702. *
  16703. * @type {RenderContext}
  16704. */
  16705. this.context = renderContext;
  16706. /**
  16707. * The 3D object's geometry.
  16708. *
  16709. * @type {BufferGeometry}
  16710. */
  16711. this.geometry = object.geometry;
  16712. /**
  16713. * The render object's version.
  16714. *
  16715. * @type {number}
  16716. */
  16717. this.version = material.version;
  16718. /**
  16719. * The draw range of the geometry.
  16720. *
  16721. * @type {?Object}
  16722. * @default null
  16723. */
  16724. this.drawRange = null;
  16725. /**
  16726. * An array holding the buffer attributes
  16727. * of the render object. This entails attribute
  16728. * definitions on geometry and node level.
  16729. *
  16730. * @type {?Array<BufferAttribute>}
  16731. * @default null
  16732. */
  16733. this.attributes = null;
  16734. /**
  16735. * A reference to a render pipeline the render
  16736. * object is processed with.
  16737. *
  16738. * @type {RenderPipeline}
  16739. * @default null
  16740. */
  16741. this.pipeline = null;
  16742. /**
  16743. * Only relevant for objects using
  16744. * multiple materials. This represents a group entry
  16745. * from the respective `BufferGeometry`.
  16746. *
  16747. * @type {?{start: number, count: number}}
  16748. * @default null
  16749. */
  16750. this.group = null;
  16751. /**
  16752. * An array holding the vertex buffers which can
  16753. * be buffer attributes but also interleaved buffers.
  16754. *
  16755. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  16756. * @default null
  16757. */
  16758. this.vertexBuffers = null;
  16759. /**
  16760. * The parameters for the draw command.
  16761. *
  16762. * @type {?Object}
  16763. * @default null
  16764. */
  16765. this.drawParams = null;
  16766. /**
  16767. * If this render object is used inside a render bundle,
  16768. * this property points to the respective bundle group.
  16769. *
  16770. * @type {?BundleGroup}
  16771. * @default null
  16772. */
  16773. this.bundle = null;
  16774. /**
  16775. * The clipping context.
  16776. *
  16777. * @type {ClippingContext}
  16778. */
  16779. this.clippingContext = clippingContext;
  16780. /**
  16781. * The clipping context's cache key.
  16782. *
  16783. * @type {string}
  16784. */
  16785. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16786. /**
  16787. * The initial node cache key.
  16788. *
  16789. * @type {number}
  16790. */
  16791. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16792. /**
  16793. * The initial cache key.
  16794. *
  16795. * @type {number}
  16796. */
  16797. this.initialCacheKey = this.getCacheKey();
  16798. /**
  16799. * The node builder state.
  16800. *
  16801. * @type {?NodeBuilderState}
  16802. * @private
  16803. * @default null
  16804. */
  16805. this._nodeBuilderState = null;
  16806. /**
  16807. * An array of bindings.
  16808. *
  16809. * @type {?Array<BindGroup>}
  16810. * @private
  16811. * @default null
  16812. */
  16813. this._bindings = null;
  16814. /**
  16815. * Reference to the node material observer.
  16816. *
  16817. * @type {?NodeMaterialObserver}
  16818. * @private
  16819. * @default null
  16820. */
  16821. this._monitor = null;
  16822. /**
  16823. * An event listener which is defined by `RenderObjects`. It performs
  16824. * clean up tasks when `dispose()` on this render object.
  16825. *
  16826. * @method
  16827. */
  16828. this.onDispose = null;
  16829. /**
  16830. * This flag can be used for type testing.
  16831. *
  16832. * @type {boolean}
  16833. * @readonly
  16834. * @default true
  16835. */
  16836. this.isRenderObject = true;
  16837. /**
  16838. * An event listener which is executed when `dispose()` is called on
  16839. * the render object's material.
  16840. *
  16841. * @method
  16842. */
  16843. this.onMaterialDispose = () => {
  16844. this.dispose();
  16845. };
  16846. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16847. }
  16848. /**
  16849. * Updates the clipping context.
  16850. *
  16851. * @param {ClippingContext} context - The clipping context to set.
  16852. */
  16853. updateClipping( context ) {
  16854. this.clippingContext = context;
  16855. }
  16856. /**
  16857. * Whether the clipping requires an update or not.
  16858. *
  16859. * @type {boolean}
  16860. * @readonly
  16861. */
  16862. get clippingNeedsUpdate() {
  16863. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16864. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16865. return true;
  16866. }
  16867. /**
  16868. * The number of clipping planes defined in context of hardware clipping.
  16869. *
  16870. * @type {number}
  16871. * @readonly
  16872. */
  16873. get hardwareClippingPlanes() {
  16874. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16875. }
  16876. /**
  16877. * Returns the node builder state of this render object.
  16878. *
  16879. * @return {NodeBuilderState} The node builder state.
  16880. */
  16881. getNodeBuilderState() {
  16882. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16883. }
  16884. /**
  16885. * Returns the node material observer of this render object.
  16886. *
  16887. * @return {NodeMaterialObserver} The node material observer.
  16888. */
  16889. getMonitor() {
  16890. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16891. }
  16892. /**
  16893. * Returns an array of bind groups of this render object.
  16894. *
  16895. * @return {Array<BindGroup>} The bindings.
  16896. */
  16897. getBindings() {
  16898. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16899. }
  16900. /**
  16901. * Returns a binding group by group name of this render object.
  16902. *
  16903. * @param {string} name - The name of the binding group.
  16904. * @return {?BindGroup} The bindings.
  16905. */
  16906. getBindingGroup( name ) {
  16907. for ( const bindingGroup of this.getBindings() ) {
  16908. if ( bindingGroup.name === name ) {
  16909. return bindingGroup;
  16910. }
  16911. }
  16912. }
  16913. /**
  16914. * Returns the index of the render object's geometry.
  16915. *
  16916. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  16917. */
  16918. getIndex() {
  16919. return this._geometries.getIndex( this );
  16920. }
  16921. /**
  16922. * Returns the indirect buffer attribute.
  16923. *
  16924. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  16925. */
  16926. getIndirect() {
  16927. return this._geometries.getIndirect( this );
  16928. }
  16929. /**
  16930. * Returns an array that acts as a key for identifying the render object in a chain map.
  16931. *
  16932. * @return {Array<Object>} An array with object references.
  16933. */
  16934. getChainArray() {
  16935. return [ this.object, this.material, this.context, this.lightsNode ];
  16936. }
  16937. /**
  16938. * This method is used when the geometry of a 3D object has been exchanged and the
  16939. * respective render object now requires an update.
  16940. *
  16941. * @param {BufferGeometry} geometry - The geometry to set.
  16942. */
  16943. setGeometry( geometry ) {
  16944. this.geometry = geometry;
  16945. this.attributes = null;
  16946. }
  16947. /**
  16948. * Returns the buffer attributes of the render object. The returned array holds
  16949. * attribute definitions on geometry and node level.
  16950. *
  16951. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16952. */
  16953. getAttributes() {
  16954. if ( this.attributes !== null ) return this.attributes;
  16955. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16956. const geometry = this.geometry;
  16957. const attributes = [];
  16958. const vertexBuffers = new Set();
  16959. for ( const nodeAttribute of nodeAttributes ) {
  16960. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16961. if ( attribute === undefined ) continue;
  16962. attributes.push( attribute );
  16963. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16964. vertexBuffers.add( bufferAttribute );
  16965. }
  16966. this.attributes = attributes;
  16967. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16968. return attributes;
  16969. }
  16970. /**
  16971. * Returns the vertex buffers of the render object.
  16972. *
  16973. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16974. */
  16975. getVertexBuffers() {
  16976. if ( this.vertexBuffers === null ) this.getAttributes();
  16977. return this.vertexBuffers;
  16978. }
  16979. /**
  16980. * Returns the draw parameters for the render object.
  16981. *
  16982. * @return {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  16983. */
  16984. getDrawParameters() {
  16985. const { object, material, geometry, group, drawRange } = this;
  16986. const drawParams = this.drawParams || ( this.drawParams = {
  16987. vertexCount: 0,
  16988. firstVertex: 0,
  16989. instanceCount: 0,
  16990. firstInstance: 0
  16991. } );
  16992. const index = this.getIndex();
  16993. const hasIndex = ( index !== null );
  16994. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16995. if ( instanceCount === 0 ) return null;
  16996. drawParams.instanceCount = instanceCount;
  16997. if ( object.isBatchedMesh === true ) return drawParams;
  16998. let rangeFactor = 1;
  16999. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  17000. rangeFactor = 2;
  17001. }
  17002. let firstVertex = drawRange.start * rangeFactor;
  17003. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  17004. if ( group !== null ) {
  17005. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  17006. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  17007. }
  17008. const position = geometry.attributes.position;
  17009. let itemCount = Infinity;
  17010. if ( hasIndex ) {
  17011. itemCount = index.count;
  17012. } else if ( position !== undefined && position !== null ) {
  17013. itemCount = position.count;
  17014. }
  17015. firstVertex = Math.max( firstVertex, 0 );
  17016. lastVertex = Math.min( lastVertex, itemCount );
  17017. const count = lastVertex - firstVertex;
  17018. if ( count < 0 || count === Infinity ) return null;
  17019. drawParams.vertexCount = count;
  17020. drawParams.firstVertex = firstVertex;
  17021. return drawParams;
  17022. }
  17023. /**
  17024. * Returns the render object's geometry cache key.
  17025. *
  17026. * The geometry cache key is part of the material cache key.
  17027. *
  17028. * @return {string} The geometry cache key.
  17029. */
  17030. getGeometryCacheKey() {
  17031. const { geometry } = this;
  17032. let cacheKey = '';
  17033. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  17034. const attribute = geometry.attributes[ name ];
  17035. cacheKey += name + ',';
  17036. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  17037. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  17038. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  17039. if ( attribute.normalized ) cacheKey += 'n,';
  17040. }
  17041. // structural equality isn't sufficient for morph targets since the
  17042. // data are maintained in textures. only if the targets are all equal
  17043. // the texture and thus the instance of `MorphNode` can be shared.
  17044. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  17045. const targets = geometry.morphAttributes[ name ];
  17046. cacheKey += 'morph-' + name + ',';
  17047. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  17048. const attribute = targets[ i ];
  17049. cacheKey += attribute.id + ',';
  17050. }
  17051. }
  17052. if ( geometry.index ) {
  17053. cacheKey += 'index,';
  17054. }
  17055. return cacheKey;
  17056. }
  17057. /**
  17058. * Returns the render object's material cache key.
  17059. *
  17060. * The material cache key is part of the render object cache key.
  17061. *
  17062. * @return {number} The material cache key.
  17063. */
  17064. getMaterialCacheKey() {
  17065. const { object, material } = this;
  17066. let cacheKey = material.customProgramCacheKey();
  17067. for ( const property of getKeys( material ) ) {
  17068. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  17069. const value = material[ property ];
  17070. let valueKey;
  17071. if ( value !== null ) {
  17072. // some material values require a formatting
  17073. const type = typeof value;
  17074. if ( type === 'number' ) {
  17075. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  17076. } else if ( type === 'object' ) {
  17077. valueKey = '{';
  17078. if ( value.isTexture ) {
  17079. valueKey += value.mapping;
  17080. }
  17081. valueKey += '}';
  17082. } else {
  17083. valueKey = String( value );
  17084. }
  17085. } else {
  17086. valueKey = String( value );
  17087. }
  17088. cacheKey += /*property + ':' +*/ valueKey + ',';
  17089. }
  17090. cacheKey += this.clippingContextCacheKey + ',';
  17091. if ( object.geometry ) {
  17092. cacheKey += this.getGeometryCacheKey();
  17093. }
  17094. if ( object.skeleton ) {
  17095. cacheKey += object.skeleton.bones.length + ',';
  17096. }
  17097. if ( object.isBatchedMesh ) {
  17098. cacheKey += object._matricesTexture.uuid + ',';
  17099. if ( object._colorsTexture !== null ) {
  17100. cacheKey += object._colorsTexture.uuid + ',';
  17101. }
  17102. }
  17103. if ( object.count > 1 ) {
  17104. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  17105. cacheKey += object.uuid + ',';
  17106. }
  17107. cacheKey += object.receiveShadow + ',';
  17108. return hashString( cacheKey );
  17109. }
  17110. /**
  17111. * Whether the geometry requires an update or not.
  17112. *
  17113. * @type {boolean}
  17114. * @readonly
  17115. */
  17116. get needsGeometryUpdate() {
  17117. return this.geometry.id !== this.object.geometry.id;
  17118. }
  17119. /**
  17120. * Whether the render object requires an update or not.
  17121. *
  17122. * Note: There are two distinct places where render objects are checked for an update.
  17123. *
  17124. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  17125. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  17126. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  17127. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  17128. * a need for a refresh due to material, geometry or object related value changes.
  17129. *
  17130. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  17131. * that performs the 'needsUpdate' check.
  17132. *
  17133. * @type {boolean}
  17134. * @readonly
  17135. */
  17136. get needsUpdate() {
  17137. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  17138. }
  17139. /**
  17140. * Returns the dynamic cache key which represents a key that is computed per draw command.
  17141. *
  17142. * @return {number} The cache key.
  17143. */
  17144. getDynamicCacheKey() {
  17145. let cacheKey = 0;
  17146. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  17147. // the renderer is inside a shadow pass.
  17148. if ( this.material.isShadowPassMaterial !== true ) {
  17149. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  17150. }
  17151. if ( this.camera.isArrayCamera ) {
  17152. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  17153. }
  17154. if ( this.object.receiveShadow ) {
  17155. cacheKey = hash$1( cacheKey, 1 );
  17156. }
  17157. return cacheKey;
  17158. }
  17159. /**
  17160. * Returns the render object's cache key.
  17161. *
  17162. * @return {number} The cache key.
  17163. */
  17164. getCacheKey() {
  17165. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  17166. }
  17167. /**
  17168. * Frees internal resources.
  17169. */
  17170. dispose() {
  17171. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  17172. this.onDispose();
  17173. }
  17174. }
  17175. const _chainKeys$5 = [];
  17176. /**
  17177. * This module manages the render objects of the renderer.
  17178. *
  17179. * @private
  17180. */
  17181. class RenderObjects {
  17182. /**
  17183. * Constructs a new render object management component.
  17184. *
  17185. * @param {Renderer} renderer - The renderer.
  17186. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17187. * @param {Geometries} geometries - Renderer component for managing geometries.
  17188. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17189. * @param {Bindings} bindings - Renderer component for managing bindings.
  17190. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17191. */
  17192. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  17193. /**
  17194. * The renderer.
  17195. *
  17196. * @type {Renderer}
  17197. */
  17198. this.renderer = renderer;
  17199. /**
  17200. * Renderer component for managing nodes related logic.
  17201. *
  17202. * @type {Nodes}
  17203. */
  17204. this.nodes = nodes;
  17205. /**
  17206. * Renderer component for managing geometries.
  17207. *
  17208. * @type {Geometries}
  17209. */
  17210. this.geometries = geometries;
  17211. /**
  17212. * Renderer component for managing pipelines.
  17213. *
  17214. * @type {Pipelines}
  17215. */
  17216. this.pipelines = pipelines;
  17217. /**
  17218. * Renderer component for managing bindings.
  17219. *
  17220. * @type {Bindings}
  17221. */
  17222. this.bindings = bindings;
  17223. /**
  17224. * Renderer component for managing metrics and monitoring data.
  17225. *
  17226. * @type {Info}
  17227. */
  17228. this.info = info;
  17229. /**
  17230. * A dictionary that manages render contexts in chain maps
  17231. * for each pass ID.
  17232. *
  17233. * @type {Object<string,ChainMap>}
  17234. */
  17235. this.chainMaps = {};
  17236. }
  17237. /**
  17238. * Returns a render object for the given object and state data.
  17239. *
  17240. * @param {Object3D} object - The 3D object.
  17241. * @param {Material} material - The 3D object's material.
  17242. * @param {Scene} scene - The scene the 3D object belongs to.
  17243. * @param {Camera} camera - The camera the 3D object should be rendered with.
  17244. * @param {LightsNode} lightsNode - The lights node.
  17245. * @param {RenderContext} renderContext - The render context.
  17246. * @param {ClippingContext} clippingContext - The clipping context.
  17247. * @param {?string} passId - An optional ID for identifying the pass.
  17248. * @return {RenderObject} The render object.
  17249. */
  17250. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17251. const chainMap = this.getChainMap( passId );
  17252. // reuse chainArray
  17253. _chainKeys$5[ 0 ] = object;
  17254. _chainKeys$5[ 1 ] = material;
  17255. _chainKeys$5[ 2 ] = renderContext;
  17256. _chainKeys$5[ 3 ] = lightsNode;
  17257. let renderObject = chainMap.get( _chainKeys$5 );
  17258. if ( renderObject === undefined ) {
  17259. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17260. chainMap.set( _chainKeys$5, renderObject );
  17261. } else {
  17262. renderObject.updateClipping( clippingContext );
  17263. if ( renderObject.needsGeometryUpdate ) {
  17264. renderObject.setGeometry( object.geometry );
  17265. }
  17266. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  17267. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  17268. renderObject.dispose();
  17269. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17270. } else {
  17271. renderObject.version = material.version;
  17272. }
  17273. }
  17274. }
  17275. _chainKeys$5.length = 0;
  17276. return renderObject;
  17277. }
  17278. /**
  17279. * Returns a chain map for the given pass ID.
  17280. *
  17281. * @param {string} [passId='default'] - The pass ID.
  17282. * @return {ChainMap} The chain map.
  17283. */
  17284. getChainMap( passId = 'default' ) {
  17285. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  17286. }
  17287. /**
  17288. * Frees internal resources.
  17289. */
  17290. dispose() {
  17291. this.chainMaps = {};
  17292. }
  17293. /**
  17294. * Factory method for creating render objects with the given list of parameters.
  17295. *
  17296. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17297. * @param {Geometries} geometries - Renderer component for managing geometries.
  17298. * @param {Renderer} renderer - The renderer.
  17299. * @param {Object3D} object - The 3D object.
  17300. * @param {Material} material - The object's material.
  17301. * @param {Scene} scene - The scene the 3D object belongs to.
  17302. * @param {Camera} camera - The camera the object should be rendered with.
  17303. * @param {LightsNode} lightsNode - The lights node.
  17304. * @param {RenderContext} renderContext - The render context.
  17305. * @param {ClippingContext} clippingContext - The clipping context.
  17306. * @param {?string} passId - An optional ID for identifying the pass.
  17307. * @return {RenderObject} The render object.
  17308. */
  17309. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17310. const chainMap = this.getChainMap( passId );
  17311. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  17312. renderObject.onDispose = () => {
  17313. this.pipelines.delete( renderObject );
  17314. this.bindings.delete( renderObject );
  17315. this.nodes.delete( renderObject );
  17316. chainMap.delete( renderObject.getChainArray() );
  17317. };
  17318. return renderObject;
  17319. }
  17320. }
  17321. /**
  17322. * Data structure for the renderer. It is intended to manage
  17323. * data of objects in dictionaries.
  17324. *
  17325. * @private
  17326. */
  17327. class DataMap {
  17328. /**
  17329. * Constructs a new data map.
  17330. */
  17331. constructor() {
  17332. /**
  17333. * `DataMap` internally uses a weak map
  17334. * to manage its data.
  17335. *
  17336. * @type {WeakMap}
  17337. */
  17338. this.data = new WeakMap();
  17339. }
  17340. /**
  17341. * Returns the dictionary for the given object.
  17342. *
  17343. * @param {Object} object - The object.
  17344. * @return {Object} The dictionary.
  17345. */
  17346. get( object ) {
  17347. let map = this.data.get( object );
  17348. if ( map === undefined ) {
  17349. map = {};
  17350. this.data.set( object, map );
  17351. }
  17352. return map;
  17353. }
  17354. /**
  17355. * Deletes the dictionary for the given object.
  17356. *
  17357. * @param {Object} object - The object.
  17358. * @return {?Object} The deleted dictionary.
  17359. */
  17360. delete( object ) {
  17361. let map = null;
  17362. if ( this.data.has( object ) ) {
  17363. map = this.data.get( object );
  17364. this.data.delete( object );
  17365. }
  17366. return map;
  17367. }
  17368. /**
  17369. * Returns `true` if the given object has a dictionary defined.
  17370. *
  17371. * @param {Object} object - The object to test.
  17372. * @return {boolean} Whether a dictionary is defined or not.
  17373. */
  17374. has( object ) {
  17375. return this.data.has( object );
  17376. }
  17377. /**
  17378. * Frees internal resources.
  17379. */
  17380. dispose() {
  17381. this.data = new WeakMap();
  17382. }
  17383. }
  17384. const AttributeType = {
  17385. VERTEX: 1,
  17386. INDEX: 2,
  17387. STORAGE: 3,
  17388. INDIRECT: 4
  17389. };
  17390. // size of a chunk in bytes (STD140 layout)
  17391. const GPU_CHUNK_BYTES = 16;
  17392. // @TODO: Move to src/constants.js
  17393. const BlendColorFactor = 211;
  17394. const OneMinusBlendColorFactor = 212;
  17395. /**
  17396. * This renderer module manages geometry attributes.
  17397. *
  17398. * @private
  17399. * @augments DataMap
  17400. */
  17401. class Attributes extends DataMap {
  17402. /**
  17403. * Constructs a new attribute management component.
  17404. *
  17405. * @param {Backend} backend - The renderer's backend.
  17406. */
  17407. constructor( backend ) {
  17408. super();
  17409. /**
  17410. * The renderer's backend.
  17411. *
  17412. * @type {Backend}
  17413. */
  17414. this.backend = backend;
  17415. }
  17416. /**
  17417. * Deletes the data for the given attribute.
  17418. *
  17419. * @param {BufferAttribute} attribute - The attribute.
  17420. * @return {Object} The deleted attribute data.
  17421. */
  17422. delete( attribute ) {
  17423. const attributeData = super.delete( attribute );
  17424. if ( attributeData !== undefined ) {
  17425. this.backend.destroyAttribute( attribute );
  17426. }
  17427. return attributeData;
  17428. }
  17429. /**
  17430. * Updates the given attribute. This method creates attribute buffers
  17431. * for new attributes and updates data for existing ones.
  17432. *
  17433. * @param {BufferAttribute} attribute - The attribute to update.
  17434. * @param {number} type - The attribute type.
  17435. */
  17436. update( attribute, type ) {
  17437. const data = this.get( attribute );
  17438. if ( data.version === undefined ) {
  17439. if ( type === AttributeType.VERTEX ) {
  17440. this.backend.createAttribute( attribute );
  17441. } else if ( type === AttributeType.INDEX ) {
  17442. this.backend.createIndexAttribute( attribute );
  17443. } else if ( type === AttributeType.STORAGE ) {
  17444. this.backend.createStorageAttribute( attribute );
  17445. } else if ( type === AttributeType.INDIRECT ) {
  17446. this.backend.createIndirectStorageAttribute( attribute );
  17447. }
  17448. data.version = this._getBufferAttribute( attribute ).version;
  17449. } else {
  17450. const bufferAttribute = this._getBufferAttribute( attribute );
  17451. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  17452. this.backend.updateAttribute( attribute );
  17453. data.version = bufferAttribute.version;
  17454. }
  17455. }
  17456. }
  17457. /**
  17458. * Utility method for handling interleaved buffer attributes correctly.
  17459. * To process them, their `InterleavedBuffer` is returned.
  17460. *
  17461. * @param {BufferAttribute} attribute - The attribute.
  17462. * @return {BufferAttribute|InterleavedBuffer}
  17463. */
  17464. _getBufferAttribute( attribute ) {
  17465. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17466. return attribute;
  17467. }
  17468. }
  17469. /**
  17470. * Returns the wireframe version for the given geometry.
  17471. *
  17472. * @private
  17473. * @function
  17474. * @param {BufferGeometry} geometry - The geometry.
  17475. * @return {number} The version.
  17476. */
  17477. function getWireframeVersion( geometry ) {
  17478. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17479. }
  17480. /**
  17481. * Returns a wireframe index attribute for the given geometry.
  17482. *
  17483. * @private
  17484. * @function
  17485. * @param {BufferGeometry} geometry - The geometry.
  17486. * @return {BufferAttribute} The wireframe index attribute.
  17487. */
  17488. function getWireframeIndex( geometry ) {
  17489. const indices = [];
  17490. const geometryIndex = geometry.index;
  17491. const geometryPosition = geometry.attributes.position;
  17492. if ( geometryIndex !== null ) {
  17493. const array = geometryIndex.array;
  17494. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17495. const a = array[ i + 0 ];
  17496. const b = array[ i + 1 ];
  17497. const c = array[ i + 2 ];
  17498. indices.push( a, b, b, c, c, a );
  17499. }
  17500. } else {
  17501. const array = geometryPosition.array;
  17502. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17503. const a = i + 0;
  17504. const b = i + 1;
  17505. const c = i + 2;
  17506. indices.push( a, b, b, c, c, a );
  17507. }
  17508. }
  17509. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17510. attribute.version = getWireframeVersion( geometry );
  17511. return attribute;
  17512. }
  17513. /**
  17514. * This renderer module manages geometries.
  17515. *
  17516. * @private
  17517. * @augments DataMap
  17518. */
  17519. class Geometries extends DataMap {
  17520. /**
  17521. * Constructs a new geometry management component.
  17522. *
  17523. * @param {Attributes} attributes - Renderer component for managing attributes.
  17524. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17525. */
  17526. constructor( attributes, info ) {
  17527. super();
  17528. /**
  17529. * Renderer component for managing attributes.
  17530. *
  17531. * @type {Attributes}
  17532. */
  17533. this.attributes = attributes;
  17534. /**
  17535. * Renderer component for managing metrics and monitoring data.
  17536. *
  17537. * @type {Info}
  17538. */
  17539. this.info = info;
  17540. /**
  17541. * Weak Map for managing attributes for wireframe rendering.
  17542. *
  17543. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17544. */
  17545. this.wireframes = new WeakMap();
  17546. /**
  17547. * This Weak Map is used to make sure buffer attributes are
  17548. * updated only once per render call.
  17549. *
  17550. * @type {WeakMap<BufferAttribute,number>}
  17551. */
  17552. this.attributeCall = new WeakMap();
  17553. }
  17554. /**
  17555. * Returns `true` if the given render object has an initialized geometry.
  17556. *
  17557. * @param {RenderObject} renderObject - The render object.
  17558. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  17559. */
  17560. has( renderObject ) {
  17561. const geometry = renderObject.geometry;
  17562. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17563. }
  17564. /**
  17565. * Prepares the geometry of the given render object for rendering.
  17566. *
  17567. * @param {RenderObject} renderObject - The render object.
  17568. */
  17569. updateForRender( renderObject ) {
  17570. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17571. this.updateAttributes( renderObject );
  17572. }
  17573. /**
  17574. * Initializes the geometry of the given render object.
  17575. *
  17576. * @param {RenderObject} renderObject - The render object.
  17577. */
  17578. initGeometry( renderObject ) {
  17579. const geometry = renderObject.geometry;
  17580. const geometryData = this.get( geometry );
  17581. geometryData.initialized = true;
  17582. this.info.memory.geometries ++;
  17583. const onDispose = () => {
  17584. this.info.memory.geometries --;
  17585. const index = geometry.index;
  17586. const geometryAttributes = renderObject.getAttributes();
  17587. if ( index !== null ) {
  17588. this.attributes.delete( index );
  17589. }
  17590. for ( const geometryAttribute of geometryAttributes ) {
  17591. this.attributes.delete( geometryAttribute );
  17592. }
  17593. const wireframeAttribute = this.wireframes.get( geometry );
  17594. if ( wireframeAttribute !== undefined ) {
  17595. this.attributes.delete( wireframeAttribute );
  17596. }
  17597. geometry.removeEventListener( 'dispose', onDispose );
  17598. };
  17599. geometry.addEventListener( 'dispose', onDispose );
  17600. }
  17601. /**
  17602. * Updates the geometry attributes of the given render object.
  17603. *
  17604. * @param {RenderObject} renderObject - The render object.
  17605. */
  17606. updateAttributes( renderObject ) {
  17607. // attributes
  17608. const attributes = renderObject.getAttributes();
  17609. for ( const attribute of attributes ) {
  17610. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17611. this.updateAttribute( attribute, AttributeType.STORAGE );
  17612. } else {
  17613. this.updateAttribute( attribute, AttributeType.VERTEX );
  17614. }
  17615. }
  17616. // indexes
  17617. const index = this.getIndex( renderObject );
  17618. if ( index !== null ) {
  17619. this.updateAttribute( index, AttributeType.INDEX );
  17620. }
  17621. // indirect
  17622. const indirect = renderObject.geometry.indirect;
  17623. if ( indirect !== null ) {
  17624. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17625. }
  17626. }
  17627. /**
  17628. * Updates the given attribute.
  17629. *
  17630. * @param {BufferAttribute} attribute - The attribute to update.
  17631. * @param {number} type - The attribute type.
  17632. */
  17633. updateAttribute( attribute, type ) {
  17634. const callId = this.info.render.calls;
  17635. if ( ! attribute.isInterleavedBufferAttribute ) {
  17636. if ( this.attributeCall.get( attribute ) !== callId ) {
  17637. this.attributes.update( attribute, type );
  17638. this.attributeCall.set( attribute, callId );
  17639. }
  17640. } else {
  17641. if ( this.attributeCall.get( attribute ) === undefined ) {
  17642. this.attributes.update( attribute, type );
  17643. this.attributeCall.set( attribute, callId );
  17644. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17645. this.attributes.update( attribute, type );
  17646. this.attributeCall.set( attribute.data, callId );
  17647. this.attributeCall.set( attribute, callId );
  17648. }
  17649. }
  17650. }
  17651. /**
  17652. * Returns the indirect buffer attribute of the given render object.
  17653. *
  17654. * @param {RenderObject} renderObject - The render object.
  17655. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  17656. */
  17657. getIndirect( renderObject ) {
  17658. return renderObject.geometry.indirect;
  17659. }
  17660. /**
  17661. * Returns the index of the given render object's geometry. This is implemented
  17662. * in a method to return a wireframe index if necessary.
  17663. *
  17664. * @param {RenderObject} renderObject - The render object.
  17665. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  17666. */
  17667. getIndex( renderObject ) {
  17668. const { geometry, material } = renderObject;
  17669. let index = geometry.index;
  17670. if ( material.wireframe === true ) {
  17671. const wireframes = this.wireframes;
  17672. let wireframeAttribute = wireframes.get( geometry );
  17673. if ( wireframeAttribute === undefined ) {
  17674. wireframeAttribute = getWireframeIndex( geometry );
  17675. wireframes.set( geometry, wireframeAttribute );
  17676. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17677. this.attributes.delete( wireframeAttribute );
  17678. wireframeAttribute = getWireframeIndex( geometry );
  17679. wireframes.set( geometry, wireframeAttribute );
  17680. }
  17681. index = wireframeAttribute;
  17682. }
  17683. return index;
  17684. }
  17685. }
  17686. /**
  17687. * This renderer module provides a series of statistical information
  17688. * about the GPU memory and the rendering process. Useful for debugging
  17689. * and monitoring.
  17690. */
  17691. class Info {
  17692. /**
  17693. * Constructs a new info component.
  17694. */
  17695. constructor() {
  17696. /**
  17697. * Whether frame related metrics should automatically
  17698. * be resetted or not. This property should be set to `false`
  17699. * by apps which manage their own animation loop. They must
  17700. * then call `renderer.info.reset()` once per frame manually.
  17701. *
  17702. * @type {boolean}
  17703. * @default true
  17704. */
  17705. this.autoReset = true;
  17706. /**
  17707. * The current frame ID. This ID is managed
  17708. * by `NodeFrame`.
  17709. *
  17710. * @type {number}
  17711. * @readonly
  17712. * @default 0
  17713. */
  17714. this.frame = 0;
  17715. /**
  17716. * The number of render calls since the
  17717. * app has been started.
  17718. *
  17719. * @type {number}
  17720. * @readonly
  17721. * @default 0
  17722. */
  17723. this.calls = 0;
  17724. /**
  17725. * Render related metrics.
  17726. *
  17727. * @type {Object}
  17728. * @readonly
  17729. * @property {number} calls - The number of render calls since the app has been started.
  17730. * @property {number} frameCalls - The number of render calls of the current frame.
  17731. * @property {number} drawCalls - The number of draw calls of the current frame.
  17732. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  17733. * @property {number} points - The number of rendered point primitives of the current frame.
  17734. * @property {number} lines - The number of rendered line primitives of the current frame.
  17735. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17736. */
  17737. this.render = {
  17738. calls: 0,
  17739. frameCalls: 0,
  17740. drawCalls: 0,
  17741. triangles: 0,
  17742. points: 0,
  17743. lines: 0,
  17744. timestamp: 0,
  17745. };
  17746. /**
  17747. * Compute related metrics.
  17748. *
  17749. * @type {Object}
  17750. * @readonly
  17751. * @property {number} calls - The number of compute calls since the app has been started.
  17752. * @property {number} frameCalls - The number of compute calls of the current frame.
  17753. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17754. */
  17755. this.compute = {
  17756. calls: 0,
  17757. frameCalls: 0,
  17758. timestamp: 0
  17759. };
  17760. /**
  17761. * Memory related metrics.
  17762. *
  17763. * @type {Object}
  17764. * @readonly
  17765. * @property {number} geometries - The number of active geometries.
  17766. * @property {number} frameCalls - The number of active textures.
  17767. */
  17768. this.memory = {
  17769. geometries: 0,
  17770. textures: 0
  17771. };
  17772. }
  17773. /**
  17774. * This method should be executed per draw call and updates the corresponding metrics.
  17775. *
  17776. * @param {Object3D} object - The 3D object that is going to be rendered.
  17777. * @param {number} count - The vertex or index count.
  17778. * @param {number} instanceCount - The instance count.
  17779. */
  17780. update( object, count, instanceCount ) {
  17781. this.render.drawCalls ++;
  17782. if ( object.isMesh || object.isSprite ) {
  17783. this.render.triangles += instanceCount * ( count / 3 );
  17784. } else if ( object.isPoints ) {
  17785. this.render.points += instanceCount * count;
  17786. } else if ( object.isLineSegments ) {
  17787. this.render.lines += instanceCount * ( count / 2 );
  17788. } else if ( object.isLine ) {
  17789. this.render.lines += instanceCount * ( count - 1 );
  17790. } else {
  17791. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17792. }
  17793. }
  17794. /**
  17795. * Resets frame related metrics.
  17796. */
  17797. reset() {
  17798. this.render.drawCalls = 0;
  17799. this.render.frameCalls = 0;
  17800. this.compute.frameCalls = 0;
  17801. this.render.triangles = 0;
  17802. this.render.points = 0;
  17803. this.render.lines = 0;
  17804. }
  17805. /**
  17806. * Performs a complete reset of the object.
  17807. */
  17808. dispose() {
  17809. this.reset();
  17810. this.calls = 0;
  17811. this.render.calls = 0;
  17812. this.compute.calls = 0;
  17813. this.render.timestamp = 0;
  17814. this.compute.timestamp = 0;
  17815. this.memory.geometries = 0;
  17816. this.memory.textures = 0;
  17817. }
  17818. }
  17819. /**
  17820. * Abstract class for representing pipelines.
  17821. *
  17822. * @private
  17823. * @abstract
  17824. */
  17825. class Pipeline {
  17826. /**
  17827. * Constructs a new pipeline.
  17828. *
  17829. * @param {string} cacheKey - The pipeline's cache key.
  17830. */
  17831. constructor( cacheKey ) {
  17832. /**
  17833. * The pipeline's cache key.
  17834. *
  17835. * @type {string}
  17836. */
  17837. this.cacheKey = cacheKey;
  17838. /**
  17839. * How often the pipeline is currently in use.
  17840. *
  17841. * @type {number}
  17842. * @default 0
  17843. */
  17844. this.usedTimes = 0;
  17845. }
  17846. }
  17847. /**
  17848. * Class for representing render pipelines.
  17849. *
  17850. * @private
  17851. * @augments Pipeline
  17852. */
  17853. class RenderPipeline extends Pipeline {
  17854. /**
  17855. * Constructs a new render pipeline.
  17856. *
  17857. * @param {string} cacheKey - The pipeline's cache key.
  17858. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17859. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17860. */
  17861. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17862. super( cacheKey );
  17863. /**
  17864. * The pipeline's vertex shader.
  17865. *
  17866. * @type {ProgrammableStage}
  17867. */
  17868. this.vertexProgram = vertexProgram;
  17869. /**
  17870. * The pipeline's fragment shader.
  17871. *
  17872. * @type {ProgrammableStage}
  17873. */
  17874. this.fragmentProgram = fragmentProgram;
  17875. }
  17876. }
  17877. /**
  17878. * Class for representing compute pipelines.
  17879. *
  17880. * @private
  17881. * @augments Pipeline
  17882. */
  17883. class ComputePipeline extends Pipeline {
  17884. /**
  17885. * Constructs a new render pipeline.
  17886. *
  17887. * @param {string} cacheKey - The pipeline's cache key.
  17888. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17889. */
  17890. constructor( cacheKey, computeProgram ) {
  17891. super( cacheKey );
  17892. /**
  17893. * The pipeline's compute shader.
  17894. *
  17895. * @type {ProgrammableStage}
  17896. */
  17897. this.computeProgram = computeProgram;
  17898. /**
  17899. * This flag can be used for type testing.
  17900. *
  17901. * @type {boolean}
  17902. * @readonly
  17903. * @default true
  17904. */
  17905. this.isComputePipeline = true;
  17906. }
  17907. }
  17908. let _id$8 = 0;
  17909. /**
  17910. * Class for representing programmable stages which are vertex,
  17911. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17912. * they represent the programmable part of a pipeline.
  17913. *
  17914. * @private
  17915. */
  17916. class ProgrammableStage {
  17917. /**
  17918. * Constructs a new programmable stage.
  17919. *
  17920. * @param {string} code - The shader code.
  17921. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17922. * @param {string} name - The name of the shader.
  17923. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17924. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17925. */
  17926. constructor( code, stage, name, transforms = null, attributes = null ) {
  17927. /**
  17928. * The id of the programmable stage.
  17929. *
  17930. * @type {number}
  17931. */
  17932. this.id = _id$8 ++;
  17933. /**
  17934. * The shader code.
  17935. *
  17936. * @type {string}
  17937. */
  17938. this.code = code;
  17939. /**
  17940. * The type of stage.
  17941. *
  17942. * @type {string}
  17943. */
  17944. this.stage = stage;
  17945. /**
  17946. * The name of the stage.
  17947. * This is used for debugging purposes.
  17948. *
  17949. * @type {string}
  17950. */
  17951. this.name = name;
  17952. /**
  17953. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17954. *
  17955. * @type {?Array<Object>}
  17956. */
  17957. this.transforms = transforms;
  17958. /**
  17959. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17960. *
  17961. * @type {?Array<Object>}
  17962. */
  17963. this.attributes = attributes;
  17964. /**
  17965. * How often the programmable stage is currently in use.
  17966. *
  17967. * @type {number}
  17968. * @default 0
  17969. */
  17970. this.usedTimes = 0;
  17971. }
  17972. }
  17973. /**
  17974. * This renderer module manages the pipelines of the renderer.
  17975. *
  17976. * @private
  17977. * @augments DataMap
  17978. */
  17979. class Pipelines extends DataMap {
  17980. /**
  17981. * Constructs a new pipeline management component.
  17982. *
  17983. * @param {Backend} backend - The renderer's backend.
  17984. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17985. */
  17986. constructor( backend, nodes ) {
  17987. super();
  17988. /**
  17989. * The renderer's backend.
  17990. *
  17991. * @type {Backend}
  17992. */
  17993. this.backend = backend;
  17994. /**
  17995. * Renderer component for managing nodes related logic.
  17996. *
  17997. * @type {Nodes}
  17998. */
  17999. this.nodes = nodes;
  18000. /**
  18001. * A references to the bindings management component.
  18002. * This reference will be set inside the `Bindings`
  18003. * constructor.
  18004. *
  18005. * @type {?Bindings}
  18006. * @default null
  18007. */
  18008. this.bindings = null;
  18009. /**
  18010. * Internal cache for maintaining pipelines.
  18011. * The key of the map is a cache key, the value the pipeline.
  18012. *
  18013. * @type {Map<string,Pipeline>}
  18014. */
  18015. this.caches = new Map();
  18016. /**
  18017. * This dictionary maintains for each shader stage type (vertex,
  18018. * fragment and compute) the programmable stage objects which
  18019. * represent the actual shader code.
  18020. *
  18021. * @type {Object<string,Map>}
  18022. */
  18023. this.programs = {
  18024. vertex: new Map(),
  18025. fragment: new Map(),
  18026. compute: new Map()
  18027. };
  18028. }
  18029. /**
  18030. * Returns a compute pipeline for the given compute node.
  18031. *
  18032. * @param {Node} computeNode - The compute node.
  18033. * @param {Array<BindGroup>} bindings - The bindings.
  18034. * @return {ComputePipeline} The compute pipeline.
  18035. */
  18036. getForCompute( computeNode, bindings ) {
  18037. const { backend } = this;
  18038. const data = this.get( computeNode );
  18039. if ( this._needsComputeUpdate( computeNode ) ) {
  18040. const previousPipeline = data.pipeline;
  18041. if ( previousPipeline ) {
  18042. previousPipeline.usedTimes --;
  18043. previousPipeline.computeProgram.usedTimes --;
  18044. }
  18045. // get shader
  18046. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  18047. // programmable stage
  18048. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  18049. if ( stageCompute === undefined ) {
  18050. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  18051. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  18052. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  18053. backend.createProgram( stageCompute );
  18054. }
  18055. // determine compute pipeline
  18056. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  18057. let pipeline = this.caches.get( cacheKey );
  18058. if ( pipeline === undefined ) {
  18059. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18060. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  18061. }
  18062. // keep track of all used times
  18063. pipeline.usedTimes ++;
  18064. stageCompute.usedTimes ++;
  18065. //
  18066. data.version = computeNode.version;
  18067. data.pipeline = pipeline;
  18068. }
  18069. return data.pipeline;
  18070. }
  18071. /**
  18072. * Returns a render pipeline for the given render object.
  18073. *
  18074. * @param {RenderObject} renderObject - The render object.
  18075. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18076. * @return {RenderPipeline} The render pipeline.
  18077. */
  18078. getForRender( renderObject, promises = null ) {
  18079. const { backend } = this;
  18080. const data = this.get( renderObject );
  18081. if ( this._needsRenderUpdate( renderObject ) ) {
  18082. const previousPipeline = data.pipeline;
  18083. if ( previousPipeline ) {
  18084. previousPipeline.usedTimes --;
  18085. previousPipeline.vertexProgram.usedTimes --;
  18086. previousPipeline.fragmentProgram.usedTimes --;
  18087. }
  18088. // get shader
  18089. const nodeBuilderState = renderObject.getNodeBuilderState();
  18090. const name = renderObject.material ? renderObject.material.name : '';
  18091. // programmable stages
  18092. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  18093. if ( stageVertex === undefined ) {
  18094. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  18095. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  18096. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  18097. backend.createProgram( stageVertex );
  18098. }
  18099. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  18100. if ( stageFragment === undefined ) {
  18101. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  18102. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  18103. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  18104. backend.createProgram( stageFragment );
  18105. }
  18106. // determine render pipeline
  18107. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18108. let pipeline = this.caches.get( cacheKey );
  18109. if ( pipeline === undefined ) {
  18110. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18111. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  18112. } else {
  18113. renderObject.pipeline = pipeline;
  18114. }
  18115. // keep track of all used times
  18116. pipeline.usedTimes ++;
  18117. stageVertex.usedTimes ++;
  18118. stageFragment.usedTimes ++;
  18119. //
  18120. data.pipeline = pipeline;
  18121. }
  18122. return data.pipeline;
  18123. }
  18124. /**
  18125. * Deletes the pipeline for the given render object.
  18126. *
  18127. * @param {RenderObject} object - The render object.
  18128. * @return {?Object} The deleted dictionary.
  18129. */
  18130. delete( object ) {
  18131. const pipeline = this.get( object ).pipeline;
  18132. if ( pipeline ) {
  18133. // pipeline
  18134. pipeline.usedTimes --;
  18135. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  18136. // programs
  18137. if ( pipeline.isComputePipeline ) {
  18138. pipeline.computeProgram.usedTimes --;
  18139. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  18140. } else {
  18141. pipeline.fragmentProgram.usedTimes --;
  18142. pipeline.vertexProgram.usedTimes --;
  18143. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  18144. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  18145. }
  18146. }
  18147. return super.delete( object );
  18148. }
  18149. /**
  18150. * Frees internal resources.
  18151. */
  18152. dispose() {
  18153. super.dispose();
  18154. this.caches = new Map();
  18155. this.programs = {
  18156. vertex: new Map(),
  18157. fragment: new Map(),
  18158. compute: new Map()
  18159. };
  18160. }
  18161. /**
  18162. * Updates the pipeline for the given render object.
  18163. *
  18164. * @param {RenderObject} renderObject - The render object.
  18165. */
  18166. updateForRender( renderObject ) {
  18167. this.getForRender( renderObject );
  18168. }
  18169. /**
  18170. * Returns a compute pipeline for the given parameters.
  18171. *
  18172. * @private
  18173. * @param {Node} computeNode - The compute node.
  18174. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18175. * @param {string} cacheKey - The cache key.
  18176. * @param {Array<BindGroup>} bindings - The bindings.
  18177. * @return {ComputePipeline} The compute pipeline.
  18178. */
  18179. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  18180. // check for existing pipeline
  18181. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  18182. let pipeline = this.caches.get( cacheKey );
  18183. if ( pipeline === undefined ) {
  18184. pipeline = new ComputePipeline( cacheKey, stageCompute );
  18185. this.caches.set( cacheKey, pipeline );
  18186. this.backend.createComputePipeline( pipeline, bindings );
  18187. }
  18188. return pipeline;
  18189. }
  18190. /**
  18191. * Returns a render pipeline for the given parameters.
  18192. *
  18193. * @private
  18194. * @param {RenderObject} renderObject - The render object.
  18195. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18196. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18197. * @param {string} cacheKey - The cache key.
  18198. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18199. * @return {ComputePipeline} The compute pipeline.
  18200. */
  18201. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  18202. // check for existing pipeline
  18203. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18204. let pipeline = this.caches.get( cacheKey );
  18205. if ( pipeline === undefined ) {
  18206. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  18207. this.caches.set( cacheKey, pipeline );
  18208. renderObject.pipeline = pipeline;
  18209. // The `promises` array is `null` by default and only set to an empty array when
  18210. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  18211. // pending promises that resolve when the render pipelines are ready for rendering.
  18212. this.backend.createRenderPipeline( renderObject, promises );
  18213. }
  18214. return pipeline;
  18215. }
  18216. /**
  18217. * Computes a cache key representing a compute pipeline.
  18218. *
  18219. * @private
  18220. * @param {Node} computeNode - The compute node.
  18221. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18222. * @return {string} The cache key.
  18223. */
  18224. _getComputeCacheKey( computeNode, stageCompute ) {
  18225. return computeNode.id + ',' + stageCompute.id;
  18226. }
  18227. /**
  18228. * Computes a cache key representing a render pipeline.
  18229. *
  18230. * @private
  18231. * @param {RenderObject} renderObject - The render object.
  18232. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18233. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18234. * @return {string} The cache key.
  18235. */
  18236. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  18237. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  18238. }
  18239. /**
  18240. * Releases the given pipeline.
  18241. *
  18242. * @private
  18243. * @param {Pipeline} pipeline - The pipeline to release.
  18244. */
  18245. _releasePipeline( pipeline ) {
  18246. this.caches.delete( pipeline.cacheKey );
  18247. }
  18248. /**
  18249. * Releases the shader program.
  18250. *
  18251. * @private
  18252. * @param {Object} program - The shader program to release.
  18253. */
  18254. _releaseProgram( program ) {
  18255. const code = program.code;
  18256. const stage = program.stage;
  18257. this.programs[ stage ].delete( code );
  18258. }
  18259. /**
  18260. * Returns `true` if the compute pipeline for the given compute node requires an update.
  18261. *
  18262. * @private
  18263. * @param {Node} computeNode - The compute node.
  18264. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  18265. */
  18266. _needsComputeUpdate( computeNode ) {
  18267. const data = this.get( computeNode );
  18268. return data.pipeline === undefined || data.version !== computeNode.version;
  18269. }
  18270. /**
  18271. * Returns `true` if the render pipeline for the given render object requires an update.
  18272. *
  18273. * @private
  18274. * @param {RenderObject} renderObject - The render object.
  18275. * @return {boolean} Whether the render object for the given render object requires an update or not.
  18276. */
  18277. _needsRenderUpdate( renderObject ) {
  18278. const data = this.get( renderObject );
  18279. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  18280. }
  18281. }
  18282. /**
  18283. * This renderer module manages the bindings of the renderer.
  18284. *
  18285. * @private
  18286. * @augments DataMap
  18287. */
  18288. class Bindings extends DataMap {
  18289. /**
  18290. * Constructs a new bindings management component.
  18291. *
  18292. * @param {Backend} backend - The renderer's backend.
  18293. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18294. * @param {Textures} textures - Renderer component for managing textures.
  18295. * @param {Attributes} attributes - Renderer component for managing attributes.
  18296. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18297. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18298. */
  18299. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  18300. super();
  18301. /**
  18302. * The renderer's backend.
  18303. *
  18304. * @type {Backend}
  18305. */
  18306. this.backend = backend;
  18307. /**
  18308. * Renderer component for managing textures.
  18309. *
  18310. * @type {Textures}
  18311. */
  18312. this.textures = textures;
  18313. /**
  18314. * Renderer component for managing pipelines.
  18315. *
  18316. * @type {Pipelines}
  18317. */
  18318. this.pipelines = pipelines;
  18319. /**
  18320. * Renderer component for managing attributes.
  18321. *
  18322. * @type {Attributes}
  18323. */
  18324. this.attributes = attributes;
  18325. /**
  18326. * Renderer component for managing nodes related logic.
  18327. *
  18328. * @type {Nodes}
  18329. */
  18330. this.nodes = nodes;
  18331. /**
  18332. * Renderer component for managing metrics and monitoring data.
  18333. *
  18334. * @type {Info}
  18335. */
  18336. this.info = info;
  18337. this.pipelines.bindings = this; // assign bindings to pipelines
  18338. }
  18339. /**
  18340. * Returns the bind groups for the given render object.
  18341. *
  18342. * @param {RenderObject} renderObject - The render object.
  18343. * @return {Array<BindGroup>} The bind groups.
  18344. */
  18345. getForRender( renderObject ) {
  18346. const bindings = renderObject.getBindings();
  18347. for ( const bindGroup of bindings ) {
  18348. const groupData = this.get( bindGroup );
  18349. if ( groupData.bindGroup === undefined ) {
  18350. // each object defines an array of bindings (ubos, textures, samplers etc.)
  18351. this._init( bindGroup );
  18352. this.backend.createBindings( bindGroup, bindings, 0 );
  18353. groupData.bindGroup = bindGroup;
  18354. }
  18355. }
  18356. return bindings;
  18357. }
  18358. /**
  18359. * Returns the bind groups for the given compute node.
  18360. *
  18361. * @param {Node} computeNode - The compute node.
  18362. * @return {Array<BindGroup>} The bind groups.
  18363. */
  18364. getForCompute( computeNode ) {
  18365. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  18366. for ( const bindGroup of bindings ) {
  18367. const groupData = this.get( bindGroup );
  18368. if ( groupData.bindGroup === undefined ) {
  18369. this._init( bindGroup );
  18370. this.backend.createBindings( bindGroup, bindings, 0 );
  18371. groupData.bindGroup = bindGroup;
  18372. }
  18373. }
  18374. return bindings;
  18375. }
  18376. /**
  18377. * Updates the bindings for the given compute node.
  18378. *
  18379. * @param {Node} computeNode - The compute node.
  18380. */
  18381. updateForCompute( computeNode ) {
  18382. this._updateBindings( this.getForCompute( computeNode ) );
  18383. }
  18384. /**
  18385. * Updates the bindings for the given render object.
  18386. *
  18387. * @param {RenderObject} renderObject - The render object.
  18388. */
  18389. updateForRender( renderObject ) {
  18390. this._updateBindings( this.getForRender( renderObject ) );
  18391. }
  18392. /**
  18393. * Updates the given array of bindings.
  18394. *
  18395. * @param {Array<BindGroup>} bindings - The bind groups.
  18396. */
  18397. _updateBindings( bindings ) {
  18398. for ( const bindGroup of bindings ) {
  18399. this._update( bindGroup, bindings );
  18400. }
  18401. }
  18402. /**
  18403. * Initializes the given bind group.
  18404. *
  18405. * @param {BindGroup} bindGroup - The bind group to initialize.
  18406. */
  18407. _init( bindGroup ) {
  18408. for ( const binding of bindGroup.bindings ) {
  18409. if ( binding.isSampledTexture ) {
  18410. this.textures.updateTexture( binding.texture );
  18411. } else if ( binding.isStorageBuffer ) {
  18412. const attribute = binding.attribute;
  18413. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  18414. this.attributes.update( attribute, attributeType );
  18415. }
  18416. }
  18417. }
  18418. /**
  18419. * Updates the given bind group.
  18420. *
  18421. * @param {BindGroup} bindGroup - The bind group to update.
  18422. * @param {Array<BindGroup>} bindings - The bind groups.
  18423. */
  18424. _update( bindGroup, bindings ) {
  18425. const { backend } = this;
  18426. let needsBindingsUpdate = false;
  18427. let cacheBindings = true;
  18428. let cacheIndex = 0;
  18429. let version = 0;
  18430. // iterate over all bindings and check if buffer updates or a new binding group is required
  18431. for ( const binding of bindGroup.bindings ) {
  18432. if ( binding.isNodeUniformsGroup ) {
  18433. const updated = this.nodes.updateGroup( binding );
  18434. // every uniforms group is a uniform buffer. So if no update is required,
  18435. // we move one with the next binding. Otherwise the next if block will update the group.
  18436. if ( updated === false ) continue;
  18437. }
  18438. if ( binding.isUniformBuffer ) {
  18439. const updated = binding.update();
  18440. if ( updated ) {
  18441. backend.updateBinding( binding );
  18442. }
  18443. } else if ( binding.isSampler ) {
  18444. binding.update();
  18445. } else if ( binding.isSampledTexture ) {
  18446. const texturesTextureData = this.textures.get( binding.texture );
  18447. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18448. const updated = binding.update();
  18449. const texture = binding.texture;
  18450. if ( updated ) {
  18451. this.textures.updateTexture( texture );
  18452. }
  18453. const textureData = backend.get( texture );
  18454. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18455. cacheBindings = false;
  18456. } else {
  18457. cacheIndex = cacheIndex * 10 + texture.id;
  18458. version += texture.version;
  18459. }
  18460. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18461. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18462. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18463. this.textures.updateTexture( texture );
  18464. needsBindingsUpdate = true;
  18465. }
  18466. if ( texture.isStorageTexture === true ) {
  18467. const textureData = this.get( texture );
  18468. if ( binding.store === true ) {
  18469. textureData.needsMipmap = true;
  18470. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18471. this.backend.generateMipmaps( texture );
  18472. textureData.needsMipmap = false;
  18473. }
  18474. }
  18475. }
  18476. }
  18477. if ( needsBindingsUpdate === true ) {
  18478. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18479. }
  18480. }
  18481. }
  18482. /**
  18483. * Default sorting function for opaque render items.
  18484. *
  18485. * @private
  18486. * @function
  18487. * @param {Object} a - The first render item.
  18488. * @param {Object} b - The second render item.
  18489. * @return {number} A numeric value which defines the sort order.
  18490. */
  18491. function painterSortStable( a, b ) {
  18492. if ( a.groupOrder !== b.groupOrder ) {
  18493. return a.groupOrder - b.groupOrder;
  18494. } else if ( a.renderOrder !== b.renderOrder ) {
  18495. return a.renderOrder - b.renderOrder;
  18496. } else if ( a.material.id !== b.material.id ) {
  18497. return a.material.id - b.material.id;
  18498. } else if ( a.z !== b.z ) {
  18499. return a.z - b.z;
  18500. } else {
  18501. return a.id - b.id;
  18502. }
  18503. }
  18504. /**
  18505. * Default sorting function for transparent render items.
  18506. *
  18507. * @private
  18508. * @function
  18509. * @param {Object} a - The first render item.
  18510. * @param {Object} b - The second render item.
  18511. * @return {number} A numeric value which defines the sort order.
  18512. */
  18513. function reversePainterSortStable( a, b ) {
  18514. if ( a.groupOrder !== b.groupOrder ) {
  18515. return a.groupOrder - b.groupOrder;
  18516. } else if ( a.renderOrder !== b.renderOrder ) {
  18517. return a.renderOrder - b.renderOrder;
  18518. } else if ( a.z !== b.z ) {
  18519. return b.z - a.z;
  18520. } else {
  18521. return a.id - b.id;
  18522. }
  18523. }
  18524. /**
  18525. * Returns `true` if the given transparent material requires a double pass.
  18526. *
  18527. * @private
  18528. * @function
  18529. * @param {Material} material - The transparent material.
  18530. * @return {boolean} Whether the given material requires a double pass or not.
  18531. */
  18532. function needsDoublePass( material ) {
  18533. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18534. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18535. }
  18536. /**
  18537. * When the renderer analyzes the scene at the beginning of a render call,
  18538. * it stores 3D object for further processing in render lists. Depending on the
  18539. * properties of a 3D objects (like their transformation or material state), the
  18540. * objects are maintained in ordered lists for the actual rendering.
  18541. *
  18542. * Render lists are unique per scene and camera combination.
  18543. *
  18544. * @private
  18545. * @augments Pipeline
  18546. */
  18547. class RenderList {
  18548. /**
  18549. * Constructs a render list.
  18550. *
  18551. * @param {Lighting} lighting - The lighting management component.
  18552. * @param {Scene} scene - The scene.
  18553. * @param {Camera} camera - The camera the scene is rendered with.
  18554. */
  18555. constructor( lighting, scene, camera ) {
  18556. /**
  18557. * 3D objects are transformed into render items and stored in this array.
  18558. *
  18559. * @type {Array<Object>}
  18560. */
  18561. this.renderItems = [];
  18562. /**
  18563. * The current render items index.
  18564. *
  18565. * @type {number}
  18566. * @default 0
  18567. */
  18568. this.renderItemsIndex = 0;
  18569. /**
  18570. * A list with opaque render items.
  18571. *
  18572. * @type {Array<Object>}
  18573. */
  18574. this.opaque = [];
  18575. /**
  18576. * A list with transparent render items which require
  18577. * double pass rendering (e.g. transmissive objects).
  18578. *
  18579. * @type {Array<Object>}
  18580. */
  18581. this.transparentDoublePass = [];
  18582. /**
  18583. * A list with transparent render items.
  18584. *
  18585. * @type {Array<Object>}
  18586. */
  18587. this.transparent = [];
  18588. /**
  18589. * A list with transparent render bundle data.
  18590. *
  18591. * @type {Array<Object>}
  18592. */
  18593. this.bundles = [];
  18594. /**
  18595. * The render list's lights node. This node is later
  18596. * relevant for the actual analytical light nodes which
  18597. * compute the scene's lighting in the shader.
  18598. *
  18599. * @type {LightsNode}
  18600. */
  18601. this.lightsNode = lighting.getNode( scene, camera );
  18602. /**
  18603. * The scene's lights stored in an array. This array
  18604. * is used to setup the lights node.
  18605. *
  18606. * @type {Array<Light>}
  18607. */
  18608. this.lightsArray = [];
  18609. /**
  18610. * The scene.
  18611. *
  18612. * @type {Scene}
  18613. */
  18614. this.scene = scene;
  18615. /**
  18616. * The camera the scene is rendered with.
  18617. *
  18618. * @type {Camera}
  18619. */
  18620. this.camera = camera;
  18621. /**
  18622. * How many objects perform occlusion query tests.
  18623. *
  18624. * @type {number}
  18625. * @default 0
  18626. */
  18627. this.occlusionQueryCount = 0;
  18628. }
  18629. /**
  18630. * This method is called right at the beginning of a render call
  18631. * before the scene is analyzed. It prepares the internal data
  18632. * structures for the upcoming render lists generation.
  18633. *
  18634. * @return {RenderList} A reference to this render list.
  18635. */
  18636. begin() {
  18637. this.renderItemsIndex = 0;
  18638. this.opaque.length = 0;
  18639. this.transparentDoublePass.length = 0;
  18640. this.transparent.length = 0;
  18641. this.bundles.length = 0;
  18642. this.lightsArray.length = 0;
  18643. this.occlusionQueryCount = 0;
  18644. return this;
  18645. }
  18646. /**
  18647. * Returns a render item for the giving render item state. The state is defined
  18648. * by a series of object-related parameters.
  18649. *
  18650. * The method avoids object creation by holding render items and reusing them in
  18651. * subsequent render calls (just with different property values).
  18652. *
  18653. * @param {Object3D} object - The 3D object.
  18654. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18655. * @param {Material} material - The 3D object's material.
  18656. * @param {number} groupOrder - The current group order.
  18657. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18658. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18659. * @param {ClippingContext} clippingContext - The current clipping context.
  18660. * @return {Object} The render item.
  18661. */
  18662. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18663. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18664. if ( renderItem === undefined ) {
  18665. renderItem = {
  18666. id: object.id,
  18667. object: object,
  18668. geometry: geometry,
  18669. material: material,
  18670. groupOrder: groupOrder,
  18671. renderOrder: object.renderOrder,
  18672. z: z,
  18673. group: group,
  18674. clippingContext: clippingContext
  18675. };
  18676. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18677. } else {
  18678. renderItem.id = object.id;
  18679. renderItem.object = object;
  18680. renderItem.geometry = geometry;
  18681. renderItem.material = material;
  18682. renderItem.groupOrder = groupOrder;
  18683. renderItem.renderOrder = object.renderOrder;
  18684. renderItem.z = z;
  18685. renderItem.group = group;
  18686. renderItem.clippingContext = clippingContext;
  18687. }
  18688. this.renderItemsIndex ++;
  18689. return renderItem;
  18690. }
  18691. /**
  18692. * Pushes the given object as a render item to the internal render lists.
  18693. * The selected lists depend on the object properties.
  18694. *
  18695. * @param {Object3D} object - The 3D object.
  18696. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18697. * @param {Material} material - The 3D object's material.
  18698. * @param {number} groupOrder - The current group order.
  18699. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18700. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18701. * @param {ClippingContext} clippingContext - The current clipping context.
  18702. */
  18703. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18704. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18705. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18706. if ( material.transparent === true || material.transmission > 0 ) {
  18707. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18708. this.transparent.push( renderItem );
  18709. } else {
  18710. this.opaque.push( renderItem );
  18711. }
  18712. }
  18713. /**
  18714. * Inserts the given object as a render item at the start of the internal render lists.
  18715. * The selected lists depend on the object properties.
  18716. *
  18717. * @param {Object3D} object - The 3D object.
  18718. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18719. * @param {Material} material - The 3D object's material.
  18720. * @param {number} groupOrder - The current group order.
  18721. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18722. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18723. * @param {ClippingContext} clippingContext - The current clipping context.
  18724. */
  18725. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18726. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18727. if ( material.transparent === true || material.transmission > 0 ) {
  18728. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18729. this.transparent.unshift( renderItem );
  18730. } else {
  18731. this.opaque.unshift( renderItem );
  18732. }
  18733. }
  18734. /**
  18735. * Pushes render bundle group data into the render list.
  18736. *
  18737. * @param {Object} group - Bundle group data.
  18738. */
  18739. pushBundle( group ) {
  18740. this.bundles.push( group );
  18741. }
  18742. /**
  18743. * Pushes a light into the render list.
  18744. *
  18745. * @param {Light} light - The light.
  18746. */
  18747. pushLight( light ) {
  18748. this.lightsArray.push( light );
  18749. }
  18750. /**
  18751. * Sorts the internal render lists.
  18752. *
  18753. * @param {function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  18754. * @param {function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  18755. */
  18756. sort( customOpaqueSort, customTransparentSort ) {
  18757. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18758. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18759. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18760. }
  18761. /**
  18762. * This method performs finalizing tasks right after the render lists
  18763. * have been generated.
  18764. */
  18765. finish() {
  18766. // update lights
  18767. this.lightsNode.setLights( this.lightsArray );
  18768. // Clear references from inactive renderItems in the list
  18769. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18770. const renderItem = this.renderItems[ i ];
  18771. if ( renderItem.id === null ) break;
  18772. renderItem.id = null;
  18773. renderItem.object = null;
  18774. renderItem.geometry = null;
  18775. renderItem.material = null;
  18776. renderItem.groupOrder = null;
  18777. renderItem.renderOrder = null;
  18778. renderItem.z = null;
  18779. renderItem.group = null;
  18780. renderItem.clippingContext = null;
  18781. }
  18782. }
  18783. }
  18784. const _chainKeys$4 = [];
  18785. /**
  18786. * This renderer module manages the render lists which are unique
  18787. * per scene and camera combination.
  18788. *
  18789. * @private
  18790. */
  18791. class RenderLists {
  18792. /**
  18793. * Constructs a render lists management component.
  18794. *
  18795. * @param {Lighting} lighting - The lighting management component.
  18796. */
  18797. constructor( lighting ) {
  18798. /**
  18799. * The lighting management component.
  18800. *
  18801. * @type {Lighting}
  18802. */
  18803. this.lighting = lighting;
  18804. /**
  18805. * The internal chain map which holds the render lists.
  18806. *
  18807. * @type {ChainMap}
  18808. */
  18809. this.lists = new ChainMap();
  18810. }
  18811. /**
  18812. * Returns a render list for the given scene and camera.
  18813. *
  18814. * @param {Scene} scene - The scene.
  18815. * @param {Camera} camera - The camera.
  18816. * @return {RenderList} The render list.
  18817. */
  18818. get( scene, camera ) {
  18819. const lists = this.lists;
  18820. _chainKeys$4[ 0 ] = scene;
  18821. _chainKeys$4[ 1 ] = camera;
  18822. let list = lists.get( _chainKeys$4 );
  18823. if ( list === undefined ) {
  18824. list = new RenderList( this.lighting, scene, camera );
  18825. lists.set( _chainKeys$4, list );
  18826. }
  18827. _chainKeys$4.length = 0;
  18828. return list;
  18829. }
  18830. /**
  18831. * Frees all internal resources.
  18832. */
  18833. dispose() {
  18834. this.lists = new ChainMap();
  18835. }
  18836. }
  18837. let _id$7 = 0;
  18838. /**
  18839. * Any render or compute command is executed in a specific context that defines
  18840. * the state of the renderer and its backend. Typical examples for such context
  18841. * data are the current clear values or data from the active framebuffer. This
  18842. * module is used to represent these contexts as objects.
  18843. *
  18844. * @private
  18845. */
  18846. class RenderContext {
  18847. /**
  18848. * Constructs a new render context.
  18849. */
  18850. constructor() {
  18851. /**
  18852. * The context's ID.
  18853. *
  18854. * @type {number}
  18855. */
  18856. this.id = _id$7 ++;
  18857. /**
  18858. * Whether the current active framebuffer has a color attachment.
  18859. *
  18860. * @type {boolean}
  18861. * @default true
  18862. */
  18863. this.color = true;
  18864. /**
  18865. * Whether the color attachment should be cleared or not.
  18866. *
  18867. * @type {boolean}
  18868. * @default true
  18869. */
  18870. this.clearColor = true;
  18871. /**
  18872. * The clear color value.
  18873. *
  18874. * @type {Object}
  18875. * @default true
  18876. */
  18877. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18878. /**
  18879. * Whether the current active framebuffer has a depth attachment.
  18880. *
  18881. * @type {boolean}
  18882. * @default true
  18883. */
  18884. this.depth = true;
  18885. /**
  18886. * Whether the depth attachment should be cleared or not.
  18887. *
  18888. * @type {boolean}
  18889. * @default true
  18890. */
  18891. this.clearDepth = true;
  18892. /**
  18893. * The clear depth value.
  18894. *
  18895. * @type {number}
  18896. * @default 1
  18897. */
  18898. this.clearDepthValue = 1;
  18899. /**
  18900. * Whether the current active framebuffer has a stencil attachment.
  18901. *
  18902. * @type {boolean}
  18903. * @default false
  18904. */
  18905. this.stencil = false;
  18906. /**
  18907. * Whether the stencil attachment should be cleared or not.
  18908. *
  18909. * @type {boolean}
  18910. * @default true
  18911. */
  18912. this.clearStencil = true;
  18913. /**
  18914. * The clear stencil value.
  18915. *
  18916. * @type {number}
  18917. * @default 1
  18918. */
  18919. this.clearStencilValue = 1;
  18920. /**
  18921. * By default the viewport encloses the entire framebuffer If a smaller
  18922. * viewport is manually defined, this property is to `true` by the renderer.
  18923. *
  18924. * @type {boolean}
  18925. * @default false
  18926. */
  18927. this.viewport = false;
  18928. /**
  18929. * The viewport value. This value is in physical pixels meaning it incorporates
  18930. * the renderer's pixel ratio. The viewport property of render targets or
  18931. * the renderer is in logical pixels.
  18932. *
  18933. * @type {Vector4}
  18934. */
  18935. this.viewportValue = new Vector4();
  18936. /**
  18937. * When the scissor test is active and scissor rectangle smaller than the
  18938. * framebuffers dimensions, this property is to `true` by the renderer.
  18939. *
  18940. * @type {boolean}
  18941. * @default false
  18942. */
  18943. this.scissor = false;
  18944. /**
  18945. * The scissor rectangle.
  18946. *
  18947. * @type {Vector4}
  18948. */
  18949. this.scissorValue = new Vector4();
  18950. /**
  18951. * The active render target.
  18952. *
  18953. * @type {?RenderTarget}
  18954. * @default null
  18955. */
  18956. this.renderTarget = null;
  18957. /**
  18958. * The textures of the active render target.
  18959. * `null` when no render target is set.
  18960. *
  18961. * @type {?Array<Texture>}
  18962. * @default null
  18963. */
  18964. this.textures = null;
  18965. /**
  18966. * The depth texture of the active render target.
  18967. * `null` when no render target is set.
  18968. *
  18969. * @type {?DepthTexture}
  18970. * @default null
  18971. */
  18972. this.depthTexture = null;
  18973. /**
  18974. * The active cube face.
  18975. *
  18976. * @type {number}
  18977. * @default 0
  18978. */
  18979. this.activeCubeFace = 0;
  18980. /**
  18981. * The active mipmap level.
  18982. *
  18983. * @type {number}
  18984. * @default 0
  18985. */
  18986. this.activeMipmapLevel = 0;
  18987. /**
  18988. * The number of MSAA samples. This value is always `1` when
  18989. * MSAA isn't used.
  18990. *
  18991. * @type {number}
  18992. * @default 1
  18993. */
  18994. this.sampleCount = 1;
  18995. /**
  18996. * The active render target's width in physical pixels.
  18997. *
  18998. * @type {number}
  18999. * @default 0
  19000. */
  19001. this.width = 0;
  19002. /**
  19003. * The active render target's height in physical pixels.
  19004. *
  19005. * @type {number}
  19006. * @default 0
  19007. */
  19008. this.height = 0;
  19009. /**
  19010. * The occlusion query count.
  19011. *
  19012. * @type {number}
  19013. * @default 0
  19014. */
  19015. this.occlusionQueryCount = 0;
  19016. /**
  19017. * The current clipping context.
  19018. *
  19019. * @type {?ClippingContext}
  19020. * @default null
  19021. */
  19022. this.clippingContext = null;
  19023. /**
  19024. * This flag can be used for type testing.
  19025. *
  19026. * @type {boolean}
  19027. * @readonly
  19028. * @default true
  19029. */
  19030. this.isRenderContext = true;
  19031. }
  19032. /**
  19033. * Returns the cache key of this render context.
  19034. *
  19035. * @return {number} The cache key.
  19036. */
  19037. getCacheKey() {
  19038. return getCacheKey( this );
  19039. }
  19040. }
  19041. /**
  19042. * Computes a cache key for the given render context. This key
  19043. * should identify the render target state so it is possible to
  19044. * configure the correct attachments in the respective backend.
  19045. *
  19046. * @param {RenderContext} renderContext - The render context.
  19047. * @return {number} The cache key.
  19048. */
  19049. function getCacheKey( renderContext ) {
  19050. const { textures, activeCubeFace } = renderContext;
  19051. const values = [ activeCubeFace ];
  19052. for ( const texture of textures ) {
  19053. values.push( texture.id );
  19054. }
  19055. return hashArray( values );
  19056. }
  19057. const _chainKeys$3 = [];
  19058. const _defaultScene = /*@__PURE__*/ new Scene();
  19059. const _defaultCamera = /*@__PURE__*/ new Camera();
  19060. /**
  19061. * This module manages the render contexts of the renderer.
  19062. *
  19063. * @private
  19064. */
  19065. class RenderContexts {
  19066. /**
  19067. * Constructs a new render context management component.
  19068. */
  19069. constructor() {
  19070. /**
  19071. * A dictionary that manages render contexts in chain maps
  19072. * for each attachment state.
  19073. *
  19074. * @type {Object<string,ChainMap>}
  19075. */
  19076. this.chainMaps = {};
  19077. }
  19078. /**
  19079. * Returns a render context for the given scene, camera and render target.
  19080. *
  19081. * @param {Scene} scene - The scene.
  19082. * @param {Camera} camera - The camera that is used to render the scene.
  19083. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19084. * @return {RenderContext} The render context.
  19085. */
  19086. get( scene, camera, renderTarget = null ) {
  19087. _chainKeys$3[ 0 ] = scene;
  19088. _chainKeys$3[ 1 ] = camera;
  19089. let attachmentState;
  19090. if ( renderTarget === null ) {
  19091. attachmentState = 'default';
  19092. } else {
  19093. const format = renderTarget.texture.format;
  19094. const count = renderTarget.textures.length;
  19095. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  19096. }
  19097. const chainMap = this._getChainMap( attachmentState );
  19098. let renderState = chainMap.get( _chainKeys$3 );
  19099. if ( renderState === undefined ) {
  19100. renderState = new RenderContext();
  19101. chainMap.set( _chainKeys$3, renderState );
  19102. }
  19103. _chainKeys$3.length = 0;
  19104. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19105. return renderState;
  19106. }
  19107. /**
  19108. * Returns a render context intended for clear operations.
  19109. *
  19110. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19111. * @return {RenderContext} The render context.
  19112. */
  19113. getForClear( renderTarget = null ) {
  19114. return this.get( _defaultScene, _defaultCamera, renderTarget );
  19115. }
  19116. /**
  19117. * Returns a chain map for the given attachment state.
  19118. *
  19119. * @private
  19120. * @param {string} attachmentState - The attachment state.
  19121. * @return {ChainMap} The chain map.
  19122. */
  19123. _getChainMap( attachmentState ) {
  19124. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  19125. }
  19126. /**
  19127. * Frees internal resources.
  19128. */
  19129. dispose() {
  19130. this.chainMaps = {};
  19131. }
  19132. }
  19133. const _size$3 = /*@__PURE__*/ new Vector3();
  19134. /**
  19135. * This module manages the textures of the renderer.
  19136. *
  19137. * @private
  19138. * @augments DataMap
  19139. */
  19140. class Textures extends DataMap {
  19141. /**
  19142. * Constructs a new texture management component.
  19143. *
  19144. * @param {Renderer} renderer - The renderer.
  19145. * @param {Backend} backend - The renderer's backend.
  19146. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19147. */
  19148. constructor( renderer, backend, info ) {
  19149. super();
  19150. /**
  19151. * The renderer.
  19152. *
  19153. * @type {Renderer}
  19154. */
  19155. this.renderer = renderer;
  19156. /**
  19157. * The backend.
  19158. *
  19159. * @type {Backend}
  19160. */
  19161. this.backend = backend;
  19162. /**
  19163. * Renderer component for managing metrics and monitoring data.
  19164. *
  19165. * @type {Info}
  19166. */
  19167. this.info = info;
  19168. }
  19169. /**
  19170. * Updates the given render target. Based on the given render target configuration,
  19171. * it updates the texture states representing the attachments of the framebuffer.
  19172. *
  19173. * @param {RenderTarget} renderTarget - The render target to update.
  19174. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  19175. */
  19176. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  19177. const renderTargetData = this.get( renderTarget );
  19178. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19179. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  19180. const textures = renderTarget.textures;
  19181. const size = this.getSize( textures[ 0 ] );
  19182. const mipWidth = size.width >> activeMipmapLevel;
  19183. const mipHeight = size.height >> activeMipmapLevel;
  19184. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  19185. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  19186. let textureNeedsUpdate = false;
  19187. if ( depthTexture === undefined && useDepthTexture ) {
  19188. depthTexture = new DepthTexture();
  19189. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  19190. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  19191. depthTexture.image.width = mipWidth;
  19192. depthTexture.image.height = mipHeight;
  19193. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  19194. }
  19195. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  19196. textureNeedsUpdate = true;
  19197. if ( depthTexture ) {
  19198. depthTexture.needsUpdate = true;
  19199. depthTexture.image.width = mipWidth;
  19200. depthTexture.image.height = mipHeight;
  19201. }
  19202. }
  19203. renderTargetData.width = size.width;
  19204. renderTargetData.height = size.height;
  19205. renderTargetData.textures = textures;
  19206. renderTargetData.depthTexture = depthTexture || null;
  19207. renderTargetData.depth = renderTarget.depthBuffer;
  19208. renderTargetData.stencil = renderTarget.stencilBuffer;
  19209. renderTargetData.renderTarget = renderTarget;
  19210. if ( renderTargetData.sampleCount !== sampleCount ) {
  19211. textureNeedsUpdate = true;
  19212. if ( depthTexture ) {
  19213. depthTexture.needsUpdate = true;
  19214. }
  19215. renderTargetData.sampleCount = sampleCount;
  19216. }
  19217. //
  19218. const options = { sampleCount };
  19219. // XR render targets require no texture updates
  19220. if ( renderTarget.isXRRenderTarget !== true ) {
  19221. for ( let i = 0; i < textures.length; i ++ ) {
  19222. const texture = textures[ i ];
  19223. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  19224. this.updateTexture( texture, options );
  19225. }
  19226. if ( depthTexture ) {
  19227. this.updateTexture( depthTexture, options );
  19228. }
  19229. }
  19230. // dispose handler
  19231. if ( renderTargetData.initialized !== true ) {
  19232. renderTargetData.initialized = true;
  19233. // dispose
  19234. const onDispose = () => {
  19235. renderTarget.removeEventListener( 'dispose', onDispose );
  19236. for ( let i = 0; i < textures.length; i ++ ) {
  19237. this._destroyTexture( textures[ i ] );
  19238. }
  19239. if ( depthTexture ) {
  19240. this._destroyTexture( depthTexture );
  19241. }
  19242. this.delete( renderTarget );
  19243. };
  19244. renderTarget.addEventListener( 'dispose', onDispose );
  19245. }
  19246. }
  19247. /**
  19248. * Updates the given texture. Depending on the texture state, this method
  19249. * triggers the upload of texture data to the GPU memory. If the texture data are
  19250. * not yet ready for the upload, it uses default texture data for as a placeholder.
  19251. *
  19252. * @param {Texture} texture - The texture to update.
  19253. * @param {Object} [options={}] - The options.
  19254. */
  19255. updateTexture( texture, options = {} ) {
  19256. const textureData = this.get( texture );
  19257. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  19258. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  19259. const backend = this.backend;
  19260. if ( isRenderTarget && textureData.initialized === true ) {
  19261. // it's an update
  19262. backend.destroySampler( texture );
  19263. backend.destroyTexture( texture );
  19264. }
  19265. //
  19266. if ( texture.isFramebufferTexture ) {
  19267. const renderTarget = this.renderer.getRenderTarget();
  19268. if ( renderTarget ) {
  19269. texture.type = renderTarget.texture.type;
  19270. } else {
  19271. texture.type = UnsignedByteType;
  19272. }
  19273. }
  19274. //
  19275. const { width, height, depth } = this.getSize( texture );
  19276. options.width = width;
  19277. options.height = height;
  19278. options.depth = depth;
  19279. options.needsMipmaps = this.needsMipmaps( texture );
  19280. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  19281. //
  19282. if ( isRenderTarget || texture.isStorageTexture === true ) {
  19283. backend.createSampler( texture );
  19284. backend.createTexture( texture, options );
  19285. textureData.generation = texture.version;
  19286. } else {
  19287. const needsCreate = textureData.initialized !== true;
  19288. if ( needsCreate ) backend.createSampler( texture );
  19289. if ( texture.version > 0 ) {
  19290. const image = texture.image;
  19291. if ( image === undefined ) {
  19292. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  19293. } else if ( image.complete === false ) {
  19294. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  19295. } else {
  19296. if ( texture.images ) {
  19297. const images = [];
  19298. for ( const image of texture.images ) {
  19299. images.push( image );
  19300. }
  19301. options.images = images;
  19302. } else {
  19303. options.image = image;
  19304. }
  19305. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  19306. backend.createTexture( texture, options );
  19307. textureData.isDefaultTexture = false;
  19308. textureData.generation = texture.version;
  19309. }
  19310. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  19311. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  19312. }
  19313. } else {
  19314. // async update
  19315. backend.createDefaultTexture( texture );
  19316. textureData.isDefaultTexture = true;
  19317. textureData.generation = texture.version;
  19318. }
  19319. }
  19320. // dispose handler
  19321. if ( textureData.initialized !== true ) {
  19322. textureData.initialized = true;
  19323. textureData.generation = texture.version;
  19324. //
  19325. this.info.memory.textures ++;
  19326. // dispose
  19327. const onDispose = () => {
  19328. texture.removeEventListener( 'dispose', onDispose );
  19329. this._destroyTexture( texture );
  19330. this.info.memory.textures --;
  19331. };
  19332. texture.addEventListener( 'dispose', onDispose );
  19333. }
  19334. //
  19335. textureData.version = texture.version;
  19336. }
  19337. /**
  19338. * Computes the size of the given texture and writes the result
  19339. * into the target vector. This vector is also returned by the
  19340. * method.
  19341. *
  19342. * If no texture data are available for the compute yet, the method
  19343. * returns default size values.
  19344. *
  19345. * @param {Texture} texture - The texture to compute the size for.
  19346. * @param {Vector3} target - The target vector.
  19347. * @return {Vector3} The target vector.
  19348. */
  19349. getSize( texture, target = _size$3 ) {
  19350. let image = texture.images ? texture.images[ 0 ] : texture.image;
  19351. if ( image ) {
  19352. if ( image.image !== undefined ) image = image.image;
  19353. target.width = image.width || 1;
  19354. target.height = image.height || 1;
  19355. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  19356. } else {
  19357. target.width = target.height = target.depth = 1;
  19358. }
  19359. return target;
  19360. }
  19361. /**
  19362. * Computes the number of mipmap levels for the given texture.
  19363. *
  19364. * @param {Texture} texture - The texture.
  19365. * @param {number} width - The texture's width.
  19366. * @param {number} height - The texture's height.
  19367. * @return {number} The number of mipmap levels.
  19368. */
  19369. getMipLevels( texture, width, height ) {
  19370. let mipLevelCount;
  19371. if ( texture.isCompressedTexture ) {
  19372. if ( texture.mipmaps ) {
  19373. mipLevelCount = texture.mipmaps.length;
  19374. } else {
  19375. mipLevelCount = 1;
  19376. }
  19377. } else {
  19378. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  19379. }
  19380. return mipLevelCount;
  19381. }
  19382. /**
  19383. * Returns `true` if the given texture requires mipmaps.
  19384. *
  19385. * @param {Texture} texture - The texture.
  19386. * @return {boolean} Whether mipmaps are required or not.
  19387. */
  19388. needsMipmaps( texture ) {
  19389. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  19390. }
  19391. /**
  19392. * Returns `true` if the given texture is an environment map.
  19393. *
  19394. * @param {Texture} texture - The texture.
  19395. * @return {boolean} Whether the given texture is an environment map or not.
  19396. */
  19397. isEnvironmentTexture( texture ) {
  19398. const mapping = texture.mapping;
  19399. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  19400. }
  19401. /**
  19402. * Frees internal resource when the given texture isn't
  19403. * required anymore.
  19404. *
  19405. * @param {Texture} texture - The texture to destroy.
  19406. */
  19407. _destroyTexture( texture ) {
  19408. this.backend.destroySampler( texture );
  19409. this.backend.destroyTexture( texture );
  19410. this.delete( texture );
  19411. }
  19412. }
  19413. /**
  19414. * A four-component version of {@link Color} which is internally
  19415. * used by the renderer to represents clear color with alpha as
  19416. * one object.
  19417. *
  19418. * @private
  19419. * @augments Color
  19420. */
  19421. class Color4 extends Color {
  19422. /**
  19423. * Constructs a new four-component color.
  19424. * You can also pass a single THREE.Color, hex or
  19425. * string argument to this constructor.
  19426. *
  19427. * @param {number|string} [r=1] - The red value.
  19428. * @param {number} [g=1] - The green value.
  19429. * @param {number} [b=1] - The blue value.
  19430. * @param {number} [a=1] - The alpha value.
  19431. */
  19432. constructor( r, g, b, a = 1 ) {
  19433. super( r, g, b );
  19434. this.a = a;
  19435. }
  19436. /**
  19437. * Overwrites the default to honor alpha.
  19438. * You can also pass a single THREE.Color, hex or
  19439. * string argument to this method.
  19440. *
  19441. * @param {number|string} r - The red value.
  19442. * @param {number} g - The green value.
  19443. * @param {number} b - The blue value.
  19444. * @param {number} [a=1] - The alpha value.
  19445. * @return {Color4} A reference to this object.
  19446. */
  19447. set( r, g, b, a = 1 ) {
  19448. this.a = a;
  19449. return super.set( r, g, b );
  19450. }
  19451. /**
  19452. * Overwrites the default to honor alpha.
  19453. *
  19454. * @param {Color4} color - The color to copy.
  19455. * @return {Color4} A reference to this object.
  19456. */
  19457. copy( color ) {
  19458. if ( color.a !== undefined ) this.a = color.a;
  19459. return super.copy( color );
  19460. }
  19461. /**
  19462. * Overwrites the default to honor alpha.
  19463. *
  19464. * @return {Color4} The cloned color.
  19465. */
  19466. clone() {
  19467. return new this.constructor( this.r, this.g, this.b, this.a );
  19468. }
  19469. }
  19470. /**
  19471. * Special version of {@link PropertyNode} which is used for parameters.
  19472. *
  19473. * @augments PropertyNode
  19474. */
  19475. class ParameterNode extends PropertyNode {
  19476. static get type() {
  19477. return 'ParameterNode';
  19478. }
  19479. /**
  19480. * Constructs a new parameter node.
  19481. *
  19482. * @param {string} nodeType - The type of the node.
  19483. * @param {?string} [name=null] - The name of the parameter in the shader.
  19484. */
  19485. constructor( nodeType, name = null ) {
  19486. super( nodeType, name );
  19487. /**
  19488. * This flag can be used for type testing.
  19489. *
  19490. * @type {boolean}
  19491. * @readonly
  19492. * @default true
  19493. */
  19494. this.isParameterNode = true;
  19495. }
  19496. getHash() {
  19497. return this.uuid;
  19498. }
  19499. generate() {
  19500. return this.name;
  19501. }
  19502. }
  19503. /**
  19504. * TSL function for creating a parameter node.
  19505. *
  19506. * @tsl
  19507. * @function
  19508. * @param {string} type - The type of the node.
  19509. * @param {?string} name - The name of the parameter in the shader.
  19510. * @returns {ParameterNode}
  19511. */
  19512. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19513. /**
  19514. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19515. * They are usually needed in cases like `If`, `Else`.
  19516. *
  19517. * @augments Node
  19518. */
  19519. class StackNode extends Node {
  19520. static get type() {
  19521. return 'StackNode';
  19522. }
  19523. /**
  19524. * Constructs a new stack node.
  19525. *
  19526. * @param {?StackNode} [parent=null] - The parent stack node.
  19527. */
  19528. constructor( parent = null ) {
  19529. super();
  19530. /**
  19531. * List of nodes.
  19532. *
  19533. * @type {Array<Node>}
  19534. */
  19535. this.nodes = [];
  19536. /**
  19537. * The output node.
  19538. *
  19539. * @type {?Node}
  19540. * @default null
  19541. */
  19542. this.outputNode = null;
  19543. /**
  19544. * The parent stack node.
  19545. *
  19546. * @type {?StackNode}
  19547. * @default null
  19548. */
  19549. this.parent = parent;
  19550. /**
  19551. * The current conditional node.
  19552. *
  19553. * @private
  19554. * @type {ConditionalNode}
  19555. * @default null
  19556. */
  19557. this._currentCond = null;
  19558. /**
  19559. * This flag can be used for type testing.
  19560. *
  19561. * @type {boolean}
  19562. * @readonly
  19563. * @default true
  19564. */
  19565. this.isStackNode = true;
  19566. }
  19567. getNodeType( builder ) {
  19568. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19569. }
  19570. getMemberType( builder, name ) {
  19571. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  19572. }
  19573. /**
  19574. * Adds a node to this stack.
  19575. *
  19576. * @param {Node} node - The node to add.
  19577. * @return {StackNode} A reference to this stack node.
  19578. */
  19579. add( node ) {
  19580. this.nodes.push( node );
  19581. return this;
  19582. }
  19583. /**
  19584. * Represent an `if` statement in TSL.
  19585. *
  19586. * @param {Node} boolNode - Represents the condition.
  19587. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19588. * @return {StackNode} A reference to this stack node.
  19589. */
  19590. If( boolNode, method ) {
  19591. const methodNode = new ShaderNode( method );
  19592. this._currentCond = select( boolNode, methodNode );
  19593. return this.add( this._currentCond );
  19594. }
  19595. /**
  19596. * Represent an `elseif` statement in TSL.
  19597. *
  19598. * @param {Node} boolNode - Represents the condition.
  19599. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19600. * @return {StackNode} A reference to this stack node.
  19601. */
  19602. ElseIf( boolNode, method ) {
  19603. const methodNode = new ShaderNode( method );
  19604. const ifNode = select( boolNode, methodNode );
  19605. this._currentCond.elseNode = ifNode;
  19606. this._currentCond = ifNode;
  19607. return this;
  19608. }
  19609. /**
  19610. * Represent an `else` statement in TSL.
  19611. *
  19612. * @param {Function} method - TSL code which is executed in the `else` case.
  19613. * @return {StackNode} A reference to this stack node.
  19614. */
  19615. Else( method ) {
  19616. this._currentCond.elseNode = new ShaderNode( method );
  19617. return this;
  19618. }
  19619. build( builder, ...params ) {
  19620. const previousStack = getCurrentStack();
  19621. setCurrentStack( this );
  19622. for ( const node of this.nodes ) {
  19623. node.build( builder, 'void' );
  19624. }
  19625. setCurrentStack( previousStack );
  19626. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19627. }
  19628. // Deprecated
  19629. /**
  19630. * @function
  19631. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19632. *
  19633. * @param {...any} params
  19634. * @returns {StackNode}
  19635. */
  19636. else( ...params ) { // @deprecated, r168
  19637. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19638. return this.Else( ...params );
  19639. }
  19640. /**
  19641. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19642. *
  19643. * @param {...any} params
  19644. * @returns {StackNode}
  19645. */
  19646. elseif( ...params ) { // @deprecated, r168
  19647. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19648. return this.ElseIf( ...params );
  19649. }
  19650. }
  19651. /**
  19652. * TSL function for creating a stack node.
  19653. *
  19654. * @tsl
  19655. * @function
  19656. * @param {?StackNode} [parent=null] - The parent stack node.
  19657. * @returns {StackNode}
  19658. */
  19659. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19660. /**
  19661. * Generates a layout for struct members.
  19662. * This function takes an object representing struct members and returns an array of member layouts.
  19663. * Each member layout includes the member's name, type, and whether it is atomic.
  19664. *
  19665. * @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.
  19666. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  19667. */
  19668. function getMembersLayout( members ) {
  19669. return Object.entries( members ).map( ( [ name, value ] ) => {
  19670. if ( typeof value === 'string' ) {
  19671. return { name, type: value, atomic: false };
  19672. }
  19673. return { name, type: value.type, atomic: value.atomic || false };
  19674. } );
  19675. }
  19676. /**
  19677. * Represents a struct type node in the node-based system.
  19678. * This class is used to define and manage the layout and types of struct members.
  19679. * It extends the base Node class and provides methods to get the length of the struct,
  19680. * retrieve member types, and generate the struct type for a builder.
  19681. *
  19682. * @augments Node
  19683. */
  19684. class StructTypeNode extends Node {
  19685. static get type() {
  19686. return 'StructTypeNode';
  19687. }
  19688. /**
  19689. * Creates an instance of StructTypeNode.
  19690. *
  19691. * @param {Object} membersLayout - The layout of the members for the struct.
  19692. * @param {string} [name=null] - The optional name of the struct.
  19693. */
  19694. constructor( membersLayout, name = null ) {
  19695. super( 'struct' );
  19696. /**
  19697. * The layout of the members for the struct
  19698. *
  19699. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  19700. */
  19701. this.membersLayout = getMembersLayout( membersLayout );
  19702. /**
  19703. * The name of the struct.
  19704. *
  19705. * @type {string}
  19706. * @default null
  19707. */
  19708. this.name = name;
  19709. /**
  19710. * This flag can be used for type testing.
  19711. *
  19712. * @type {boolean}
  19713. * @readonly
  19714. * @default true
  19715. */
  19716. this.isStructLayoutNode = true;
  19717. }
  19718. /**
  19719. * Returns the length of the struct.
  19720. * The length is calculated by summing the lengths of the struct's members.
  19721. *
  19722. * @returns {number} The length of the struct.
  19723. */
  19724. getLength() {
  19725. let length = 0;
  19726. for ( const member of this.membersLayout ) {
  19727. length += getLengthFromType( member.type );
  19728. }
  19729. return length;
  19730. }
  19731. getMemberType( builder, name ) {
  19732. const member = this.membersLayout.find( m => m.name === name );
  19733. return member ? member.type : 'void';
  19734. }
  19735. getNodeType( builder ) {
  19736. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  19737. return structType.name;
  19738. }
  19739. setup( builder ) {
  19740. builder.addInclude( this );
  19741. }
  19742. generate( builder ) {
  19743. return this.getNodeType( builder );
  19744. }
  19745. }
  19746. /**
  19747. * StructNode allows to create custom structures with multiple members.
  19748. * This can also be used to define structures in attribute and uniform data.
  19749. *
  19750. * ```js
  19751. * // Define a custom struct
  19752. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  19753. *
  19754. * // Create a new instance of the struct
  19755. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  19756. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  19757. *
  19758. * // Access the struct members
  19759. * const min = bb.get( 'min' );
  19760. *
  19761. * // Assign a new value to a member
  19762. * min.assign( vec3() );
  19763. * ```
  19764. * @augments Node
  19765. */
  19766. class StructNode extends Node {
  19767. static get type() {
  19768. return 'StructNode';
  19769. }
  19770. constructor( structLayoutNode, values ) {
  19771. super( 'vec3' );
  19772. this.structLayoutNode = structLayoutNode;
  19773. this.values = values;
  19774. this.isStructNode = true;
  19775. }
  19776. getNodeType( builder ) {
  19777. return this.structLayoutNode.getNodeType( builder );
  19778. }
  19779. getMemberType( builder, name ) {
  19780. return this.structLayoutNode.getMemberType( builder, name );
  19781. }
  19782. generate( builder ) {
  19783. const nodeVar = builder.getVarFromNode( this );
  19784. const structType = nodeVar.type;
  19785. const propertyName = builder.getPropertyName( nodeVar );
  19786. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  19787. return nodeVar.name;
  19788. }
  19789. }
  19790. /**
  19791. * TSL function for creating a struct node.
  19792. *
  19793. * @tsl
  19794. * @function
  19795. * @param {Object} membersLayout - The layout of the struct members.
  19796. * @param {string} [name=null] - The name of the struct.
  19797. * @returns {Function} The struct function.
  19798. */
  19799. const struct = ( membersLayout, name = null ) => {
  19800. const structLayout = new StructTypeNode( membersLayout, name );
  19801. const struct = ( ...params ) => {
  19802. let values = null;
  19803. if ( params.length > 0 ) {
  19804. if ( params[ 0 ].isNode ) {
  19805. values = {};
  19806. const names = Object.keys( membersLayout );
  19807. for ( let i = 0; i < params.length; i ++ ) {
  19808. values[ names[ i ] ] = params[ i ];
  19809. }
  19810. } else {
  19811. values = params[ 0 ];
  19812. }
  19813. }
  19814. return nodeObject( new StructNode( structLayout, values ) );
  19815. };
  19816. struct.layout = structLayout;
  19817. struct.isStruct = true;
  19818. return struct;
  19819. };
  19820. /**
  19821. * This node can be used to define multiple outputs in a shader programs.
  19822. *
  19823. * @augments Node
  19824. */
  19825. class OutputStructNode extends Node {
  19826. static get type() {
  19827. return 'OutputStructNode';
  19828. }
  19829. /**
  19830. * Constructs a new output struct node. The constructor can be invoked with an
  19831. * arbitrary number of nodes representing the members.
  19832. *
  19833. * @param {...Node} members - A parameter list of nodes.
  19834. */
  19835. constructor( ...members ) {
  19836. super();
  19837. /**
  19838. * An array of nodes which defines the output.
  19839. *
  19840. * @type {Array<Node>}
  19841. */
  19842. this.members = members;
  19843. /**
  19844. * This flag can be used for type testing.
  19845. *
  19846. * @type {boolean}
  19847. * @readonly
  19848. * @default true
  19849. */
  19850. this.isOutputStructNode = true;
  19851. }
  19852. getNodeType( builder ) {
  19853. const properties = builder.getNodeProperties( this );
  19854. if ( properties.membersLayout === undefined ) {
  19855. const members = this.members;
  19856. const membersLayout = [];
  19857. for ( let i = 0; i < members.length; i ++ ) {
  19858. const name = 'm' + i;
  19859. const type = members[ i ].getNodeType( builder );
  19860. membersLayout.push( { name, type, index: i } );
  19861. }
  19862. properties.membersLayout = membersLayout;
  19863. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  19864. }
  19865. return properties.structType.name;
  19866. }
  19867. generate( builder ) {
  19868. const propertyName = builder.getOutputStructName();
  19869. const members = this.members;
  19870. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19871. for ( let i = 0; i < members.length; i ++ ) {
  19872. const snippet = members[ i ].build( builder );
  19873. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19874. }
  19875. return propertyName;
  19876. }
  19877. }
  19878. /**
  19879. * TSL function for creating an output struct node.
  19880. *
  19881. * @tsl
  19882. * @function
  19883. * @param {...Node} members - A parameter list of nodes.
  19884. * @returns {OutputStructNode}
  19885. */
  19886. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19887. /**
  19888. * Returns the MRT texture index for the given name.
  19889. *
  19890. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19891. * @param {string} name - The name of the MRT texture which index is requested.
  19892. * @return {number} The texture index.
  19893. */
  19894. function getTextureIndex( textures, name ) {
  19895. for ( let i = 0; i < textures.length; i ++ ) {
  19896. if ( textures[ i ].name === name ) {
  19897. return i;
  19898. }
  19899. }
  19900. return -1;
  19901. }
  19902. /**
  19903. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19904. * post-processing is shown below:
  19905. * ```js
  19906. * const mrtNode = mrt( {
  19907. * output: output,
  19908. * normal: normalView
  19909. * } ) );
  19910. * ```
  19911. * The MRT output is defined as a dictionary.
  19912. *
  19913. * @augments OutputStructNode
  19914. */
  19915. class MRTNode extends OutputStructNode {
  19916. static get type() {
  19917. return 'MRTNode';
  19918. }
  19919. /**
  19920. * Constructs a new output struct node.
  19921. *
  19922. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  19923. */
  19924. constructor( outputNodes ) {
  19925. super();
  19926. /**
  19927. * A dictionary representing the MRT outputs. The key
  19928. * is the name of the output, the value the node which produces
  19929. * the output result.
  19930. *
  19931. * @type {Object<string, Node>}
  19932. */
  19933. this.outputNodes = outputNodes;
  19934. /**
  19935. * This flag can be used for type testing.
  19936. *
  19937. * @type {boolean}
  19938. * @readonly
  19939. * @default true
  19940. */
  19941. this.isMRTNode = true;
  19942. }
  19943. /**
  19944. * Returns `true` if the MRT node has an output with the given name.
  19945. *
  19946. * @param {string} name - The name of the output.
  19947. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19948. */
  19949. has( name ) {
  19950. return this.outputNodes[ name ] !== undefined;
  19951. }
  19952. /**
  19953. * Returns the output node for the given name.
  19954. *
  19955. * @param {string} name - The name of the output.
  19956. * @return {Node} The output node.
  19957. */
  19958. get( name ) {
  19959. return this.outputNodes[ name ];
  19960. }
  19961. /**
  19962. * Merges the outputs of the given MRT node with the outputs of this node.
  19963. *
  19964. * @param {MRTNode} mrtNode - The MRT to merge.
  19965. * @return {MRTNode} A new MRT node with merged outputs..
  19966. */
  19967. merge( mrtNode ) {
  19968. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19969. return mrt( outputs );
  19970. }
  19971. setup( builder ) {
  19972. const outputNodes = this.outputNodes;
  19973. const mrt = builder.renderer.getRenderTarget();
  19974. const members = [];
  19975. const textures = mrt.textures;
  19976. for ( const name in outputNodes ) {
  19977. const index = getTextureIndex( textures, name );
  19978. members[ index ] = vec4( outputNodes[ name ] );
  19979. }
  19980. this.members = members;
  19981. return super.setup( builder );
  19982. }
  19983. }
  19984. /**
  19985. * TSL function for creating a MRT node.
  19986. *
  19987. * @tsl
  19988. * @function
  19989. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  19990. * @returns {MRTNode}
  19991. */
  19992. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19993. /**
  19994. * Generates a hash value in the range `[0, 1]` from the given seed.
  19995. *
  19996. * @tsl
  19997. * @function
  19998. * @param {Node<float>} seed - The seed.
  19999. * @return {Node<float>} The hash value.
  20000. */
  20001. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  20002. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  20003. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  20004. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  20005. const result = word.shiftRight( 22 ).bitXor( word );
  20006. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  20007. } );
  20008. /**
  20009. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20010. * The corners are mapped to `0` and the center to `1`.
  20011. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20012. *
  20013. * @tsl
  20014. * @function
  20015. * @param {Node<float>} x - The value to remap.
  20016. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  20017. * @return {Node<float>} The remapped value.
  20018. */
  20019. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  20020. /**
  20021. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20022. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  20023. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20024. *
  20025. * @tsl
  20026. * @function
  20027. * @param {Node<float>} x - The value to remap.
  20028. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  20029. * @return {Node<float>} The remapped value.
  20030. */
  20031. 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 ) );
  20032. /**
  20033. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20034. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  20035. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20036. *
  20037. * @tsl
  20038. * @function
  20039. * @param {Node<float>} x - The value to remap.
  20040. * @param {Node<float>} a - First control parameter.
  20041. * @param {Node<float>} b - Second control parameter.
  20042. * @return {Node<float>} The remapped value.
  20043. */
  20044. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  20045. /**
  20046. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  20047. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20048. *
  20049. * @tsl
  20050. * @function
  20051. * @param {Node<float>} x - The value to compute the sin for.
  20052. * @param {Node<float>} k - Controls the amount of bounces.
  20053. * @return {Node<float>} The result value.
  20054. */
  20055. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  20056. // https://github.com/cabbibo/glsl-tri-noise-3d
  20057. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  20058. return x.fract().sub( .5 ).abs();
  20059. } ).setLayout( {
  20060. name: 'tri',
  20061. type: 'float',
  20062. inputs: [
  20063. { name: 'x', type: 'float' }
  20064. ]
  20065. } );
  20066. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  20067. 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. ) ) ) ) );
  20068. } ).setLayout( {
  20069. name: 'tri3',
  20070. type: 'vec3',
  20071. inputs: [
  20072. { name: 'p', type: 'vec3' }
  20073. ]
  20074. } );
  20075. /**
  20076. * Generates a noise value from the given position, speed and time parameters.
  20077. *
  20078. * @tsl
  20079. * @function
  20080. * @param {Node<vec3>} position - The position.
  20081. * @param {Node<float>} speed - The speed.
  20082. * @param {Node<float>} time - The time.
  20083. * @return {Node<float>} The generated noise.
  20084. */
  20085. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  20086. const p = vec3( position ).toVar();
  20087. const z = float( 1.4 ).toVar();
  20088. const rz = float( 0.0 ).toVar();
  20089. const bp = vec3( p ).toVar();
  20090. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  20091. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  20092. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  20093. bp.mulAssign( 1.8 );
  20094. z.mulAssign( 1.5 );
  20095. p.mulAssign( 1.2 );
  20096. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  20097. rz.addAssign( t.div( z ) );
  20098. bp.addAssign( 0.14 );
  20099. } );
  20100. return rz;
  20101. } ).setLayout( {
  20102. name: 'triNoise3D',
  20103. type: 'float',
  20104. inputs: [
  20105. { name: 'position', type: 'vec3' },
  20106. { name: 'speed', type: 'float' },
  20107. { name: 'time', type: 'float' }
  20108. ]
  20109. } );
  20110. /**
  20111. * This class allows to define multiple overloaded versions
  20112. * of the same function. Depending on the parameters of the function
  20113. * call, the node picks the best-fit overloaded version.
  20114. *
  20115. * @augments Node
  20116. */
  20117. class FunctionOverloadingNode extends Node {
  20118. static get type() {
  20119. return 'FunctionOverloadingNode';
  20120. }
  20121. /**
  20122. * Constructs a new function overloading node.
  20123. *
  20124. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20125. * @param {...Node} parametersNodes - A list of parameter nodes.
  20126. */
  20127. constructor( functionNodes = [], ...parametersNodes ) {
  20128. super();
  20129. /**
  20130. * Array of `Fn` function definitions.
  20131. *
  20132. * @type {Array<Function>}
  20133. */
  20134. this.functionNodes = functionNodes;
  20135. /**
  20136. * A list of parameter nodes.
  20137. *
  20138. * @type {Array<Node>}
  20139. */
  20140. this.parametersNodes = parametersNodes;
  20141. /**
  20142. * The selected overloaded function call.
  20143. *
  20144. * @private
  20145. * @type {ShaderCallNodeInternal}
  20146. */
  20147. this._candidateFnCall = null;
  20148. /**
  20149. * This node is marked as global.
  20150. *
  20151. * @type {boolean}
  20152. * @default true
  20153. */
  20154. this.global = true;
  20155. }
  20156. /**
  20157. * This method is overwritten since the node type is inferred from
  20158. * the function's return type.
  20159. *
  20160. * @param {NodeBuilder} builder - The current node builder.
  20161. * @return {string} The node type.
  20162. */
  20163. getNodeType() {
  20164. return this.functionNodes[ 0 ].shaderNode.layout.type;
  20165. }
  20166. setup( builder ) {
  20167. const params = this.parametersNodes;
  20168. let candidateFnCall = this._candidateFnCall;
  20169. if ( candidateFnCall === null ) {
  20170. let candidateFn = null;
  20171. let candidateScore = -1;
  20172. for ( const functionNode of this.functionNodes ) {
  20173. const shaderNode = functionNode.shaderNode;
  20174. const layout = shaderNode.layout;
  20175. if ( layout === null ) {
  20176. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  20177. }
  20178. const inputs = layout.inputs;
  20179. if ( params.length === inputs.length ) {
  20180. let score = 0;
  20181. for ( let i = 0; i < params.length; i ++ ) {
  20182. const param = params[ i ];
  20183. const input = inputs[ i ];
  20184. if ( param.getNodeType( builder ) === input.type ) {
  20185. score ++;
  20186. } else {
  20187. score = 0;
  20188. }
  20189. }
  20190. if ( score > candidateScore ) {
  20191. candidateFn = functionNode;
  20192. candidateScore = score;
  20193. }
  20194. }
  20195. }
  20196. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  20197. }
  20198. return candidateFnCall;
  20199. }
  20200. }
  20201. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  20202. /**
  20203. * TSL function for creating a function overloading node.
  20204. *
  20205. * @tsl
  20206. * @function
  20207. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20208. * @returns {FunctionOverloadingNode}
  20209. */
  20210. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  20211. /**
  20212. * Represents the elapsed time in seconds.
  20213. *
  20214. * @tsl
  20215. * @type {UniformNode<float>}
  20216. */
  20217. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  20218. /**
  20219. * Represents the delta time in seconds.
  20220. *
  20221. * @tsl
  20222. * @type {UniformNode<float>}
  20223. */
  20224. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  20225. /**
  20226. * Represents the current frame ID.
  20227. *
  20228. * @tsl
  20229. * @type {UniformNode<uint>}
  20230. */
  20231. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  20232. // Deprecated
  20233. /**
  20234. * @tsl
  20235. * @function
  20236. * @deprecated since r170. Use {@link time} instead.
  20237. *
  20238. * @param {number} [timeScale=1] - The time scale.
  20239. * @returns {UniformNode<float>}
  20240. */
  20241. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  20242. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  20243. return time.mul( timeScale );
  20244. };
  20245. /**
  20246. * @tsl
  20247. * @function
  20248. * @deprecated since r170. Use {@link time} instead.
  20249. *
  20250. * @param {number} [timeScale=1] - The time scale.
  20251. * @returns {UniformNode<float>}
  20252. */
  20253. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  20254. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  20255. return time.mul( timeScale );
  20256. };
  20257. /**
  20258. * @tsl
  20259. * @function
  20260. * @deprecated since r170. Use {@link deltaTime} instead.
  20261. *
  20262. * @param {number} [timeScale=1] - The time scale.
  20263. * @returns {UniformNode<float>}
  20264. */
  20265. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  20266. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  20267. return deltaTime.mul( timeScale );
  20268. };
  20269. /**
  20270. * Generates a sine wave oscillation based on a timer.
  20271. *
  20272. * @tsl
  20273. * @function
  20274. * @param {Node<float>} t - The timer to generate the oscillation with.
  20275. * @return {Node<float>} The oscillation node.
  20276. */
  20277. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  20278. /**
  20279. * Generates a square wave oscillation based on a timer.
  20280. *
  20281. * @tsl
  20282. * @function
  20283. * @param {Node<float>} t - The timer to generate the oscillation with.
  20284. * @return {Node<float>} The oscillation node.
  20285. */
  20286. const oscSquare = ( t = time ) => t.fract().round();
  20287. /**
  20288. * Generates a triangle wave oscillation based on a timer.
  20289. *
  20290. * @tsl
  20291. * @function
  20292. * @param {Node<float>} t - The timer to generate the oscillation with.
  20293. * @return {Node<float>} The oscillation node.
  20294. */
  20295. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  20296. /**
  20297. * Generates a sawtooth wave oscillation based on a timer.
  20298. *
  20299. * @tsl
  20300. * @function
  20301. * @param {Node<float>} t - The timer to generate the oscillation with.
  20302. * @return {Node<float>} The oscillation node.
  20303. */
  20304. const oscSawtooth = ( t = time ) => t.fract();
  20305. /**
  20306. * Rotates the given uv coordinates around a center point
  20307. *
  20308. * @tsl
  20309. * @function
  20310. * @param {Node<vec2>} uv - The uv coordinates.
  20311. * @param {Node<float>} rotation - The rotation defined in radians.
  20312. * @param {Node<vec2>} center - The center of rotation
  20313. * @return {Node<vec2>} The rotated uv coordinates.
  20314. */
  20315. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  20316. return rotate( uv.sub( center ), rotation ).add( center );
  20317. } );
  20318. /**
  20319. * Applies a spherical warping effect to the given uv coordinates.
  20320. *
  20321. * @tsl
  20322. * @function
  20323. * @param {Node<vec2>} uv - The uv coordinates.
  20324. * @param {Node<float>} strength - The strength of the effect.
  20325. * @param {Node<vec2>} center - The center point
  20326. * @return {Node<vec2>} The updated uv coordinates.
  20327. */
  20328. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  20329. const delta = uv.sub( center );
  20330. const delta2 = delta.dot( delta );
  20331. const delta4 = delta2.mul( delta2 );
  20332. const deltaOffset = delta4.mul( strength );
  20333. return uv.add( delta.mul( deltaOffset ) );
  20334. } );
  20335. /**
  20336. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  20337. * oriented always towards the camera.
  20338. *
  20339. * ```js
  20340. * material.vertexNode = billboarding();
  20341. * ```
  20342. *
  20343. * @tsl
  20344. * @function
  20345. * @param {Object} config - The configuration object.
  20346. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  20347. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  20348. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  20349. * @return {Node<vec3>} The updated vertex position in clip space.
  20350. */
  20351. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  20352. let worldMatrix;
  20353. if ( position !== null ) {
  20354. worldMatrix = modelWorldMatrix.toVar();
  20355. worldMatrix[ 3 ][ 0 ] = position.x;
  20356. worldMatrix[ 3 ][ 1 ] = position.y;
  20357. worldMatrix[ 3 ][ 2 ] = position.z;
  20358. } else {
  20359. worldMatrix = modelWorldMatrix;
  20360. }
  20361. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  20362. if ( defined( horizontal ) ) {
  20363. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  20364. modelViewMatrix[ 0 ][ 1 ] = 0;
  20365. modelViewMatrix[ 0 ][ 2 ] = 0;
  20366. }
  20367. if ( defined( vertical ) ) {
  20368. modelViewMatrix[ 1 ][ 0 ] = 0;
  20369. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  20370. modelViewMatrix[ 1 ][ 2 ] = 0;
  20371. }
  20372. modelViewMatrix[ 2 ][ 0 ] = 0;
  20373. modelViewMatrix[ 2 ][ 1 ] = 0;
  20374. modelViewMatrix[ 2 ][ 2 ] = 1;
  20375. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  20376. } );
  20377. /**
  20378. * A special version of a screen uv function that involves a depth comparison
  20379. * when computing the final uvs. The function mitigates visual errors when
  20380. * using viewport texture nodes for refraction purposes. Without this function
  20381. * objects in front of a refractive surface might appear on the refractive surface
  20382. * which is incorrect.
  20383. *
  20384. * @tsl
  20385. * @function
  20386. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  20387. * @return {Node<vec2>} The update uv coordinates.
  20388. */
  20389. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  20390. const depth = linearDepth();
  20391. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  20392. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  20393. return finalUV;
  20394. } );
  20395. /**
  20396. * Can be used to compute texture coordinates for animated sprite sheets.
  20397. *
  20398. * ```js
  20399. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  20400. *
  20401. * material.colorNode = texture( spriteSheet, uvNode );
  20402. * ```
  20403. *
  20404. * @augments Node
  20405. */
  20406. class SpriteSheetUVNode extends Node {
  20407. static get type() {
  20408. return 'SpriteSheetUVNode';
  20409. }
  20410. /**
  20411. * Constructs a new sprite sheet uv node.
  20412. *
  20413. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20414. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20415. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20416. */
  20417. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  20418. super( 'vec2' );
  20419. /**
  20420. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20421. *
  20422. * @type {Node<vec2>}
  20423. */
  20424. this.countNode = countNode;
  20425. /**
  20426. * The uv node.
  20427. *
  20428. * @type {Node<vec2>}
  20429. */
  20430. this.uvNode = uvNode;
  20431. /**
  20432. * The node that defines the current frame/sprite.
  20433. *
  20434. * @type {Node<float>}
  20435. */
  20436. this.frameNode = frameNode;
  20437. }
  20438. setup() {
  20439. const { frameNode, uvNode, countNode } = this;
  20440. const { width, height } = countNode;
  20441. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  20442. const column = frameNum.mod( width );
  20443. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  20444. const scale = countNode.reciprocal();
  20445. const uvFrameOffset = vec2( column, row );
  20446. return uvNode.add( uvFrameOffset ).mul( scale );
  20447. }
  20448. }
  20449. /**
  20450. * TSL function for creating a sprite sheet uv node.
  20451. *
  20452. * @tsl
  20453. * @function
  20454. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20455. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20456. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20457. * @returns {SpriteSheetUVNode}
  20458. */
  20459. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  20460. /**
  20461. * Can be used for triplanar texture mapping.
  20462. *
  20463. * ```js
  20464. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  20465. * ```
  20466. *
  20467. * @augments Node
  20468. */
  20469. class TriplanarTexturesNode extends Node {
  20470. static get type() {
  20471. return 'TriplanarTexturesNode';
  20472. }
  20473. /**
  20474. * Constructs a new triplanar textures node.
  20475. *
  20476. * @param {Node} textureXNode - First texture node.
  20477. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20478. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20479. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20480. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20481. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20482. */
  20483. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  20484. super( 'vec4' );
  20485. /**
  20486. * First texture node.
  20487. *
  20488. * @type {Node}
  20489. */
  20490. this.textureXNode = textureXNode;
  20491. /**
  20492. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20493. *
  20494. * @type {Node}
  20495. * @default null
  20496. */
  20497. this.textureYNode = textureYNode;
  20498. /**
  20499. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20500. *
  20501. * @type {Node}
  20502. * @default null
  20503. */
  20504. this.textureZNode = textureZNode;
  20505. /**
  20506. * The scale node.
  20507. *
  20508. * @type {Node<float>}
  20509. * @default float(1)
  20510. */
  20511. this.scaleNode = scaleNode;
  20512. /**
  20513. * Vertex positions in local space.
  20514. *
  20515. * @type {Node<vec3>}
  20516. * @default positionLocal
  20517. */
  20518. this.positionNode = positionNode;
  20519. /**
  20520. * Normals in local space.
  20521. *
  20522. * @type {Node<vec3>}
  20523. * @default normalLocal
  20524. */
  20525. this.normalNode = normalNode;
  20526. }
  20527. setup() {
  20528. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  20529. // Ref: https://github.com/keijiro/StandardTriplanar
  20530. // Blending factor of triplanar mapping
  20531. let bf = normalNode.abs().normalize();
  20532. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  20533. // Triplanar mapping
  20534. const tx = positionNode.yz.mul( scaleNode );
  20535. const ty = positionNode.zx.mul( scaleNode );
  20536. const tz = positionNode.xy.mul( scaleNode );
  20537. // Base color
  20538. const textureX = textureXNode.value;
  20539. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  20540. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  20541. const cx = texture( textureX, tx ).mul( bf.x );
  20542. const cy = texture( textureY, ty ).mul( bf.y );
  20543. const cz = texture( textureZ, tz ).mul( bf.z );
  20544. return add( cx, cy, cz );
  20545. }
  20546. }
  20547. /**
  20548. * TSL function for creating a triplanar textures node.
  20549. *
  20550. * @tsl
  20551. * @function
  20552. * @param {Node} textureXNode - First texture node.
  20553. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20554. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20555. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20556. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20557. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20558. * @returns {TriplanarTexturesNode}
  20559. */
  20560. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  20561. /**
  20562. * TSL function for creating a triplanar textures node.
  20563. *
  20564. * @tsl
  20565. * @function
  20566. * @param {Node} textureXNode - First texture node.
  20567. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20568. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20569. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20570. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20571. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20572. * @returns {TriplanarTexturesNode}
  20573. */
  20574. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  20575. const _reflectorPlane = new Plane();
  20576. const _normal = new Vector3();
  20577. const _reflectorWorldPosition = new Vector3();
  20578. const _cameraWorldPosition = new Vector3();
  20579. const _rotationMatrix = new Matrix4();
  20580. const _lookAtPosition = new Vector3( 0, 0, -1 );
  20581. const clipPlane = new Vector4();
  20582. const _view = new Vector3();
  20583. const _target = new Vector3();
  20584. const _q = new Vector4();
  20585. const _size$2 = new Vector2();
  20586. const _defaultRT = new RenderTarget();
  20587. const _defaultUV = screenUV.flipX();
  20588. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  20589. let _inReflector = false;
  20590. /**
  20591. * This node can be used to implement mirror-like flat reflective surfaces.
  20592. *
  20593. * ```js
  20594. * const groundReflector = reflector();
  20595. * material.colorNode = groundReflector;
  20596. *
  20597. * const plane = new Mesh( geometry, material );
  20598. * plane.add( groundReflector.target );
  20599. * ```
  20600. *
  20601. * @augments TextureNode
  20602. */
  20603. class ReflectorNode extends TextureNode {
  20604. static get type() {
  20605. return 'ReflectorNode';
  20606. }
  20607. /**
  20608. * Constructs a new reflector node.
  20609. *
  20610. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20611. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20612. * @param {number} [parameters.resolution=1] - The resolution scale.
  20613. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20614. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20615. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20616. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20617. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20618. */
  20619. constructor( parameters = {} ) {
  20620. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20621. /**
  20622. * A reference to the internal reflector base node which holds the actual implementation.
  20623. *
  20624. * @private
  20625. * @type {?ReflectorBaseNode}
  20626. * @default null
  20627. */
  20628. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20629. /**
  20630. * A reference to the internal depth node.
  20631. *
  20632. * @private
  20633. * @type {?Node}
  20634. * @default null
  20635. */
  20636. this._depthNode = null;
  20637. this.setUpdateMatrix( false );
  20638. }
  20639. /**
  20640. * A reference to the internal reflector node.
  20641. *
  20642. * @type {ReflectorBaseNode}
  20643. */
  20644. get reflector() {
  20645. return this._reflectorBaseNode;
  20646. }
  20647. /**
  20648. * A reference to 3D object the reflector is linked to.
  20649. *
  20650. * @type {Object3D}
  20651. */
  20652. get target() {
  20653. return this._reflectorBaseNode.target;
  20654. }
  20655. /**
  20656. * Returns a node representing the mirror's depth. That can be used
  20657. * to implement more advanced reflection effects like distance attenuation.
  20658. *
  20659. * @return {Node} The depth node.
  20660. */
  20661. getDepthNode() {
  20662. if ( this._depthNode === null ) {
  20663. if ( this._reflectorBaseNode.depth !== true ) {
  20664. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20665. }
  20666. this._depthNode = nodeObject( new ReflectorNode( {
  20667. defaultTexture: _defaultRT.depthTexture,
  20668. reflector: this._reflectorBaseNode
  20669. } ) );
  20670. }
  20671. return this._depthNode;
  20672. }
  20673. setup( builder ) {
  20674. // ignore if used in post-processing
  20675. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20676. return super.setup( builder );
  20677. }
  20678. clone() {
  20679. const texture = new this.constructor( this.reflectorNode );
  20680. texture._reflectorBaseNode = this._reflectorBaseNode;
  20681. return texture;
  20682. }
  20683. }
  20684. /**
  20685. * Holds the actual implementation of the reflector.
  20686. *
  20687. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20688. * in `ReflectorNode`, see #29619.
  20689. *
  20690. * @private
  20691. * @augments Node
  20692. */
  20693. class ReflectorBaseNode extends Node {
  20694. static get type() {
  20695. return 'ReflectorBaseNode';
  20696. }
  20697. /**
  20698. * Constructs a new reflector base node.
  20699. *
  20700. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20701. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20702. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20703. * @param {number} [parameters.resolution=1] - The resolution scale.
  20704. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20705. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20706. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20707. */
  20708. constructor( textureNode, parameters = {} ) {
  20709. super();
  20710. const {
  20711. target = new Object3D(),
  20712. resolution = 1,
  20713. generateMipmaps = false,
  20714. bounces = true,
  20715. depth = false
  20716. } = parameters;
  20717. /**
  20718. * Represents the rendered reflections as a texture node.
  20719. *
  20720. * @type {TextureNode}
  20721. */
  20722. this.textureNode = textureNode;
  20723. /**
  20724. * The 3D object the reflector is linked to.
  20725. *
  20726. * @type {Object3D}
  20727. * @default {new Object3D()}
  20728. */
  20729. this.target = target;
  20730. /**
  20731. * The resolution scale.
  20732. *
  20733. * @type {number}
  20734. * @default {1}
  20735. */
  20736. this.resolution = resolution;
  20737. /**
  20738. * Whether mipmaps should be generated or not.
  20739. *
  20740. * @type {boolean}
  20741. * @default {false}
  20742. */
  20743. this.generateMipmaps = generateMipmaps;
  20744. /**
  20745. * Whether reflectors can render other reflector nodes or not.
  20746. *
  20747. * @type {boolean}
  20748. * @default {true}
  20749. */
  20750. this.bounces = bounces;
  20751. /**
  20752. * Whether depth data should be generated or not.
  20753. *
  20754. * @type {boolean}
  20755. * @default {false}
  20756. */
  20757. this.depth = depth;
  20758. /**
  20759. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20760. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20761. *
  20762. * @type {string}
  20763. * @default 'render'
  20764. */
  20765. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20766. /**
  20767. * Weak map for managing virtual cameras.
  20768. *
  20769. * @type {WeakMap<Camera, Camera>}
  20770. */
  20771. this.virtualCameras = new WeakMap();
  20772. /**
  20773. * Weak map for managing render targets.
  20774. *
  20775. * @type {WeakMap<Camera, RenderTarget>}
  20776. */
  20777. this.renderTargets = new WeakMap();
  20778. }
  20779. /**
  20780. * Updates the resolution of the internal render target.
  20781. *
  20782. * @private
  20783. * @param {RenderTarget} renderTarget - The render target to resize.
  20784. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20785. */
  20786. _updateResolution( renderTarget, renderer ) {
  20787. const resolution = this.resolution;
  20788. renderer.getDrawingBufferSize( _size$2 );
  20789. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20790. }
  20791. setup( builder ) {
  20792. this._updateResolution( _defaultRT, builder.renderer );
  20793. return super.setup( builder );
  20794. }
  20795. /**
  20796. * Returns a virtual camera for the given camera. The virtual camera is used to
  20797. * render the scene from the reflector's view so correct reflections can be produced.
  20798. *
  20799. * @param {Camera} camera - The scene's camera.
  20800. * @return {Camera} The corresponding virtual camera.
  20801. */
  20802. getVirtualCamera( camera ) {
  20803. let virtualCamera = this.virtualCameras.get( camera );
  20804. if ( virtualCamera === undefined ) {
  20805. virtualCamera = camera.clone();
  20806. this.virtualCameras.set( camera, virtualCamera );
  20807. }
  20808. return virtualCamera;
  20809. }
  20810. /**
  20811. * Returns a render target for the given camera. The reflections are rendered
  20812. * into this render target.
  20813. *
  20814. * @param {Camera} camera - The scene's camera.
  20815. * @return {RenderTarget} The render target.
  20816. */
  20817. getRenderTarget( camera ) {
  20818. let renderTarget = this.renderTargets.get( camera );
  20819. if ( renderTarget === undefined ) {
  20820. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20821. if ( this.generateMipmaps === true ) {
  20822. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20823. renderTarget.texture.generateMipmaps = true;
  20824. }
  20825. if ( this.depth === true ) {
  20826. renderTarget.depthTexture = new DepthTexture();
  20827. }
  20828. this.renderTargets.set( camera, renderTarget );
  20829. }
  20830. return renderTarget;
  20831. }
  20832. updateBefore( frame ) {
  20833. if ( this.bounces === false && _inReflector ) return false;
  20834. _inReflector = true;
  20835. const { scene, camera, renderer, material } = frame;
  20836. const { target } = this;
  20837. const virtualCamera = this.getVirtualCamera( camera );
  20838. const renderTarget = this.getRenderTarget( virtualCamera );
  20839. renderer.getDrawingBufferSize( _size$2 );
  20840. this._updateResolution( renderTarget, renderer );
  20841. //
  20842. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20843. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20844. _rotationMatrix.extractRotation( target.matrixWorld );
  20845. _normal.set( 0, 0, 1 );
  20846. _normal.applyMatrix4( _rotationMatrix );
  20847. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20848. // Avoid rendering when reflector is facing away
  20849. if ( _view.dot( _normal ) > 0 ) return;
  20850. _view.reflect( _normal ).negate();
  20851. _view.add( _reflectorWorldPosition );
  20852. _rotationMatrix.extractRotation( camera.matrixWorld );
  20853. _lookAtPosition.set( 0, 0, -1 );
  20854. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20855. _lookAtPosition.add( _cameraWorldPosition );
  20856. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20857. _target.reflect( _normal ).negate();
  20858. _target.add( _reflectorWorldPosition );
  20859. //
  20860. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20861. virtualCamera.position.copy( _view );
  20862. virtualCamera.up.set( 0, 1, 0 );
  20863. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20864. virtualCamera.up.reflect( _normal );
  20865. virtualCamera.lookAt( _target );
  20866. virtualCamera.near = camera.near;
  20867. virtualCamera.far = camera.far;
  20868. virtualCamera.updateMatrixWorld();
  20869. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20870. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20871. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20872. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20873. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20874. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20875. const projectionMatrix = virtualCamera.projectionMatrix;
  20876. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20877. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20878. _q.z = -1;
  20879. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20880. // Calculate the scaled plane vector
  20881. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20882. const clipBias = 0;
  20883. // Replacing the third row of the projection matrix
  20884. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20885. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20886. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20887. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20888. //
  20889. this.textureNode.value = renderTarget.texture;
  20890. if ( this.depth === true ) {
  20891. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20892. }
  20893. material.visible = false;
  20894. const currentRenderTarget = renderer.getRenderTarget();
  20895. const currentMRT = renderer.getMRT();
  20896. const currentAutoClear = renderer.autoClear;
  20897. renderer.setMRT( null );
  20898. renderer.setRenderTarget( renderTarget );
  20899. renderer.autoClear = true;
  20900. renderer.render( scene, virtualCamera );
  20901. renderer.setMRT( currentMRT );
  20902. renderer.setRenderTarget( currentRenderTarget );
  20903. renderer.autoClear = currentAutoClear;
  20904. material.visible = true;
  20905. _inReflector = false;
  20906. }
  20907. }
  20908. /**
  20909. * TSL function for creating a reflector node.
  20910. *
  20911. * @tsl
  20912. * @function
  20913. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20914. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20915. * @param {number} [parameters.resolution=1] - The resolution scale.
  20916. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20917. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20918. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20919. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20920. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20921. * @returns {ReflectorNode}
  20922. */
  20923. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20924. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  20925. /**
  20926. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20927. *
  20928. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20929. *
  20930. * @private
  20931. * @augments BufferGeometry
  20932. */
  20933. class QuadGeometry extends BufferGeometry {
  20934. /**
  20935. * Constructs a new quad geometry.
  20936. *
  20937. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20938. */
  20939. constructor( flipY = false ) {
  20940. super();
  20941. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20942. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  20943. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20944. }
  20945. }
  20946. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20947. /**
  20948. * This module is a helper for passes which need to render a full
  20949. * screen effect which is quite common in context of post processing.
  20950. *
  20951. * The intended usage is to reuse a single quad mesh for rendering
  20952. * subsequent passes by just reassigning the `material` reference.
  20953. *
  20954. * @augments Mesh
  20955. */
  20956. class QuadMesh extends Mesh {
  20957. /**
  20958. * Constructs a new quad mesh.
  20959. *
  20960. * @param {?Material} [material=null] - The material to render the quad mesh with.
  20961. */
  20962. constructor( material = null ) {
  20963. super( _geometry, material );
  20964. /**
  20965. * The camera to render the quad mesh with.
  20966. *
  20967. * @type {OrthographicCamera}
  20968. * @readonly
  20969. */
  20970. this.camera = _camera;
  20971. /**
  20972. * This flag can be used for type testing.
  20973. *
  20974. * @type {boolean}
  20975. * @readonly
  20976. * @default true
  20977. */
  20978. this.isQuadMesh = true;
  20979. }
  20980. /**
  20981. * Async version of `render()`.
  20982. *
  20983. * @async
  20984. * @param {Renderer} renderer - The renderer.
  20985. * @return {Promise} A Promise that resolves when the render has been finished.
  20986. */
  20987. async renderAsync( renderer ) {
  20988. return renderer.renderAsync( this, _camera );
  20989. }
  20990. /**
  20991. * Renders the quad mesh
  20992. *
  20993. * @param {Renderer} renderer - The renderer.
  20994. */
  20995. render( renderer ) {
  20996. renderer.render( this, _camera );
  20997. }
  20998. }
  20999. const _size$1 = /*@__PURE__*/ new Vector2();
  21000. /**
  21001. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  21002. * This module is especially relevant in context of post processing where certain nodes require
  21003. * texture input for their effects. With the helper function `convertToTexture()` which is based
  21004. * on this module, the node system can automatically ensure texture input if required.
  21005. *
  21006. * @augments TextureNode
  21007. */
  21008. class RTTNode extends TextureNode {
  21009. static get type() {
  21010. return 'RTTNode';
  21011. }
  21012. /**
  21013. * Constructs a new RTT node.
  21014. *
  21015. * @param {Node} node - The node to render a texture with.
  21016. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21017. * @param {?number} [height=null] - The height of the internal render target.
  21018. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21019. */
  21020. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  21021. const renderTarget = new RenderTarget( width, height, options );
  21022. super( renderTarget.texture, uv() );
  21023. /**
  21024. * The node to render a texture with.
  21025. *
  21026. * @type {Node}
  21027. */
  21028. this.node = node;
  21029. /**
  21030. * The width of the internal render target.
  21031. * If not width is applied, the render target is automatically resized.
  21032. *
  21033. * @type {?number}
  21034. * @default null
  21035. */
  21036. this.width = width;
  21037. /**
  21038. * The height of the internal render target.
  21039. *
  21040. * @type {?number}
  21041. * @default null
  21042. */
  21043. this.height = height;
  21044. /**
  21045. * The pixel ratio
  21046. *
  21047. * @type {number}
  21048. * @default 1
  21049. */
  21050. this.pixelRatio = 1;
  21051. /**
  21052. * The render target
  21053. *
  21054. * @type {RenderTarget}
  21055. */
  21056. this.renderTarget = renderTarget;
  21057. /**
  21058. * Whether the texture requires an update or not.
  21059. *
  21060. * @type {boolean}
  21061. * @default true
  21062. */
  21063. this.textureNeedsUpdate = true;
  21064. /**
  21065. * Whether the texture should automatically be updated or not.
  21066. *
  21067. * @type {boolean}
  21068. * @default true
  21069. */
  21070. this.autoUpdate = true;
  21071. /**
  21072. * The node which is used with the quad mesh for RTT.
  21073. *
  21074. * @private
  21075. * @type {Node}
  21076. * @default null
  21077. */
  21078. this._rttNode = null;
  21079. /**
  21080. * The internal quad mesh for RTT.
  21081. *
  21082. * @private
  21083. * @type {QuadMesh}
  21084. */
  21085. this._quadMesh = new QuadMesh( new NodeMaterial() );
  21086. /**
  21087. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  21088. * the texture once per render in its {@link RTTNode#updateBefore} method.
  21089. *
  21090. * @type {string}
  21091. * @default 'render'
  21092. */
  21093. this.updateBeforeType = NodeUpdateType.RENDER;
  21094. }
  21095. /**
  21096. * Whether the internal render target should automatically be resized or not.
  21097. *
  21098. * @type {boolean}
  21099. * @readonly
  21100. * @default true
  21101. */
  21102. get autoSize() {
  21103. return this.width === null;
  21104. }
  21105. setup( builder ) {
  21106. this._rttNode = this.node.context( builder.getSharedContext() );
  21107. this._quadMesh.material.name = 'RTT';
  21108. this._quadMesh.material.needsUpdate = true;
  21109. return super.setup( builder );
  21110. }
  21111. /**
  21112. * Sets the size of the internal render target
  21113. *
  21114. * @param {number} width - The width to set.
  21115. * @param {number} height - The width to set.
  21116. */
  21117. setSize( width, height ) {
  21118. this.width = width;
  21119. this.height = height;
  21120. const effectiveWidth = width * this.pixelRatio;
  21121. const effectiveHeight = height * this.pixelRatio;
  21122. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  21123. this.textureNeedsUpdate = true;
  21124. }
  21125. /**
  21126. * Sets the pixel ratio. This will also resize the render target.
  21127. *
  21128. * @param {number} pixelRatio - The pixel ratio to set.
  21129. */
  21130. setPixelRatio( pixelRatio ) {
  21131. this.pixelRatio = pixelRatio;
  21132. this.setSize( this.width, this.height );
  21133. }
  21134. updateBefore( { renderer } ) {
  21135. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  21136. this.textureNeedsUpdate = false;
  21137. //
  21138. if ( this.autoSize === true ) {
  21139. this.pixelRatio = renderer.getPixelRatio();
  21140. const size = renderer.getSize( _size$1 );
  21141. this.setSize( size.width, size.height );
  21142. }
  21143. //
  21144. this._quadMesh.material.fragmentNode = this._rttNode;
  21145. //
  21146. const currentRenderTarget = renderer.getRenderTarget();
  21147. renderer.setRenderTarget( this.renderTarget );
  21148. this._quadMesh.render( renderer );
  21149. renderer.setRenderTarget( currentRenderTarget );
  21150. }
  21151. clone() {
  21152. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  21153. newNode.sampler = this.sampler;
  21154. newNode.referenceNode = this;
  21155. return newNode;
  21156. }
  21157. }
  21158. /**
  21159. * TSL function for creating a RTT node.
  21160. *
  21161. * @tsl
  21162. * @function
  21163. * @param {Node} node - The node to render a texture with.
  21164. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21165. * @param {?number} [height=null] - The height of the internal render target.
  21166. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21167. * @returns {RTTNode}
  21168. */
  21169. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  21170. /**
  21171. * TSL function for converting nodes to textures nodes.
  21172. *
  21173. * @tsl
  21174. * @function
  21175. * @param {Node} node - The node to render a texture with.
  21176. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21177. * @param {?number} [height=null] - The height of the internal render target.
  21178. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21179. * @returns {RTTNode}
  21180. */
  21181. const convertToTexture = ( node, ...params ) => {
  21182. if ( node.isTextureNode ) return node;
  21183. if ( node.isPassNode ) return node.getTextureNode();
  21184. return rtt( node, ...params );
  21185. };
  21186. /**
  21187. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  21188. * depth value and the camera's inverse projection matrix.
  21189. *
  21190. * @tsl
  21191. * @function
  21192. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  21193. * @param {Node<float>} depth - The fragment's depth value.
  21194. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21195. * @return {Node<vec3>} The fragments position in view space.
  21196. */
  21197. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  21198. let clipSpacePosition;
  21199. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  21200. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  21201. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  21202. } else {
  21203. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  21204. }
  21205. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  21206. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  21207. } );
  21208. /**
  21209. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  21210. * and the camera's projection matrix
  21211. *
  21212. * @tsl
  21213. * @function
  21214. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  21215. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  21216. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  21217. */
  21218. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  21219. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  21220. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  21221. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  21222. } );
  21223. /**
  21224. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  21225. * target is available or if flat surface normals are required.
  21226. *
  21227. * @tsl
  21228. * @function
  21229. * @param {Node<vec2>} uv - The texture coordinate.
  21230. * @param {DepthTexture} depthTexture - The depth texture.
  21231. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21232. * @return {Node<vec3>} The computed normal vector.
  21233. */
  21234. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  21235. const size = textureSize( textureLoad( depthTexture ) );
  21236. const p = ivec2( uv.mul( size ) ).toVar();
  21237. const c0 = textureLoad( depthTexture, p ).toVar();
  21238. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  21239. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  21240. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  21241. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  21242. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  21243. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  21244. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  21245. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  21246. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  21247. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  21248. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  21249. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  21250. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  21251. 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 ) ) );
  21252. 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 ) ) );
  21253. return normalize( cross( dpdx, dpdy ) );
  21254. } );
  21255. /**
  21256. * This special type of instanced buffer attribute is intended for compute shaders.
  21257. * In earlier three.js versions it was only possible to update attribute data
  21258. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21259. * new material system and renderer it is now possible to use compute shaders
  21260. * to compute the data for an attribute more efficiently on the GPU.
  21261. *
  21262. * The idea is to create an instance of this class and provide it as an input
  21263. * to {@link StorageBufferNode}.
  21264. *
  21265. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21266. *
  21267. * @augments InstancedBufferAttribute
  21268. */
  21269. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  21270. /**
  21271. * Constructs a new storage instanced buffer attribute.
  21272. *
  21273. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21274. * The subsequent parameters are then obsolete.
  21275. * @param {number} itemSize - The item size.
  21276. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21277. */
  21278. constructor( count, itemSize, typeClass = Float32Array ) {
  21279. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21280. super( array, itemSize );
  21281. /**
  21282. * This flag can be used for type testing.
  21283. *
  21284. * @type {boolean}
  21285. * @readonly
  21286. * @default true
  21287. */
  21288. this.isStorageInstancedBufferAttribute = true;
  21289. }
  21290. }
  21291. /**
  21292. * This special type of buffer attribute is intended for compute shaders.
  21293. * In earlier three.js versions it was only possible to update attribute data
  21294. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21295. * new material system and renderer it is now possible to use compute shaders
  21296. * to compute the data for an attribute more efficiently on the GPU.
  21297. *
  21298. * The idea is to create an instance of this class and provide it as an input
  21299. * to {@link StorageBufferNode}.
  21300. *
  21301. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21302. *
  21303. * @augments BufferAttribute
  21304. */
  21305. class StorageBufferAttribute extends BufferAttribute {
  21306. /**
  21307. * Constructs a new storage buffer attribute.
  21308. *
  21309. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21310. * The subsequent parameters are then obsolete.
  21311. * @param {number} itemSize - The item size.
  21312. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21313. */
  21314. constructor( count, itemSize, typeClass = Float32Array ) {
  21315. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21316. super( array, itemSize );
  21317. /**
  21318. * This flag can be used for type testing.
  21319. *
  21320. * @type {boolean}
  21321. * @readonly
  21322. * @default true
  21323. */
  21324. this.isStorageBufferAttribute = true;
  21325. }
  21326. }
  21327. /**
  21328. * This class enables element access on instances of {@link StorageBufferNode}.
  21329. * In most cases, it is indirectly used when accessing elements with the
  21330. * {@link StorageBufferNode#element} method.
  21331. *
  21332. * ```js
  21333. * const position = positionStorage.element( instanceIndex );
  21334. * ```
  21335. *
  21336. * @augments ArrayElementNode
  21337. */
  21338. class StorageArrayElementNode extends ArrayElementNode {
  21339. static get type() {
  21340. return 'StorageArrayElementNode';
  21341. }
  21342. /**
  21343. * Constructs storage buffer element node.
  21344. *
  21345. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21346. * @param {Node} indexNode - The index node that defines the element access.
  21347. */
  21348. constructor( storageBufferNode, indexNode ) {
  21349. super( storageBufferNode, indexNode );
  21350. /**
  21351. * This flag can be used for type testing.
  21352. *
  21353. * @type {boolean}
  21354. * @readonly
  21355. * @default true
  21356. */
  21357. this.isStorageArrayElementNode = true;
  21358. }
  21359. /**
  21360. * The storage buffer node.
  21361. *
  21362. * @param {Node} value
  21363. * @type {StorageBufferNode}
  21364. */
  21365. set storageBufferNode( value ) {
  21366. this.node = value;
  21367. }
  21368. get storageBufferNode() {
  21369. return this.node;
  21370. }
  21371. getMemberType( builder, name ) {
  21372. const structTypeNode = this.storageBufferNode.structTypeNode;
  21373. if ( structTypeNode ) {
  21374. return structTypeNode.getMemberType( builder, name );
  21375. }
  21376. return 'void';
  21377. }
  21378. setup( builder ) {
  21379. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21380. if ( this.node.isPBO === true ) {
  21381. builder.setupPBO( this.node );
  21382. }
  21383. }
  21384. return super.setup( builder );
  21385. }
  21386. generate( builder, output ) {
  21387. let snippet;
  21388. const isAssignContext = builder.context.assign;
  21389. //
  21390. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21391. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  21392. snippet = builder.generatePBO( this );
  21393. } else {
  21394. snippet = this.node.build( builder );
  21395. }
  21396. } else {
  21397. snippet = super.generate( builder );
  21398. }
  21399. if ( isAssignContext !== true ) {
  21400. const type = this.getNodeType( builder );
  21401. snippet = builder.format( snippet, type, output );
  21402. }
  21403. return snippet;
  21404. }
  21405. }
  21406. /**
  21407. * TSL function for creating a storage element node.
  21408. *
  21409. * @tsl
  21410. * @function
  21411. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21412. * @param {Node} indexNode - The index node that defines the element access.
  21413. * @returns {StorageArrayElementNode}
  21414. */
  21415. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  21416. /**
  21417. * This node is used in context of compute shaders and allows to define a
  21418. * storage buffer for data. A typical workflow is to create instances of
  21419. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  21420. * setup up a compute shader that writes into the buffers and then convert
  21421. * the storage buffers to attribute nodes for rendering.
  21422. *
  21423. * ```js
  21424. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  21425. *
  21426. * const computeInit = Fn( () => { // the compute shader
  21427. *
  21428. * const position = positionBuffer.element( instanceIndex );
  21429. *
  21430. * // compute position data
  21431. *
  21432. * position.x = 1;
  21433. * position.y = 1;
  21434. * position.z = 1;
  21435. *
  21436. * } )().compute( particleCount );
  21437. *
  21438. * const particleMaterial = new THREE.SpriteNodeMaterial();
  21439. * particleMaterial.positionNode = positionBuffer.toAttribute();
  21440. *
  21441. * renderer.computeAsync( computeInit );
  21442. *
  21443. * ```
  21444. *
  21445. * @augments BufferNode
  21446. */
  21447. class StorageBufferNode extends BufferNode {
  21448. static get type() {
  21449. return 'StorageBufferNode';
  21450. }
  21451. /**
  21452. * Constructs a new storage buffer node.
  21453. *
  21454. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21455. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  21456. * @param {number} [bufferCount=0] - The buffer count.
  21457. */
  21458. constructor( value, bufferType = null, bufferCount = 0 ) {
  21459. let nodeType, structTypeNode = null;
  21460. if ( bufferType && bufferType.isStruct ) {
  21461. nodeType = 'struct';
  21462. structTypeNode = bufferType.layout;
  21463. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  21464. nodeType = getTypeFromLength( value.itemSize );
  21465. bufferCount = value.count;
  21466. } else {
  21467. nodeType = bufferType;
  21468. }
  21469. super( value, nodeType, bufferCount );
  21470. /**
  21471. * This flag can be used for type testing.
  21472. *
  21473. * @type {boolean}
  21474. * @readonly
  21475. * @default true
  21476. */
  21477. this.isStorageBufferNode = true;
  21478. /**
  21479. * The buffer struct type.
  21480. *
  21481. * @type {?structTypeNode}
  21482. * @default null
  21483. */
  21484. this.structTypeNode = structTypeNode;
  21485. /**
  21486. * The access type of the texture node.
  21487. *
  21488. * @type {string}
  21489. * @default 'readWrite'
  21490. */
  21491. this.access = NodeAccess.READ_WRITE;
  21492. /**
  21493. * Whether the node is atomic or not.
  21494. *
  21495. * @type {boolean}
  21496. * @default false
  21497. */
  21498. this.isAtomic = false;
  21499. /**
  21500. * Whether the node represents a PBO or not.
  21501. * Only relevant for WebGL.
  21502. *
  21503. * @type {boolean}
  21504. * @default false
  21505. */
  21506. this.isPBO = false;
  21507. /**
  21508. * A reference to the internal buffer attribute node.
  21509. *
  21510. * @type {?BufferAttributeNode}
  21511. * @default null
  21512. */
  21513. this._attribute = null;
  21514. /**
  21515. * A reference to the internal varying node.
  21516. *
  21517. * @type {?VaryingNode}
  21518. * @default null
  21519. */
  21520. this._varying = null;
  21521. /**
  21522. * `StorageBufferNode` sets this property to `true` by default.
  21523. *
  21524. * @type {boolean}
  21525. * @default true
  21526. */
  21527. this.global = true;
  21528. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  21529. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  21530. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  21531. else value.isStorageBufferAttribute = true;
  21532. }
  21533. }
  21534. /**
  21535. * This method is overwritten since the buffer data might be shared
  21536. * and thus the hash should be shared as well.
  21537. *
  21538. * @param {NodeBuilder} builder - The current node builder.
  21539. * @return {string} The hash.
  21540. */
  21541. getHash( builder ) {
  21542. if ( this.bufferCount === 0 ) {
  21543. let bufferData = builder.globalCache.getData( this.value );
  21544. if ( bufferData === undefined ) {
  21545. bufferData = {
  21546. node: this
  21547. };
  21548. builder.globalCache.setData( this.value, bufferData );
  21549. }
  21550. return bufferData.node.uuid;
  21551. }
  21552. return this.uuid;
  21553. }
  21554. /**
  21555. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  21556. *
  21557. * @param {NodeBuilder} builder - The current node builder.
  21558. * @return {string} The input type.
  21559. */
  21560. getInputType( /*builder*/ ) {
  21561. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  21562. }
  21563. /**
  21564. * Enables element access with the given index node.
  21565. *
  21566. * @param {IndexNode} indexNode - The index node.
  21567. * @return {StorageArrayElementNode} A node representing the element access.
  21568. */
  21569. element( indexNode ) {
  21570. return storageElement( this, indexNode );
  21571. }
  21572. /**
  21573. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  21574. *
  21575. * @param {boolean} value - The value so set.
  21576. * @return {StorageBufferNode} A reference to this node.
  21577. */
  21578. setPBO( value ) {
  21579. this.isPBO = value;
  21580. return this;
  21581. }
  21582. /**
  21583. * Returns the `isPBO` value.
  21584. *
  21585. * @return {boolean} Whether the node represents a PBO or not.
  21586. */
  21587. getPBO() {
  21588. return this.isPBO;
  21589. }
  21590. /**
  21591. * Defines the node access.
  21592. *
  21593. * @param {string} value - The node access.
  21594. * @return {StorageBufferNode} A reference to this node.
  21595. */
  21596. setAccess( value ) {
  21597. this.access = value;
  21598. return this;
  21599. }
  21600. /**
  21601. * Convenience method for configuring a read-only node access.
  21602. *
  21603. * @return {StorageBufferNode} A reference to this node.
  21604. */
  21605. toReadOnly() {
  21606. return this.setAccess( NodeAccess.READ_ONLY );
  21607. }
  21608. /**
  21609. * Defines whether the node is atomic or not.
  21610. *
  21611. * @param {boolean} value - The atomic flag.
  21612. * @return {StorageBufferNode} A reference to this node.
  21613. */
  21614. setAtomic( value ) {
  21615. this.isAtomic = value;
  21616. return this;
  21617. }
  21618. /**
  21619. * Convenience method for making this node atomic.
  21620. *
  21621. * @return {StorageBufferNode} A reference to this node.
  21622. */
  21623. toAtomic() {
  21624. return this.setAtomic( true );
  21625. }
  21626. /**
  21627. * Returns attribute data for this storage buffer node.
  21628. *
  21629. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21630. */
  21631. getAttributeData() {
  21632. if ( this._attribute === null ) {
  21633. this._attribute = bufferAttribute( this.value );
  21634. this._varying = varying( this._attribute );
  21635. }
  21636. return {
  21637. attribute: this._attribute,
  21638. varying: this._varying
  21639. };
  21640. }
  21641. /**
  21642. * This method is overwritten since the node type from the availability of storage buffers
  21643. * and the attribute data.
  21644. *
  21645. * @param {NodeBuilder} builder - The current node builder.
  21646. * @return {string} The node type.
  21647. */
  21648. getNodeType( builder ) {
  21649. if ( this.structTypeNode !== null ) {
  21650. return this.structTypeNode.getNodeType( builder );
  21651. }
  21652. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21653. return super.getNodeType( builder );
  21654. }
  21655. const { attribute } = this.getAttributeData();
  21656. return attribute.getNodeType( builder );
  21657. }
  21658. /**
  21659. * Generates the code snippet of the storage buffer node.
  21660. *
  21661. * @param {NodeBuilder} builder - The current node builder.
  21662. * @return {string} The generated code snippet.
  21663. */
  21664. generate( builder ) {
  21665. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  21666. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21667. return super.generate( builder );
  21668. }
  21669. const { attribute, varying } = this.getAttributeData();
  21670. const output = varying.build( builder );
  21671. builder.registerTransform( output, attribute );
  21672. return output;
  21673. }
  21674. }
  21675. /**
  21676. * TSL function for creating a storage buffer node.
  21677. *
  21678. * @tsl
  21679. * @function
  21680. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21681. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  21682. * @param {number} [count=0] - The buffer count.
  21683. * @returns {StorageBufferNode}
  21684. */
  21685. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21686. /**
  21687. * @tsl
  21688. * @function
  21689. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21690. *
  21691. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21692. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  21693. * @param {number} count - The buffer count.
  21694. * @returns {StorageBufferNode}
  21695. */
  21696. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21697. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21698. return storage( value, type, count ).setPBO( true );
  21699. };
  21700. /**
  21701. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21702. *
  21703. * @tsl
  21704. * @function
  21705. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21706. * @param {string|Struct} [type='float'] - The data type.
  21707. * @returns {StorageBufferNode}
  21708. */
  21709. const attributeArray = ( count, type = 'float' ) => {
  21710. let itemSize, typedArray;
  21711. if ( type.isStruct === true ) {
  21712. itemSize = type.layout.getLength();
  21713. typedArray = getTypedArrayFromType( 'float' );
  21714. } else {
  21715. itemSize = getLengthFromType( type );
  21716. typedArray = getTypedArrayFromType( type );
  21717. }
  21718. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21719. const node = storage( buffer, type, count );
  21720. return node;
  21721. };
  21722. /**
  21723. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21724. *
  21725. * @tsl
  21726. * @function
  21727. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21728. * @param {string|Struct} [type='float'] - The data type.
  21729. * @returns {StorageBufferNode}
  21730. */
  21731. const instancedArray = ( count, type = 'float' ) => {
  21732. let itemSize, typedArray;
  21733. if ( type.isStruct === true ) {
  21734. itemSize = type.layout.getLength();
  21735. typedArray = getTypedArrayFromType( 'float' );
  21736. } else {
  21737. itemSize = getLengthFromType( type );
  21738. typedArray = getTypedArrayFromType( type );
  21739. }
  21740. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21741. const node = storage( buffer, type, count );
  21742. return node;
  21743. };
  21744. /**
  21745. * An attribute node for representing vertex colors.
  21746. *
  21747. * @augments AttributeNode
  21748. */
  21749. class VertexColorNode extends AttributeNode {
  21750. static get type() {
  21751. return 'VertexColorNode';
  21752. }
  21753. /**
  21754. * Constructs a new vertex color node.
  21755. *
  21756. * @param {number} [index=0] - The attribute index.
  21757. */
  21758. constructor( index = 0 ) {
  21759. super( null, 'vec4' );
  21760. /**
  21761. * This flag can be used for type testing.
  21762. *
  21763. * @type {boolean}
  21764. * @readonly
  21765. * @default true
  21766. */
  21767. this.isVertexColorNode = true;
  21768. /**
  21769. * The attribute index to enable more than one sets of vertex colors.
  21770. *
  21771. * @type {number}
  21772. * @default 0
  21773. */
  21774. this.index = index;
  21775. }
  21776. /**
  21777. * Overwrites the default implementation by honoring the attribute index.
  21778. *
  21779. * @param {NodeBuilder} builder - The current node builder.
  21780. * @return {string} The attribute name.
  21781. */
  21782. getAttributeName( /*builder*/ ) {
  21783. const index = this.index;
  21784. return 'color' + ( index > 0 ? index : '' );
  21785. }
  21786. generate( builder ) {
  21787. const attributeName = this.getAttributeName( builder );
  21788. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21789. let result;
  21790. if ( geometryAttribute === true ) {
  21791. result = super.generate( builder );
  21792. } else {
  21793. // Vertex color fallback should be white
  21794. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21795. }
  21796. return result;
  21797. }
  21798. serialize( data ) {
  21799. super.serialize( data );
  21800. data.index = this.index;
  21801. }
  21802. deserialize( data ) {
  21803. super.deserialize( data );
  21804. this.index = data.index;
  21805. }
  21806. }
  21807. /**
  21808. * TSL function for creating a reference node.
  21809. *
  21810. * @tsl
  21811. * @function
  21812. * @param {number} index - The attribute index.
  21813. * @returns {VertexColorNode}
  21814. */
  21815. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21816. /**
  21817. * A node for representing the uv coordinates of points.
  21818. *
  21819. * Can only be used with a WebGL backend. In WebGPU, point
  21820. * primitives always have the size of one pixel and can thus
  21821. * can't be used as sprite-like objects that display textures.
  21822. *
  21823. * @augments Node
  21824. */
  21825. class PointUVNode extends Node {
  21826. static get type() {
  21827. return 'PointUVNode';
  21828. }
  21829. /**
  21830. * Constructs a new point uv node.
  21831. */
  21832. constructor() {
  21833. super( 'vec2' );
  21834. /**
  21835. * This flag can be used for type testing.
  21836. *
  21837. * @type {boolean}
  21838. * @readonly
  21839. * @default true
  21840. */
  21841. this.isPointUVNode = true;
  21842. }
  21843. generate( /*builder*/ ) {
  21844. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21845. }
  21846. }
  21847. /**
  21848. * TSL object that represents the uv coordinates of points.
  21849. *
  21850. * @tsl
  21851. * @type {PointUVNode}
  21852. */
  21853. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21854. const _e1 = /*@__PURE__*/ new Euler();
  21855. const _m1 = /*@__PURE__*/ new Matrix4();
  21856. /**
  21857. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21858. * are available for easier use:
  21859. *
  21860. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21861. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21862. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21863. *
  21864. * @augments Node
  21865. */
  21866. class SceneNode extends Node {
  21867. static get type() {
  21868. return 'SceneNode';
  21869. }
  21870. /**
  21871. * Constructs a new scene node.
  21872. *
  21873. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21874. * @param {?Scene} [scene=null] - A reference to the scene.
  21875. */
  21876. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21877. super();
  21878. /**
  21879. * The scope defines the type of scene property that is accessed.
  21880. *
  21881. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21882. */
  21883. this.scope = scope;
  21884. /**
  21885. * A reference to the scene that is going to be accessed.
  21886. *
  21887. * @type {?Scene}
  21888. * @default null
  21889. */
  21890. this.scene = scene;
  21891. }
  21892. /**
  21893. * Depending on the scope, the method returns a different type of node that represents
  21894. * the respective scene property.
  21895. *
  21896. * @param {NodeBuilder} builder - The current node builder.
  21897. * @return {Node} The output node.
  21898. */
  21899. setup( builder ) {
  21900. const scope = this.scope;
  21901. const scene = this.scene !== null ? this.scene : builder.scene;
  21902. let output;
  21903. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21904. output = reference( 'backgroundBlurriness', 'float', scene );
  21905. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21906. output = reference( 'backgroundIntensity', 'float', scene );
  21907. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21908. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21909. const background = scene.background;
  21910. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21911. _e1.copy( scene.backgroundRotation );
  21912. // accommodate left-handed frame
  21913. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  21914. _m1.makeRotationFromEuler( _e1 );
  21915. } else {
  21916. _m1.identity();
  21917. }
  21918. return _m1;
  21919. } );
  21920. } else {
  21921. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21922. }
  21923. return output;
  21924. }
  21925. }
  21926. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21927. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21928. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21929. /**
  21930. * TSL object that represents the scene's background blurriness.
  21931. *
  21932. * @tsl
  21933. * @type {SceneNode}
  21934. */
  21935. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21936. /**
  21937. * TSL object that represents the scene's background intensity.
  21938. *
  21939. * @tsl
  21940. * @type {SceneNode}
  21941. */
  21942. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21943. /**
  21944. * TSL object that represents the scene's background rotation.
  21945. *
  21946. * @tsl
  21947. * @type {SceneNode}
  21948. */
  21949. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21950. /**
  21951. * This special version of a texture node can be used to
  21952. * write data into a storage texture with a compute shader.
  21953. *
  21954. * ```js
  21955. * const storageTexture = new THREE.StorageTexture( width, height );
  21956. *
  21957. * const computeTexture = Fn( ( { storageTexture } ) => {
  21958. *
  21959. * const posX = instanceIndex.modInt( width );
  21960. * const posY = instanceIndex.div( width );
  21961. * const indexUV = uvec2( posX, posY );
  21962. *
  21963. * // generate RGB values
  21964. *
  21965. * const r = 1;
  21966. * const g = 1;
  21967. * const b = 1;
  21968. *
  21969. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21970. *
  21971. * } );
  21972. *
  21973. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21974. * renderer.computeAsync( computeNode );
  21975. * ```
  21976. *
  21977. * This node can only be used with a WebGPU backend.
  21978. *
  21979. * @augments TextureNode
  21980. */
  21981. class StorageTextureNode extends TextureNode {
  21982. static get type() {
  21983. return 'StorageTextureNode';
  21984. }
  21985. /**
  21986. * Constructs a new storage texture node.
  21987. *
  21988. * @param {StorageTexture} value - The storage texture.
  21989. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21990. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  21991. */
  21992. constructor( value, uvNode, storeNode = null ) {
  21993. super( value, uvNode );
  21994. /**
  21995. * The value node that should be stored in the texture.
  21996. *
  21997. * @type {?Node}
  21998. * @default null
  21999. */
  22000. this.storeNode = storeNode;
  22001. /**
  22002. * This flag can be used for type testing.
  22003. *
  22004. * @type {boolean}
  22005. * @readonly
  22006. * @default true
  22007. */
  22008. this.isStorageTextureNode = true;
  22009. /**
  22010. * The access type of the texture node.
  22011. *
  22012. * @type {string}
  22013. * @default 'writeOnly'
  22014. */
  22015. this.access = NodeAccess.WRITE_ONLY;
  22016. }
  22017. /**
  22018. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  22019. *
  22020. * @param {NodeBuilder} builder - The current node builder.
  22021. * @return {string} The input type.
  22022. */
  22023. getInputType( /*builder*/ ) {
  22024. return 'storageTexture';
  22025. }
  22026. setup( builder ) {
  22027. super.setup( builder );
  22028. const properties = builder.getNodeProperties( this );
  22029. properties.storeNode = this.storeNode;
  22030. }
  22031. /**
  22032. * Defines the node access.
  22033. *
  22034. * @param {string} value - The node access.
  22035. * @return {StorageTextureNode} A reference to this node.
  22036. */
  22037. setAccess( value ) {
  22038. this.access = value;
  22039. return this;
  22040. }
  22041. /**
  22042. * Generates the code snippet of the stroge node. If no `storeNode`
  22043. * is defined, the texture node is generated as normal texture.
  22044. *
  22045. * @param {NodeBuilder} builder - The current node builder.
  22046. * @param {string} output - The current output.
  22047. * @return {string} The generated code snippet.
  22048. */
  22049. generate( builder, output ) {
  22050. let snippet;
  22051. if ( this.storeNode !== null ) {
  22052. snippet = this.generateStore( builder );
  22053. } else {
  22054. snippet = super.generate( builder, output );
  22055. }
  22056. return snippet;
  22057. }
  22058. /**
  22059. * Convenience method for configuring a read/write node access.
  22060. *
  22061. * @return {StorageTextureNode} A reference to this node.
  22062. */
  22063. toReadWrite() {
  22064. return this.setAccess( NodeAccess.READ_WRITE );
  22065. }
  22066. /**
  22067. * Convenience method for configuring a read-only node access.
  22068. *
  22069. * @return {StorageTextureNode} A reference to this node.
  22070. */
  22071. toReadOnly() {
  22072. return this.setAccess( NodeAccess.READ_ONLY );
  22073. }
  22074. /**
  22075. * Convenience method for configuring a write-only node access.
  22076. *
  22077. * @return {StorageTextureNode} A reference to this node.
  22078. */
  22079. toWriteOnly() {
  22080. return this.setAccess( NodeAccess.WRITE_ONLY );
  22081. }
  22082. /**
  22083. * Generates the code snippet of the storage texture node.
  22084. *
  22085. * @param {NodeBuilder} builder - The current node builder.
  22086. */
  22087. generateStore( builder ) {
  22088. const properties = builder.getNodeProperties( this );
  22089. const { uvNode, storeNode } = properties;
  22090. const textureProperty = super.generate( builder, 'property' );
  22091. const uvSnippet = uvNode.build( builder, 'uvec2' );
  22092. const storeSnippet = storeNode.build( builder, 'vec4' );
  22093. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  22094. builder.addLineFlowCode( snippet, this );
  22095. }
  22096. }
  22097. /**
  22098. * TSL function for creating a storage texture node.
  22099. *
  22100. * @tsl
  22101. * @function
  22102. * @param {StorageTexture} value - The storage texture.
  22103. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22104. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22105. * @returns {StorageTextureNode}
  22106. */
  22107. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  22108. /**
  22109. * TODO: Explain difference to `storageTexture()`.
  22110. *
  22111. * @tsl
  22112. * @function
  22113. * @param {StorageTexture} value - The storage texture.
  22114. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22115. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22116. * @returns {StorageTextureNode}
  22117. */
  22118. const textureStore = ( value, uvNode, storeNode ) => {
  22119. const node = storageTexture( value, uvNode, storeNode );
  22120. if ( storeNode !== null ) node.append();
  22121. return node;
  22122. };
  22123. /**
  22124. * A special type of reference node that allows to link values in
  22125. * `userData` fields to node objects.
  22126. * ```js
  22127. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  22128. *
  22129. * const material = new THREE.SpriteNodeMaterial();
  22130. * material.rotationNode = userData( 'rotation', 'float' );
  22131. * ```
  22132. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  22133. * will automatically be updated when the `rotation` user data field changes.
  22134. *
  22135. * @augments ReferenceNode
  22136. */
  22137. class UserDataNode extends ReferenceNode {
  22138. static get type() {
  22139. return 'UserDataNode';
  22140. }
  22141. /**
  22142. * Constructs a new user data node.
  22143. *
  22144. * @param {string} property - The property name that should be referenced by the node.
  22145. * @param {string} inputType - The node data type of the reference.
  22146. * @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.
  22147. */
  22148. constructor( property, inputType, userData = null ) {
  22149. super( property, inputType, userData );
  22150. /**
  22151. * A reference to the `userData` object. If not provided, the `userData`
  22152. * property of the 3D object that uses the node material is evaluated.
  22153. *
  22154. * @type {?Object}
  22155. * @default null
  22156. */
  22157. this.userData = userData;
  22158. }
  22159. /**
  22160. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  22161. * `userData` field.
  22162. *
  22163. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  22164. * @return {Object} A reference to the `userData` field.
  22165. */
  22166. updateReference( state ) {
  22167. this.reference = this.userData !== null ? this.userData : state.object.userData;
  22168. return this.reference;
  22169. }
  22170. }
  22171. /**
  22172. * TSL function for creating a user data node.
  22173. *
  22174. * @tsl
  22175. * @function
  22176. * @param {string} name - The property name that should be referenced by the node.
  22177. * @param {string} inputType - The node data type of the reference.
  22178. * @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.
  22179. * @returns {UserDataNode}
  22180. */
  22181. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  22182. const _objectData = new WeakMap();
  22183. /**
  22184. * A node for representing motion or velocity vectors. Foundation
  22185. * for advanced post processing effects like motion blur or TRAA.
  22186. *
  22187. * The node keeps track of the model, view and projection matrices
  22188. * of the previous frame and uses them to compute offsets in NDC space.
  22189. * These offsets represent the final velocity.
  22190. *
  22191. * @augments TempNode
  22192. */
  22193. class VelocityNode extends TempNode {
  22194. static get type() {
  22195. return 'VelocityNode';
  22196. }
  22197. /**
  22198. * Constructs a new vertex color node.
  22199. */
  22200. constructor() {
  22201. super( 'vec2' );
  22202. /**
  22203. * The current projection matrix.
  22204. *
  22205. * @type {?Matrix4}
  22206. * @default null
  22207. */
  22208. this.projectionMatrix = null;
  22209. /**
  22210. * Overwritten since velocity nodes are updated per object.
  22211. *
  22212. * @type {string}
  22213. * @default 'object'
  22214. */
  22215. this.updateType = NodeUpdateType.OBJECT;
  22216. /**
  22217. * Overwritten since velocity nodes save data after the update.
  22218. *
  22219. * @type {string}
  22220. * @default 'object'
  22221. */
  22222. this.updateAfterType = NodeUpdateType.OBJECT;
  22223. /**
  22224. * Uniform node representing the previous model matrix in world space.
  22225. *
  22226. * @type {UniformNode<mat4>}
  22227. * @default null
  22228. */
  22229. this.previousModelWorldMatrix = uniform( new Matrix4() );
  22230. /**
  22231. * Uniform node representing the previous projection matrix.
  22232. *
  22233. * @type {UniformNode<mat4>}
  22234. * @default null
  22235. */
  22236. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  22237. /**
  22238. * Uniform node representing the previous view matrix.
  22239. *
  22240. * @type {UniformNode<mat4>}
  22241. * @default null
  22242. */
  22243. this.previousCameraViewMatrix = uniform( new Matrix4() );
  22244. }
  22245. /**
  22246. * Sets the given projection matrix.
  22247. *
  22248. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  22249. */
  22250. setProjectionMatrix( projectionMatrix ) {
  22251. this.projectionMatrix = projectionMatrix;
  22252. }
  22253. /**
  22254. * Updates velocity specific uniforms.
  22255. *
  22256. * @param {NodeFrame} frame - A reference to the current node frame.
  22257. */
  22258. update( { frameId, camera, object } ) {
  22259. const previousModelMatrix = getPreviousMatrix( object );
  22260. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  22261. //
  22262. const cameraData = getData( camera );
  22263. if ( cameraData.frameId !== frameId ) {
  22264. cameraData.frameId = frameId;
  22265. if ( cameraData.previousProjectionMatrix === undefined ) {
  22266. cameraData.previousProjectionMatrix = new Matrix4();
  22267. cameraData.previousCameraViewMatrix = new Matrix4();
  22268. cameraData.currentProjectionMatrix = new Matrix4();
  22269. cameraData.currentCameraViewMatrix = new Matrix4();
  22270. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  22271. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  22272. } else {
  22273. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  22274. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  22275. }
  22276. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  22277. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  22278. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  22279. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  22280. }
  22281. }
  22282. /**
  22283. * Overwritten to updated velocity specific uniforms.
  22284. *
  22285. * @param {NodeFrame} frame - A reference to the current node frame.
  22286. */
  22287. updateAfter( { object } ) {
  22288. getPreviousMatrix( object ).copy( object.matrixWorld );
  22289. }
  22290. /**
  22291. * Implements the velocity computation based on the previous and current vertex data.
  22292. *
  22293. * @param {NodeBuilder} builder - A reference to the current node builder.
  22294. * @return {Node<vec2>} The motion vector.
  22295. */
  22296. setup( /*builder*/ ) {
  22297. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  22298. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  22299. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22300. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  22301. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  22302. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  22303. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  22304. return velocity;
  22305. }
  22306. }
  22307. function getData( object ) {
  22308. let objectData = _objectData.get( object );
  22309. if ( objectData === undefined ) {
  22310. objectData = {};
  22311. _objectData.set( object, objectData );
  22312. }
  22313. return objectData;
  22314. }
  22315. function getPreviousMatrix( object, index = 0 ) {
  22316. const objectData = getData( object );
  22317. let matrix = objectData[ index ];
  22318. if ( matrix === undefined ) {
  22319. objectData[ index ] = matrix = new Matrix4();
  22320. }
  22321. return matrix;
  22322. }
  22323. /**
  22324. * TSL object that represents the velocity of a render pass.
  22325. *
  22326. * @tsl
  22327. * @type {VelocityNode}
  22328. */
  22329. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  22330. /**
  22331. * Represents a "Color Burn" blend mode.
  22332. *
  22333. * It's designed to darken the base layer's colors based on the color of the blend layer.
  22334. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  22335. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  22336. *
  22337. * @tsl
  22338. * @function
  22339. * @param {Node<vec3>} base - The base color.
  22340. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  22341. * @return {Node<vec3>} The result.
  22342. */
  22343. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22344. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  22345. } ).setLayout( {
  22346. name: 'blendBurn',
  22347. type: 'vec3',
  22348. inputs: [
  22349. { name: 'base', type: 'vec3' },
  22350. { name: 'blend', type: 'vec3' }
  22351. ]
  22352. } );
  22353. /**
  22354. * Represents a "Color Dodge" blend mode.
  22355. *
  22356. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  22357. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  22358. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  22359. *
  22360. * @tsl
  22361. * @function
  22362. * @param {Node<vec3>} base - The base color.
  22363. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22364. * @return {Node<vec3>} The result.
  22365. */
  22366. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22367. return min$1( base.div( blend.oneMinus() ), 1.0 );
  22368. } ).setLayout( {
  22369. name: 'blendDodge',
  22370. type: 'vec3',
  22371. inputs: [
  22372. { name: 'base', type: 'vec3' },
  22373. { name: 'blend', type: 'vec3' }
  22374. ]
  22375. } );
  22376. /**
  22377. * Represents a "Screen" blend mode.
  22378. *
  22379. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  22380. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  22381. * effects.
  22382. *
  22383. * @tsl
  22384. * @function
  22385. * @param {Node<vec3>} base - The base color.
  22386. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22387. * @return {Node<vec3>} The result.
  22388. */
  22389. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22390. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  22391. } ).setLayout( {
  22392. name: 'blendScreen',
  22393. type: 'vec3',
  22394. inputs: [
  22395. { name: 'base', type: 'vec3' },
  22396. { name: 'blend', type: 'vec3' }
  22397. ]
  22398. } );
  22399. /**
  22400. * Represents a "Overlay" blend mode.
  22401. *
  22402. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  22403. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  22404. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  22405. *
  22406. * @tsl
  22407. * @function
  22408. * @param {Node<vec3>} base - The base color.
  22409. * @param {Node<vec3>} blend - The blend color
  22410. * @return {Node<vec3>} The result.
  22411. */
  22412. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22413. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  22414. } ).setLayout( {
  22415. name: 'blendOverlay',
  22416. type: 'vec3',
  22417. inputs: [
  22418. { name: 'base', type: 'vec3' },
  22419. { name: 'blend', type: 'vec3' }
  22420. ]
  22421. } );
  22422. /**
  22423. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  22424. * It assumes both input colors have non-preumiltiplied alpha.
  22425. *
  22426. * @tsl
  22427. * @function
  22428. * @param {Node<vec4>} base - The base color.
  22429. * @param {Node<vec4>} blend - The blend color
  22430. * @return {Node<vec4>} The result.
  22431. */
  22432. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22433. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  22434. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  22435. } ).setLayout( {
  22436. name: 'blendColor',
  22437. type: 'vec4',
  22438. inputs: [
  22439. { name: 'base', type: 'vec4' },
  22440. { name: 'blend', type: 'vec4' }
  22441. ]
  22442. } );
  22443. // Deprecated
  22444. /**
  22445. * @tsl
  22446. * @function
  22447. * @deprecated since r171. Use {@link blendBurn} instead.
  22448. *
  22449. * @param {...any} params
  22450. * @returns {Function}
  22451. */
  22452. const burn = ( ...params ) => { // @deprecated, r171
  22453. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  22454. return blendBurn( params );
  22455. };
  22456. /**
  22457. * @tsl
  22458. * @function
  22459. * @deprecated since r171. Use {@link blendDodge} instead.
  22460. *
  22461. * @param {...any} params
  22462. * @returns {Function}
  22463. */
  22464. const dodge = ( ...params ) => { // @deprecated, r171
  22465. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  22466. return blendDodge( params );
  22467. };
  22468. /**
  22469. * @tsl
  22470. * @function
  22471. * @deprecated since r171. Use {@link blendScreen} instead.
  22472. *
  22473. * @param {...any} params
  22474. * @returns {Function}
  22475. */
  22476. const screen = ( ...params ) => { // @deprecated, r171
  22477. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  22478. return blendScreen( params );
  22479. };
  22480. /**
  22481. * @tsl
  22482. * @function
  22483. * @deprecated since r171. Use {@link blendOverlay} instead.
  22484. *
  22485. * @param {...any} params
  22486. * @returns {Function}
  22487. */
  22488. const overlay = ( ...params ) => { // @deprecated, r171
  22489. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  22490. return blendOverlay( params );
  22491. };
  22492. /**
  22493. * Computes a grayscale value for the given RGB color value.
  22494. *
  22495. * @tsl
  22496. * @function
  22497. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  22498. * @return {Node<vec3>} The grayscale color.
  22499. */
  22500. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22501. return luminance( color.rgb );
  22502. } );
  22503. /**
  22504. * Super-saturates or desaturates the given RGB color.
  22505. *
  22506. * @tsl
  22507. * @function
  22508. * @param {Node<vec3>} color - The input color.
  22509. * @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.
  22510. * @return {Node<vec3>} The saturated color.
  22511. */
  22512. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22513. return adjustment.mix( luminance( color.rgb ), color.rgb );
  22514. } );
  22515. /**
  22516. * Selectively enhance the intensity of less saturated RGB colors. Can result
  22517. * in a more natural and visually appealing image with enhanced color depth
  22518. * compared to {@link ColorAdjustment#saturation}.
  22519. *
  22520. * @tsl
  22521. * @function
  22522. * @param {Node<vec3>} color - The input color.
  22523. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  22524. * @return {Node<vec3>} The updated color.
  22525. */
  22526. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22527. const average = add( color.r, color.g, color.b ).div( 3.0 );
  22528. const mx = color.r.max( color.g.max( color.b ) );
  22529. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  22530. return mix( color.rgb, mx, amt );
  22531. } );
  22532. /**
  22533. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  22534. *
  22535. * @tsl
  22536. * @function
  22537. * @param {Node<vec3>} color - The input color.
  22538. * @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.
  22539. * @return {Node<vec3>} The updated color.
  22540. */
  22541. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22542. const k = vec3( 0.57735, 0.57735, 0.57735 );
  22543. const cosAngle = adjustment.cos();
  22544. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  22545. } );
  22546. /**
  22547. * Computes the luminance for the given RGB color value.
  22548. *
  22549. * @tsl
  22550. * @function
  22551. * @param {Node<vec3>} color - The color value to compute the luminance for.
  22552. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  22553. * @return {Node<vec3>} The luminance.
  22554. */
  22555. const luminance = (
  22556. color,
  22557. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  22558. ) => dot( color, luminanceCoefficients );
  22559. /**
  22560. * Color Decision List (CDL) v1.2
  22561. *
  22562. * Compact representation of color grading information, defined by slope, offset, power, and
  22563. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  22564. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  22565. *
  22566. * @tsl
  22567. * @function
  22568. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  22569. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  22570. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  22571. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  22572. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  22573. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  22574. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  22575. *
  22576. * References:
  22577. * - ASC CDL v1.2
  22578. * - {@link https://blender.stackexchange.com/a/55239/43930}
  22579. * - {@link https://docs.acescentral.com/specifications/acescc/}
  22580. */
  22581. const cdl = /*@__PURE__*/ Fn( ( [
  22582. color,
  22583. slope = vec3( 1 ),
  22584. offset = vec3( 0 ),
  22585. power = vec3( 1 ),
  22586. saturation = float( 1 ),
  22587. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  22588. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  22589. ] ) => {
  22590. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  22591. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  22592. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  22593. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  22594. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  22595. const pv = v.pow( power ).toVar();
  22596. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  22597. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  22598. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  22599. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  22600. return vec4( v.rgb, color.a );
  22601. } );
  22602. /**
  22603. * Represents a posterize effect which reduces the number of colors
  22604. * in an image, resulting in a more blocky and stylized appearance.
  22605. *
  22606. * @augments TempNode
  22607. */
  22608. class PosterizeNode extends TempNode {
  22609. static get type() {
  22610. return 'PosterizeNode';
  22611. }
  22612. /**
  22613. * Constructs a new posterize node.
  22614. *
  22615. * @param {Node} sourceNode - The input color.
  22616. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22617. */
  22618. constructor( sourceNode, stepsNode ) {
  22619. super();
  22620. /**
  22621. * The input color.
  22622. *
  22623. * @type {Node}
  22624. */
  22625. this.sourceNode = sourceNode;
  22626. /**
  22627. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22628. *
  22629. * @type {Node}
  22630. */
  22631. this.stepsNode = stepsNode;
  22632. }
  22633. setup() {
  22634. const { sourceNode, stepsNode } = this;
  22635. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  22636. }
  22637. }
  22638. /**
  22639. * TSL function for creating a posterize node.
  22640. *
  22641. * @tsl
  22642. * @function
  22643. * @param {Node} sourceNode - The input color.
  22644. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22645. * @returns {PosterizeNode}
  22646. */
  22647. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  22648. const _size = /*@__PURE__*/ new Vector2();
  22649. /**
  22650. * Represents the texture of a pass node.
  22651. *
  22652. * @augments TextureNode
  22653. */
  22654. class PassTextureNode extends TextureNode {
  22655. static get type() {
  22656. return 'PassTextureNode';
  22657. }
  22658. /**
  22659. * Constructs a new pass texture node.
  22660. *
  22661. * @param {PassNode} passNode - The pass node.
  22662. * @param {Texture} texture - The output texture.
  22663. */
  22664. constructor( passNode, texture ) {
  22665. super( texture );
  22666. /**
  22667. * A reference to the pass node.
  22668. *
  22669. * @type {PassNode}
  22670. */
  22671. this.passNode = passNode;
  22672. this.setUpdateMatrix( false );
  22673. }
  22674. setup( builder ) {
  22675. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22676. return super.setup( builder );
  22677. }
  22678. clone() {
  22679. return new this.constructor( this.passNode, this.value );
  22680. }
  22681. }
  22682. /**
  22683. * An extension of `PassTextureNode` which allows to manage more than one
  22684. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22685. *
  22686. * @augments PassTextureNode
  22687. */
  22688. class PassMultipleTextureNode extends PassTextureNode {
  22689. static get type() {
  22690. return 'PassMultipleTextureNode';
  22691. }
  22692. /**
  22693. * Constructs a new pass texture node.
  22694. *
  22695. * @param {PassNode} passNode - The pass node.
  22696. * @param {string} textureName - The output texture name.
  22697. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22698. */
  22699. constructor( passNode, textureName, previousTexture = false ) {
  22700. // null is passed to the super call since this class does not
  22701. // use an external texture for rendering pass data into. Instead
  22702. // the texture is managed by the pass node itself
  22703. super( passNode, null );
  22704. /**
  22705. * The output texture name.
  22706. *
  22707. * @type {string}
  22708. */
  22709. this.textureName = textureName;
  22710. /**
  22711. * Whether previous frame data should be used or not.
  22712. *
  22713. * @type {boolean}
  22714. */
  22715. this.previousTexture = previousTexture;
  22716. }
  22717. /**
  22718. * Updates the texture reference of this node.
  22719. */
  22720. updateTexture() {
  22721. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22722. }
  22723. setup( builder ) {
  22724. this.updateTexture();
  22725. return super.setup( builder );
  22726. }
  22727. clone() {
  22728. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22729. }
  22730. }
  22731. /**
  22732. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22733. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22734. * via MRT for further processing.
  22735. *
  22736. * ```js
  22737. * const postProcessing = new PostProcessing( renderer );
  22738. *
  22739. * const scenePass = pass( scene, camera );
  22740. *
  22741. * postProcessing.outputNode = scenePass;
  22742. * ```
  22743. *
  22744. * @augments TempNode
  22745. */
  22746. class PassNode extends TempNode {
  22747. static get type() {
  22748. return 'PassNode';
  22749. }
  22750. /**
  22751. * Constructs a new pass node.
  22752. *
  22753. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22754. * @param {Scene} scene - A reference to the scene.
  22755. * @param {Camera} camera - A reference to the camera.
  22756. * @param {Object} options - Options for the internal render target.
  22757. */
  22758. constructor( scope, scene, camera, options = {} ) {
  22759. super( 'vec4' );
  22760. /**
  22761. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22762. *
  22763. * @type {('color'|'depth')}
  22764. */
  22765. this.scope = scope;
  22766. /**
  22767. * A reference to the scene.
  22768. *
  22769. * @type {Scene}
  22770. */
  22771. this.scene = scene;
  22772. /**
  22773. * A reference to the camera.
  22774. *
  22775. * @type {Camera}
  22776. */
  22777. this.camera = camera;
  22778. /**
  22779. * Options for the internal render target.
  22780. *
  22781. * @type {Object}
  22782. */
  22783. this.options = options;
  22784. /**
  22785. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22786. *
  22787. * @private
  22788. * @type {number}
  22789. * @default 1
  22790. */
  22791. this._pixelRatio = 1;
  22792. /**
  22793. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22794. * @private
  22795. * @type {number}
  22796. * @default 1
  22797. */
  22798. this._width = 1;
  22799. /**
  22800. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22801. * @private
  22802. * @type {number}
  22803. * @default 1
  22804. */
  22805. this._height = 1;
  22806. const depthTexture = new DepthTexture();
  22807. depthTexture.isRenderTargetTexture = true;
  22808. //depthTexture.type = FloatType;
  22809. depthTexture.name = 'depth';
  22810. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22811. renderTarget.texture.name = 'output';
  22812. renderTarget.depthTexture = depthTexture;
  22813. /**
  22814. * The pass's render target.
  22815. *
  22816. * @type {RenderTarget}
  22817. */
  22818. this.renderTarget = renderTarget;
  22819. /**
  22820. * A dictionary holding the internal result textures.
  22821. *
  22822. * @private
  22823. * @type {Object<string, Texture>}
  22824. */
  22825. this._textures = {
  22826. output: renderTarget.texture,
  22827. depth: depthTexture
  22828. };
  22829. /**
  22830. * A dictionary holding the internal texture nodes.
  22831. *
  22832. * @private
  22833. * @type {Object<string, TextureNode>}
  22834. */
  22835. this._textureNodes = {};
  22836. /**
  22837. * A dictionary holding the internal depth nodes.
  22838. *
  22839. * @private
  22840. * @type {Object}
  22841. */
  22842. this._linearDepthNodes = {};
  22843. /**
  22844. * A dictionary holding the internal viewZ nodes.
  22845. *
  22846. * @private
  22847. * @type {Object}
  22848. */
  22849. this._viewZNodes = {};
  22850. /**
  22851. * A dictionary holding the texture data of the previous frame.
  22852. * Used for computing velocity/motion vectors.
  22853. *
  22854. * @private
  22855. * @type {Object<string, Texture>}
  22856. */
  22857. this._previousTextures = {};
  22858. /**
  22859. * A dictionary holding the texture nodes of the previous frame.
  22860. * Used for computing velocity/motion vectors.
  22861. *
  22862. * @private
  22863. * @type {Object<string, TextureNode>}
  22864. */
  22865. this._previousTextureNodes = {};
  22866. /**
  22867. * The `near` property of the camera as a uniform.
  22868. *
  22869. * @private
  22870. * @type {UniformNode}
  22871. */
  22872. this._cameraNear = uniform( 0 );
  22873. /**
  22874. * The `far` property of the camera as a uniform.
  22875. *
  22876. * @private
  22877. * @type {UniformNode}
  22878. */
  22879. this._cameraFar = uniform( 0 );
  22880. /**
  22881. * A MRT node configuring the MRT settings.
  22882. *
  22883. * @private
  22884. * @type {?MRTNode}
  22885. * @default null
  22886. */
  22887. this._mrt = null;
  22888. /**
  22889. * This flag can be used for type testing.
  22890. *
  22891. * @type {boolean}
  22892. * @readonly
  22893. * @default true
  22894. */
  22895. this.isPassNode = true;
  22896. /**
  22897. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22898. * scene once per frame in its {@link PassNode#updateBefore} method.
  22899. *
  22900. * @type {string}
  22901. * @default 'frame'
  22902. */
  22903. this.updateBeforeType = NodeUpdateType.FRAME;
  22904. }
  22905. /**
  22906. * Sets the given MRT node to setup MRT for this pass.
  22907. *
  22908. * @param {MRTNode} mrt - The MRT object.
  22909. * @return {PassNode} A reference to this pass.
  22910. */
  22911. setMRT( mrt ) {
  22912. this._mrt = mrt;
  22913. return this;
  22914. }
  22915. /**
  22916. * Returns the current MRT node.
  22917. *
  22918. * @return {MRTNode} The current MRT node.
  22919. */
  22920. getMRT() {
  22921. return this._mrt;
  22922. }
  22923. /**
  22924. * The method is overwritten so it always returns `true`.
  22925. *
  22926. * @return {boolean} Whether this node is global or not.
  22927. */
  22928. isGlobal() {
  22929. return true;
  22930. }
  22931. /**
  22932. * Returns the texture for the given output name.
  22933. *
  22934. * @param {string} name - The output name to get the texture for.
  22935. * @return {Texture} The texture.
  22936. */
  22937. getTexture( name ) {
  22938. let texture = this._textures[ name ];
  22939. if ( texture === undefined ) {
  22940. const refTexture = this.renderTarget.texture;
  22941. texture = refTexture.clone();
  22942. texture.name = name;
  22943. this._textures[ name ] = texture;
  22944. this.renderTarget.textures.push( texture );
  22945. }
  22946. return texture;
  22947. }
  22948. /**
  22949. * Returns the texture holding the data of the previous frame for the given output name.
  22950. *
  22951. * @param {string} name - The output name to get the texture for.
  22952. * @return {Texture} The texture holding the data of the previous frame.
  22953. */
  22954. getPreviousTexture( name ) {
  22955. let texture = this._previousTextures[ name ];
  22956. if ( texture === undefined ) {
  22957. texture = this.getTexture( name ).clone();
  22958. this._previousTextures[ name ] = texture;
  22959. }
  22960. return texture;
  22961. }
  22962. /**
  22963. * Switches current and previous textures for the given output name.
  22964. *
  22965. * @param {string} name - The output name.
  22966. */
  22967. toggleTexture( name ) {
  22968. const prevTexture = this._previousTextures[ name ];
  22969. if ( prevTexture !== undefined ) {
  22970. const texture = this._textures[ name ];
  22971. const index = this.renderTarget.textures.indexOf( texture );
  22972. this.renderTarget.textures[ index ] = prevTexture;
  22973. this._textures[ name ] = prevTexture;
  22974. this._previousTextures[ name ] = texture;
  22975. this._textureNodes[ name ].updateTexture();
  22976. this._previousTextureNodes[ name ].updateTexture();
  22977. }
  22978. }
  22979. /**
  22980. * Returns the texture node for the given output name.
  22981. *
  22982. * @param {string} [name='output'] - The output name to get the texture node for.
  22983. * @return {TextureNode} The texture node.
  22984. */
  22985. getTextureNode( name = 'output' ) {
  22986. let textureNode = this._textureNodes[ name ];
  22987. if ( textureNode === undefined ) {
  22988. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22989. textureNode.updateTexture();
  22990. this._textureNodes[ name ] = textureNode;
  22991. }
  22992. return textureNode;
  22993. }
  22994. /**
  22995. * Returns the previous texture node for the given output name.
  22996. *
  22997. * @param {string} [name='output'] - The output name to get the previous texture node for.
  22998. * @return {TextureNode} The previous texture node.
  22999. */
  23000. getPreviousTextureNode( name = 'output' ) {
  23001. let textureNode = this._previousTextureNodes[ name ];
  23002. if ( textureNode === undefined ) {
  23003. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  23004. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  23005. textureNode.updateTexture();
  23006. this._previousTextureNodes[ name ] = textureNode;
  23007. }
  23008. return textureNode;
  23009. }
  23010. /**
  23011. * Returns a viewZ node of this pass.
  23012. *
  23013. * @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.
  23014. * @return {Node} The viewZ node.
  23015. */
  23016. getViewZNode( name = 'depth' ) {
  23017. let viewZNode = this._viewZNodes[ name ];
  23018. if ( viewZNode === undefined ) {
  23019. const cameraNear = this._cameraNear;
  23020. const cameraFar = this._cameraFar;
  23021. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  23022. }
  23023. return viewZNode;
  23024. }
  23025. /**
  23026. * Returns a linear depth node of this pass.
  23027. *
  23028. * @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.
  23029. * @return {Node} The linear depth node.
  23030. */
  23031. getLinearDepthNode( name = 'depth' ) {
  23032. let linearDepthNode = this._linearDepthNodes[ name ];
  23033. if ( linearDepthNode === undefined ) {
  23034. const cameraNear = this._cameraNear;
  23035. const cameraFar = this._cameraFar;
  23036. const viewZNode = this.getViewZNode( name );
  23037. // TODO: just if ( builder.camera.isPerspectiveCamera )
  23038. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  23039. }
  23040. return linearDepthNode;
  23041. }
  23042. setup( { renderer } ) {
  23043. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  23044. // TODO: Disable MSAA for WebGL backend for now
  23045. if ( renderer.backend.isWebGLBackend === true ) {
  23046. this.renderTarget.samples = 0;
  23047. }
  23048. this.renderTarget.texture.type = renderer.getColorBufferType();
  23049. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  23050. }
  23051. updateBefore( frame ) {
  23052. const { renderer } = frame;
  23053. const { scene } = this;
  23054. let camera;
  23055. let pixelRatio;
  23056. const outputRenderTarget = renderer.getOutputRenderTarget();
  23057. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  23058. pixelRatio = 1;
  23059. camera = renderer.xr.getCamera();
  23060. renderer.xr.updateCamera( camera );
  23061. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  23062. } else {
  23063. camera = this.camera;
  23064. pixelRatio = renderer.getPixelRatio();
  23065. renderer.getSize( _size );
  23066. }
  23067. this._pixelRatio = pixelRatio;
  23068. this.setSize( _size.width, _size.height );
  23069. const currentRenderTarget = renderer.getRenderTarget();
  23070. const currentMRT = renderer.getMRT();
  23071. this._cameraNear.value = camera.near;
  23072. this._cameraFar.value = camera.far;
  23073. for ( const name in this._previousTextures ) {
  23074. this.toggleTexture( name );
  23075. }
  23076. renderer.setRenderTarget( this.renderTarget );
  23077. renderer.setMRT( this._mrt );
  23078. renderer.render( scene, camera );
  23079. renderer.setRenderTarget( currentRenderTarget );
  23080. renderer.setMRT( currentMRT );
  23081. }
  23082. /**
  23083. * Sets the size of the pass's render target. Honors the pixel ratio.
  23084. *
  23085. * @param {number} width - The width to set.
  23086. * @param {number} height - The height to set.
  23087. */
  23088. setSize( width, height ) {
  23089. this._width = width;
  23090. this._height = height;
  23091. const effectiveWidth = this._width * this._pixelRatio;
  23092. const effectiveHeight = this._height * this._pixelRatio;
  23093. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23094. }
  23095. /**
  23096. * Sets the pixel ratio the pass's render target and updates the size.
  23097. *
  23098. * @param {number} pixelRatio - The pixel ratio to set.
  23099. */
  23100. setPixelRatio( pixelRatio ) {
  23101. this._pixelRatio = pixelRatio;
  23102. this.setSize( this._width, this._height );
  23103. }
  23104. /**
  23105. * Frees internal resources. Should be called when the node is no longer in use.
  23106. */
  23107. dispose() {
  23108. this.renderTarget.dispose();
  23109. }
  23110. }
  23111. PassNode.COLOR = 'color';
  23112. PassNode.DEPTH = 'depth';
  23113. /**
  23114. * TSL function for creating a pass node.
  23115. *
  23116. * @tsl
  23117. * @function
  23118. * @param {Scene} scene - A reference to the scene.
  23119. * @param {Camera} camera - A reference to the camera.
  23120. * @param {Object} options - Options for the internal render target.
  23121. * @returns {PassNode}
  23122. */
  23123. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  23124. /**
  23125. * TSL function for creating a pass texture node.
  23126. *
  23127. * @tsl
  23128. * @function
  23129. * @param {PassNode} pass - The pass node.
  23130. * @param {Texture} texture - The output texture.
  23131. * @returns {PassTextureNode}
  23132. */
  23133. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  23134. /**
  23135. * TSL function for creating a depth pass node.
  23136. *
  23137. * @tsl
  23138. * @function
  23139. * @param {Scene} scene - A reference to the scene.
  23140. * @param {Camera} camera - A reference to the camera.
  23141. * @param {Object} options - Options for the internal render target.
  23142. * @returns {PassNode}
  23143. */
  23144. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  23145. /**
  23146. * Represents a render pass for producing a toon outline effect on compatible objects.
  23147. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  23148. * will receive the outline.
  23149. *
  23150. * ```js
  23151. * const postProcessing = new PostProcessing( renderer );
  23152. *
  23153. * const scenePass = toonOutlinePass( scene, camera );
  23154. *
  23155. * postProcessing.outputNode = scenePass;
  23156. * ```
  23157. * @augments PassNode
  23158. */
  23159. class ToonOutlinePassNode extends PassNode {
  23160. static get type() {
  23161. return 'ToonOutlinePassNode';
  23162. }
  23163. /**
  23164. * Constructs a new outline pass node.
  23165. *
  23166. * @param {Scene} scene - A reference to the scene.
  23167. * @param {Camera} camera - A reference to the camera.
  23168. * @param {Node} colorNode - Defines the outline's color.
  23169. * @param {Node} thicknessNode - Defines the outline's thickness.
  23170. * @param {Node} alphaNode - Defines the outline's alpha.
  23171. */
  23172. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  23173. super( PassNode.COLOR, scene, camera );
  23174. /**
  23175. * Defines the outline's color.
  23176. *
  23177. * @type {Node}
  23178. */
  23179. this.colorNode = colorNode;
  23180. /**
  23181. * Defines the outline's thickness.
  23182. *
  23183. * @type {Node}
  23184. */
  23185. this.thicknessNode = thicknessNode;
  23186. /**
  23187. * Defines the outline's alpha.
  23188. *
  23189. * @type {Node}
  23190. */
  23191. this.alphaNode = alphaNode;
  23192. /**
  23193. * An internal material cache.
  23194. *
  23195. * @private
  23196. * @type {WeakMap<Material, NodeMaterial>}
  23197. */
  23198. this._materialCache = new WeakMap();
  23199. }
  23200. updateBefore( frame ) {
  23201. const { renderer } = frame;
  23202. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  23203. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  23204. // only render outline for supported materials
  23205. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  23206. if ( material.wireframe === false ) {
  23207. const outlineMaterial = this._getOutlineMaterial( material );
  23208. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  23209. }
  23210. }
  23211. // default
  23212. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  23213. } );
  23214. super.updateBefore( frame );
  23215. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  23216. }
  23217. /**
  23218. * Creates the material used for outline rendering.
  23219. *
  23220. * @private
  23221. * @return {NodeMaterial} The outline material.
  23222. */
  23223. _createMaterial() {
  23224. const material = new NodeMaterial();
  23225. material.isMeshToonOutlineMaterial = true;
  23226. material.name = 'Toon_Outline';
  23227. material.side = BackSide;
  23228. // vertex node
  23229. const outlineNormal = normalLocal.negate();
  23230. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  23231. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  23232. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  23233. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  23234. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  23235. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  23236. // color node
  23237. material.colorNode = vec4( this.colorNode, this.alphaNode );
  23238. return material;
  23239. }
  23240. /**
  23241. * For the given toon material, this method returns a corresponding
  23242. * outline material.
  23243. *
  23244. * @private
  23245. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  23246. * @return {NodeMaterial} The outline material.
  23247. */
  23248. _getOutlineMaterial( originalMaterial ) {
  23249. let outlineMaterial = this._materialCache.get( originalMaterial );
  23250. if ( outlineMaterial === undefined ) {
  23251. outlineMaterial = this._createMaterial();
  23252. this._materialCache.set( originalMaterial, outlineMaterial );
  23253. }
  23254. return outlineMaterial;
  23255. }
  23256. }
  23257. /**
  23258. * TSL function for creating a toon outline pass node.
  23259. *
  23260. * @tsl
  23261. * @function
  23262. * @param {Scene} scene - A reference to the scene.
  23263. * @param {Camera} camera - A reference to the camera.
  23264. * @param {Color} color - Defines the outline's color.
  23265. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  23266. * @param {number} [alpha=1] - Defines the outline's alpha.
  23267. * @returns {ToonOutlinePassNode}
  23268. */
  23269. 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 ) ) );
  23270. /**
  23271. * Linear tone mapping, exposure only.
  23272. *
  23273. * @tsl
  23274. * @function
  23275. * @param {Node<vec3>} color - The color that should be tone mapped.
  23276. * @param {Node<float>} exposure - The exposure.
  23277. * @return {Node<vec3>} The tone mapped color.
  23278. */
  23279. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23280. return color.mul( exposure ).clamp();
  23281. } ).setLayout( {
  23282. name: 'linearToneMapping',
  23283. type: 'vec3',
  23284. inputs: [
  23285. { name: 'color', type: 'vec3' },
  23286. { name: 'exposure', type: 'float' }
  23287. ]
  23288. } );
  23289. /**
  23290. * Reinhard tone mapping.
  23291. *
  23292. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  23293. *
  23294. * @tsl
  23295. * @function
  23296. * @param {Node<vec3>} color - The color that should be tone mapped.
  23297. * @param {Node<float>} exposure - The exposure.
  23298. * @return {Node<vec3>} The tone mapped color.
  23299. */
  23300. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23301. color = color.mul( exposure );
  23302. return color.div( color.add( 1.0 ) ).clamp();
  23303. } ).setLayout( {
  23304. name: 'reinhardToneMapping',
  23305. type: 'vec3',
  23306. inputs: [
  23307. { name: 'color', type: 'vec3' },
  23308. { name: 'exposure', type: 'float' }
  23309. ]
  23310. } );
  23311. /**
  23312. * Cineon tone mapping.
  23313. *
  23314. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  23315. *
  23316. * @tsl
  23317. * @function
  23318. * @param {Node<vec3>} color - The color that should be tone mapped.
  23319. * @param {Node<float>} exposure - The exposure.
  23320. * @return {Node<vec3>} The tone mapped color.
  23321. */
  23322. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23323. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  23324. color = color.mul( exposure );
  23325. color = color.sub( 0.004 ).max( 0.0 );
  23326. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  23327. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  23328. return a.div( b ).pow( 2.2 );
  23329. } ).setLayout( {
  23330. name: 'cineonToneMapping',
  23331. type: 'vec3',
  23332. inputs: [
  23333. { name: 'color', type: 'vec3' },
  23334. { name: 'exposure', type: 'float' }
  23335. ]
  23336. } );
  23337. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  23338. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23339. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  23340. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  23341. return a.div( b );
  23342. } );
  23343. /**
  23344. * ACESFilmic tone mapping.
  23345. *
  23346. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  23347. *
  23348. * @tsl
  23349. * @function
  23350. * @param {Node<vec3>} color - The color that should be tone mapped.
  23351. * @param {Node<float>} exposure - The exposure.
  23352. * @return {Node<vec3>} The tone mapped color.
  23353. */
  23354. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23355. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  23356. const ACESInputMat = mat3(
  23357. 0.59719, 0.35458, 0.04823,
  23358. 0.07600, 0.90834, 0.01566,
  23359. 0.02840, 0.13383, 0.83777
  23360. );
  23361. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  23362. const ACESOutputMat = mat3(
  23363. 1.60475, -0.53108, -0.07367,
  23364. -0.10208, 1.10813, -605e-5,
  23365. -327e-5, -0.07276, 1.07602
  23366. );
  23367. color = color.mul( exposure ).div( 0.6 );
  23368. color = ACESInputMat.mul( color );
  23369. // Apply RRT and ODT
  23370. color = RRTAndODTFit( color );
  23371. color = ACESOutputMat.mul( color );
  23372. // Clamp to [0, 1]
  23373. return color.clamp();
  23374. } ).setLayout( {
  23375. name: 'acesFilmicToneMapping',
  23376. type: 'vec3',
  23377. inputs: [
  23378. { name: 'color', type: 'vec3' },
  23379. { name: 'exposure', type: 'float' }
  23380. ]
  23381. } );
  23382. 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 ) );
  23383. 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 ) );
  23384. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  23385. const x = vec3( x_immutable ).toVar();
  23386. const x2 = vec3( x.mul( x ) ).toVar();
  23387. const x4 = vec3( x2.mul( x2 ) ).toVar();
  23388. 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 ) ) ) );
  23389. } );
  23390. /**
  23391. * AgX tone mapping.
  23392. *
  23393. * @tsl
  23394. * @function
  23395. * @param {Node<vec3>} color - The color that should be tone mapped.
  23396. * @param {Node<float>} exposure - The exposure.
  23397. * @return {Node<vec3>} The tone mapped color.
  23398. */
  23399. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23400. const colortone = vec3( color ).toVar();
  23401. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  23402. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  23403. const AgxMinEv = float( -12.47393 );
  23404. const AgxMaxEv = float( 4.026069 );
  23405. colortone.mulAssign( exposure );
  23406. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  23407. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  23408. colortone.assign( max$1( colortone, 1e-10 ) );
  23409. colortone.assign( log2( colortone ) );
  23410. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  23411. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23412. colortone.assign( agxDefaultContrastApprox( colortone ) );
  23413. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  23414. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  23415. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  23416. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23417. return colortone;
  23418. } ).setLayout( {
  23419. name: 'agxToneMapping',
  23420. type: 'vec3',
  23421. inputs: [
  23422. { name: 'color', type: 'vec3' },
  23423. { name: 'exposure', type: 'float' }
  23424. ]
  23425. } );
  23426. /**
  23427. * Neutral tone mapping.
  23428. *
  23429. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  23430. *
  23431. * @tsl
  23432. * @function
  23433. * @param {Node<vec3>} color - The color that should be tone mapped.
  23434. * @param {Node<float>} exposure - The exposure.
  23435. * @return {Node<vec3>} The tone mapped color.
  23436. */
  23437. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23438. const StartCompression = float( 0.8 - 0.04 );
  23439. const Desaturation = float( 0.15 );
  23440. color = color.mul( exposure );
  23441. const x = min$1( color.r, min$1( color.g, color.b ) );
  23442. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  23443. color.subAssign( offset );
  23444. const peak = max$1( color.r, max$1( color.g, color.b ) );
  23445. If( peak.lessThan( StartCompression ), () => {
  23446. return color;
  23447. } );
  23448. const d = sub( 1, StartCompression );
  23449. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  23450. color.mulAssign( newPeak.div( peak ) );
  23451. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  23452. return mix( color, vec3( newPeak ), g );
  23453. } ).setLayout( {
  23454. name: 'neutralToneMapping',
  23455. type: 'vec3',
  23456. inputs: [
  23457. { name: 'color', type: 'vec3' },
  23458. { name: 'exposure', type: 'float' }
  23459. ]
  23460. } );
  23461. /**
  23462. * This class represents native code sections. It is the base
  23463. * class for modules like {@link FunctionNode} which allows to implement
  23464. * functions with native shader languages.
  23465. *
  23466. * @augments Node
  23467. */
  23468. class CodeNode extends Node {
  23469. static get type() {
  23470. return 'CodeNode';
  23471. }
  23472. /**
  23473. * Constructs a new code node.
  23474. *
  23475. * @param {string} [code=''] - The native code.
  23476. * @param {Array<Node>} [includes=[]] - An array of includes.
  23477. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23478. */
  23479. constructor( code = '', includes = [], language = '' ) {
  23480. super( 'code' );
  23481. /**
  23482. * This flag can be used for type testing.
  23483. *
  23484. * @type {boolean}
  23485. * @readonly
  23486. * @default true
  23487. */
  23488. this.isCodeNode = true;
  23489. /**
  23490. * The native code.
  23491. *
  23492. * @type {string}
  23493. * @default ''
  23494. */
  23495. this.code = code;
  23496. /**
  23497. * An array of includes
  23498. *
  23499. * @type {Array<Node>}
  23500. * @default []
  23501. */
  23502. this.includes = includes;
  23503. /**
  23504. * The used language.
  23505. *
  23506. * @type {('js'|'wgsl'|'glsl')}
  23507. * @default ''
  23508. */
  23509. this.language = language;
  23510. }
  23511. /**
  23512. * The method is overwritten so it always returns `true`.
  23513. *
  23514. * @return {boolean} Whether this node is global or not.
  23515. */
  23516. isGlobal() {
  23517. return true;
  23518. }
  23519. /**
  23520. * Sets the includes of this code node.
  23521. *
  23522. * @param {Array<Node>} includes - The includes to set.
  23523. * @return {CodeNode} A reference to this node.
  23524. */
  23525. setIncludes( includes ) {
  23526. this.includes = includes;
  23527. return this;
  23528. }
  23529. /**
  23530. * Returns the includes of this code node.
  23531. *
  23532. * @param {NodeBuilder} builder - The current node builder.
  23533. * @return {Array<Node>} The includes.
  23534. */
  23535. getIncludes( /*builder*/ ) {
  23536. return this.includes;
  23537. }
  23538. generate( builder ) {
  23539. const includes = this.getIncludes( builder );
  23540. for ( const include of includes ) {
  23541. include.build( builder );
  23542. }
  23543. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23544. nodeCode.code = this.code;
  23545. return nodeCode.code;
  23546. }
  23547. serialize( data ) {
  23548. super.serialize( data );
  23549. data.code = this.code;
  23550. data.language = this.language;
  23551. }
  23552. deserialize( data ) {
  23553. super.deserialize( data );
  23554. this.code = data.code;
  23555. this.language = data.language;
  23556. }
  23557. }
  23558. /**
  23559. * TSL function for creating a code node.
  23560. *
  23561. * @tsl
  23562. * @function
  23563. * @param {string} [code=''] - The native code.
  23564. * @param {Array<Node>} [includes=[]] - An array of includes.
  23565. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23566. * @returns {CodeNode}
  23567. */
  23568. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  23569. /**
  23570. * TSL function for creating a JS code node.
  23571. *
  23572. * @tsl
  23573. * @function
  23574. * @param {string} src - The native code.
  23575. * @param {Array<Node>} includes - An array of includes.
  23576. * @returns {CodeNode}
  23577. */
  23578. const js = ( src, includes ) => code( src, includes, 'js' );
  23579. /**
  23580. * TSL function for creating a WGSL code node.
  23581. *
  23582. * @tsl
  23583. * @function
  23584. * @param {string} src - The native code.
  23585. * @param {Array<Node>} includes - An array of includes.
  23586. * @returns {CodeNode}
  23587. */
  23588. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23589. /**
  23590. * TSL function for creating a GLSL code node.
  23591. *
  23592. * @tsl
  23593. * @function
  23594. * @param {string} src - The native code.
  23595. * @param {Array<Node>} includes - An array of includes.
  23596. * @returns {CodeNode}
  23597. */
  23598. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23599. /**
  23600. * This class represents a native shader function. It can be used to implement
  23601. * certain aspects of a node material with native shader code. There are two predefined
  23602. * TSL functions for easier usage.
  23603. *
  23604. * - `wgslFn`: Creates a WGSL function node.
  23605. * - `glslFn`: Creates a GLSL function node.
  23606. *
  23607. * A basic example with one include looks like so:
  23608. *
  23609. * ```js
  23610. * const desaturateWGSLFn = wgslFn( `
  23611. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  23612. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  23613. * return vec3<f32>( dot( lum, color ) );
  23614. * }`
  23615. *);
  23616. * const someWGSLFn = wgslFn( `
  23617. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  23618. * return desaturate( color );
  23619. * }
  23620. * `, [ desaturateWGSLFn ] );
  23621. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  23622. *```
  23623. * @augments CodeNode
  23624. */
  23625. class FunctionNode extends CodeNode {
  23626. static get type() {
  23627. return 'FunctionNode';
  23628. }
  23629. /**
  23630. * Constructs a new function node.
  23631. *
  23632. * @param {string} [code=''] - The native code.
  23633. * @param {Array<Node>} [includes=[]] - An array of includes.
  23634. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23635. */
  23636. constructor( code = '', includes = [], language = '' ) {
  23637. super( code, includes, language );
  23638. }
  23639. getNodeType( builder ) {
  23640. return this.getNodeFunction( builder ).type;
  23641. }
  23642. /**
  23643. * Returns the inputs of this function node.
  23644. *
  23645. * @param {NodeBuilder} builder - The current node builder.
  23646. * @return {Array<NodeFunctionInput>} The inputs.
  23647. */
  23648. getInputs( builder ) {
  23649. return this.getNodeFunction( builder ).inputs;
  23650. }
  23651. /**
  23652. * Returns the node function for this function node.
  23653. *
  23654. * @param {NodeBuilder} builder - The current node builder.
  23655. * @return {NodeFunction} The node function.
  23656. */
  23657. getNodeFunction( builder ) {
  23658. const nodeData = builder.getDataFromNode( this );
  23659. let nodeFunction = nodeData.nodeFunction;
  23660. if ( nodeFunction === undefined ) {
  23661. nodeFunction = builder.parser.parseFunction( this.code );
  23662. nodeData.nodeFunction = nodeFunction;
  23663. }
  23664. return nodeFunction;
  23665. }
  23666. generate( builder, output ) {
  23667. super.generate( builder );
  23668. const nodeFunction = this.getNodeFunction( builder );
  23669. const name = nodeFunction.name;
  23670. const type = nodeFunction.type;
  23671. const nodeCode = builder.getCodeFromNode( this, type );
  23672. if ( name !== '' ) {
  23673. // use a custom property name
  23674. nodeCode.name = name;
  23675. }
  23676. const propertyName = builder.getPropertyName( nodeCode );
  23677. const code = this.getNodeFunction( builder ).getCode( propertyName );
  23678. nodeCode.code = code + '\n';
  23679. if ( output === 'property' ) {
  23680. return propertyName;
  23681. } else {
  23682. return builder.format( `${ propertyName }()`, type, output );
  23683. }
  23684. }
  23685. }
  23686. const nativeFn = ( code, includes = [], language = '' ) => {
  23687. for ( let i = 0; i < includes.length; i ++ ) {
  23688. const include = includes[ i ];
  23689. // TSL Function: glslFn, wgslFn
  23690. if ( typeof include === 'function' ) {
  23691. includes[ i ] = include.functionNode;
  23692. }
  23693. }
  23694. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23695. const fn = ( ...params ) => functionNode.call( ...params );
  23696. fn.functionNode = functionNode;
  23697. return fn;
  23698. };
  23699. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23700. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23701. /**
  23702. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23703. *
  23704. * @augments Node
  23705. */
  23706. class ScriptableValueNode extends Node {
  23707. static get type() {
  23708. return 'ScriptableValueNode';
  23709. }
  23710. /**
  23711. * Constructs a new scriptable node.
  23712. *
  23713. * @param {any} [value=null] - The value.
  23714. */
  23715. constructor( value = null ) {
  23716. super();
  23717. /**
  23718. * A reference to the value.
  23719. *
  23720. * @private
  23721. * @default null
  23722. */
  23723. this._value = value;
  23724. /**
  23725. * Depending on the type of `_value`, this property might cache parsed data.
  23726. *
  23727. * @private
  23728. * @default null
  23729. */
  23730. this._cache = null;
  23731. /**
  23732. * If this node represents an input, this property represents the input type.
  23733. *
  23734. * @type {?string}
  23735. * @default null
  23736. */
  23737. this.inputType = null;
  23738. /**
  23739. * If this node represents an output, this property represents the output type.
  23740. *
  23741. * @type {?string}
  23742. * @default null
  23743. */
  23744. this.outputType = null;
  23745. /**
  23746. * An event dispatcher for managing events.
  23747. *
  23748. * @type {EventDispatcher}
  23749. */
  23750. this.events = new EventDispatcher();
  23751. /**
  23752. * This flag can be used for type testing.
  23753. *
  23754. * @type {boolean}
  23755. * @readonly
  23756. * @default true
  23757. */
  23758. this.isScriptableValueNode = true;
  23759. }
  23760. /**
  23761. * Whether this node represents an output or not.
  23762. *
  23763. * @type {boolean}
  23764. * @readonly
  23765. * @default true
  23766. */
  23767. get isScriptableOutputNode() {
  23768. return this.outputType !== null;
  23769. }
  23770. set value( val ) {
  23771. if ( this._value === val ) return;
  23772. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23773. URL.revokeObjectURL( this._cache );
  23774. this._cache = null;
  23775. }
  23776. this._value = val;
  23777. this.events.dispatchEvent( { type: 'change' } );
  23778. this.refresh();
  23779. }
  23780. /**
  23781. * The node's value.
  23782. *
  23783. * @type {any}
  23784. */
  23785. get value() {
  23786. return this._value;
  23787. }
  23788. /**
  23789. * Dispatches the `refresh` event.
  23790. */
  23791. refresh() {
  23792. this.events.dispatchEvent( { type: 'refresh' } );
  23793. }
  23794. /**
  23795. * The `value` property usually represents a node or even binary data in form of array buffers.
  23796. * In this case, this method tries to return the actual value behind the complex type.
  23797. *
  23798. * @return {any} The value.
  23799. */
  23800. getValue() {
  23801. const value = this.value;
  23802. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23803. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23804. } else if ( value && value.value !== null && value.value !== undefined && (
  23805. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23806. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23807. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23808. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23809. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23810. ( this.inputType === 'Color' && value.value.isColor ) ||
  23811. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23812. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23813. ) ) {
  23814. return value.value;
  23815. }
  23816. return this._cache || value;
  23817. }
  23818. /**
  23819. * Overwritten since the node type is inferred from the value.
  23820. *
  23821. * @param {NodeBuilder} builder - The current node builder.
  23822. * @return {string} The node type.
  23823. */
  23824. getNodeType( builder ) {
  23825. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23826. }
  23827. setup() {
  23828. return this.value && this.value.isNode ? this.value : float();
  23829. }
  23830. serialize( data ) {
  23831. super.serialize( data );
  23832. if ( this.value !== null ) {
  23833. if ( this.inputType === 'ArrayBuffer' ) {
  23834. data.value = arrayBufferToBase64( this.value );
  23835. } else {
  23836. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23837. }
  23838. } else {
  23839. data.value = null;
  23840. }
  23841. data.inputType = this.inputType;
  23842. data.outputType = this.outputType;
  23843. }
  23844. deserialize( data ) {
  23845. super.deserialize( data );
  23846. let value = null;
  23847. if ( data.value !== null ) {
  23848. if ( data.inputType === 'ArrayBuffer' ) {
  23849. value = base64ToArrayBuffer( data.value );
  23850. } else if ( data.inputType === 'Texture' ) {
  23851. value = data.meta.textures[ data.value ];
  23852. } else {
  23853. value = data.meta.nodes[ data.value ] || null;
  23854. }
  23855. }
  23856. this.value = value;
  23857. this.inputType = data.inputType;
  23858. this.outputType = data.outputType;
  23859. }
  23860. }
  23861. /**
  23862. * TSL function for creating a scriptable value node.
  23863. *
  23864. * @tsl
  23865. * @function
  23866. * @param {any} [value=null] - The value.
  23867. * @returns {ScriptableValueNode}
  23868. */
  23869. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23870. /**
  23871. * A Map-like data structure for managing resources of scriptable nodes.
  23872. *
  23873. * @augments Map
  23874. */
  23875. class Resources extends Map {
  23876. get( key, callback = null, ...params ) {
  23877. if ( this.has( key ) ) return super.get( key );
  23878. if ( callback !== null ) {
  23879. const value = callback( ...params );
  23880. this.set( key, value );
  23881. return value;
  23882. }
  23883. }
  23884. }
  23885. class Parameters {
  23886. constructor( scriptableNode ) {
  23887. this.scriptableNode = scriptableNode;
  23888. }
  23889. get parameters() {
  23890. return this.scriptableNode.parameters;
  23891. }
  23892. get layout() {
  23893. return this.scriptableNode.getLayout();
  23894. }
  23895. getInputLayout( id ) {
  23896. return this.scriptableNode.getInputLayout( id );
  23897. }
  23898. get( name ) {
  23899. const param = this.parameters[ name ];
  23900. const value = param ? param.getValue() : null;
  23901. return value;
  23902. }
  23903. }
  23904. /**
  23905. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23906. *
  23907. * @type {Resources}
  23908. */
  23909. const ScriptableNodeResources = new Resources();
  23910. /**
  23911. * This type of node allows to implement nodes with custom scripts. The script
  23912. * section is represented as an instance of `CodeNode` written with JavaScript.
  23913. * The script itself must adhere to a specific structure.
  23914. *
  23915. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23916. * - layout: The layout object defines the script's interface (inputs and outputs).
  23917. *
  23918. * ```js
  23919. * ScriptableNodeResources.set( 'TSL', TSL );
  23920. *
  23921. * const scriptableNode = scriptable( js( `
  23922. * layout = {
  23923. * outputType: 'node',
  23924. * elements: [
  23925. * { name: 'source', inputType: 'node' },
  23926. * ]
  23927. * };
  23928. *
  23929. * const { mul, oscSine } = TSL;
  23930. *
  23931. * function main() {
  23932. * const source = parameters.get( 'source' ) || float();
  23933. * return mul( source, oscSine() ) );
  23934. * }
  23935. *
  23936. * ` ) );
  23937. *
  23938. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23939. *
  23940. * const material = new THREE.MeshBasicNodeMaterial();
  23941. * material.colorNode = scriptableNode;
  23942. * ```
  23943. *
  23944. * @augments Node
  23945. */
  23946. class ScriptableNode extends Node {
  23947. static get type() {
  23948. return 'ScriptableNode';
  23949. }
  23950. /**
  23951. * Constructs a new scriptable node.
  23952. *
  23953. * @param {?CodeNode} [codeNode=null] - The code node.
  23954. * @param {Object} [parameters={}] - The parameters definition.
  23955. */
  23956. constructor( codeNode = null, parameters = {} ) {
  23957. super();
  23958. /**
  23959. * The code node.
  23960. *
  23961. * @type {?CodeNode}
  23962. * @default null
  23963. */
  23964. this.codeNode = codeNode;
  23965. /**
  23966. * The parameters definition.
  23967. *
  23968. * @type {Object}
  23969. * @default {}
  23970. */
  23971. this.parameters = parameters;
  23972. this._local = new Resources();
  23973. this._output = scriptableValue();
  23974. this._outputs = {};
  23975. this._source = this.source;
  23976. this._method = null;
  23977. this._object = null;
  23978. this._value = null;
  23979. this._needsOutputUpdate = true;
  23980. this.onRefresh = this.onRefresh.bind( this );
  23981. /**
  23982. * This flag can be used for type testing.
  23983. *
  23984. * @type {boolean}
  23985. * @readonly
  23986. * @default true
  23987. */
  23988. this.isScriptableNode = true;
  23989. }
  23990. /**
  23991. * The source code of the scriptable node.
  23992. *
  23993. * @type {string}
  23994. */
  23995. get source() {
  23996. return this.codeNode ? this.codeNode.code : '';
  23997. }
  23998. /**
  23999. * Sets the reference of a local script variable.
  24000. *
  24001. * @param {string} name - The variable name.
  24002. * @param {Object} value - The reference to set.
  24003. * @return {Resources} The resource map
  24004. */
  24005. setLocal( name, value ) {
  24006. return this._local.set( name, value );
  24007. }
  24008. /**
  24009. * Gets the value of a local script variable.
  24010. *
  24011. * @param {string} name - The variable name.
  24012. * @return {Object} The value.
  24013. */
  24014. getLocal( name ) {
  24015. return this._local.get( name );
  24016. }
  24017. /**
  24018. * Event listener for the `refresh` event.
  24019. */
  24020. onRefresh() {
  24021. this._refresh();
  24022. }
  24023. /**
  24024. * Returns an input from the layout with the given id/name.
  24025. *
  24026. * @param {string} id - The id/name of the input.
  24027. * @return {Object} The element entry.
  24028. */
  24029. getInputLayout( id ) {
  24030. for ( const element of this.getLayout() ) {
  24031. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  24032. return element;
  24033. }
  24034. }
  24035. }
  24036. /**
  24037. * Returns an output from the layout with the given id/name.
  24038. *
  24039. * @param {string} id - The id/name of the output.
  24040. * @return {Object} The element entry.
  24041. */
  24042. getOutputLayout( id ) {
  24043. for ( const element of this.getLayout() ) {
  24044. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  24045. return element;
  24046. }
  24047. }
  24048. }
  24049. /**
  24050. * Defines a script output for the given name and value.
  24051. *
  24052. * @param {string} name - The name of the output.
  24053. * @param {Node} value - The node value.
  24054. * @return {ScriptableNode} A reference to this node.
  24055. */
  24056. setOutput( name, value ) {
  24057. const outputs = this._outputs;
  24058. if ( outputs[ name ] === undefined ) {
  24059. outputs[ name ] = scriptableValue( value );
  24060. } else {
  24061. outputs[ name ].value = value;
  24062. }
  24063. return this;
  24064. }
  24065. /**
  24066. * Returns a script output for the given name.
  24067. *
  24068. * @param {string} name - The name of the output.
  24069. * @return {ScriptableValueNode} The node value.
  24070. */
  24071. getOutput( name ) {
  24072. return this._outputs[ name ];
  24073. }
  24074. /**
  24075. * Returns a parameter for the given name
  24076. *
  24077. * @param {string} name - The name of the parameter.
  24078. * @return {ScriptableValueNode} The node value.
  24079. */
  24080. getParameter( name ) {
  24081. return this.parameters[ name ];
  24082. }
  24083. /**
  24084. * Sets a value for the given parameter name.
  24085. *
  24086. * @param {string} name - The parameter name.
  24087. * @param {any} value - The parameter value.
  24088. * @return {ScriptableNode} A reference to this node.
  24089. */
  24090. setParameter( name, value ) {
  24091. const parameters = this.parameters;
  24092. if ( value && value.isScriptableNode ) {
  24093. this.deleteParameter( name );
  24094. parameters[ name ] = value;
  24095. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  24096. } else if ( value && value.isScriptableValueNode ) {
  24097. this.deleteParameter( name );
  24098. parameters[ name ] = value;
  24099. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24100. } else if ( parameters[ name ] === undefined ) {
  24101. parameters[ name ] = scriptableValue( value );
  24102. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24103. } else {
  24104. parameters[ name ].value = value;
  24105. }
  24106. return this;
  24107. }
  24108. /**
  24109. * Returns the value of this node which is the value of
  24110. * the default output.
  24111. *
  24112. * @return {Node} The value.
  24113. */
  24114. getValue() {
  24115. return this.getDefaultOutput().getValue();
  24116. }
  24117. /**
  24118. * Deletes a parameter from the script.
  24119. *
  24120. * @param {string} name - The parameter to remove.
  24121. * @return {ScriptableNode} A reference to this node.
  24122. */
  24123. deleteParameter( name ) {
  24124. let valueNode = this.parameters[ name ];
  24125. if ( valueNode ) {
  24126. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24127. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  24128. }
  24129. return this;
  24130. }
  24131. /**
  24132. * Deletes all parameters from the script.
  24133. *
  24134. * @return {ScriptableNode} A reference to this node.
  24135. */
  24136. clearParameters() {
  24137. for ( const name of Object.keys( this.parameters ) ) {
  24138. this.deleteParameter( name );
  24139. }
  24140. this.needsUpdate = true;
  24141. return this;
  24142. }
  24143. /**
  24144. * Calls a function from the script.
  24145. *
  24146. * @param {string} name - The function name.
  24147. * @param {...any} params - A list of parameters.
  24148. * @return {any} The result of the function call.
  24149. */
  24150. call( name, ...params ) {
  24151. const object = this.getObject();
  24152. const method = object[ name ];
  24153. if ( typeof method === 'function' ) {
  24154. return method( ...params );
  24155. }
  24156. }
  24157. /**
  24158. * Asynchronously calls a function from the script.
  24159. *
  24160. * @param {string} name - The function name.
  24161. * @param {...any} params - A list of parameters.
  24162. * @return {Promise<any>} The result of the function call.
  24163. */
  24164. async callAsync( name, ...params ) {
  24165. const object = this.getObject();
  24166. const method = object[ name ];
  24167. if ( typeof method === 'function' ) {
  24168. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  24169. }
  24170. }
  24171. /**
  24172. * Overwritten since the node types is inferred from the script's output.
  24173. *
  24174. * @param {NodeBuilder} builder - The current node builder
  24175. * @return {string} The node type.
  24176. */
  24177. getNodeType( builder ) {
  24178. return this.getDefaultOutputNode().getNodeType( builder );
  24179. }
  24180. /**
  24181. * Refreshes the script node.
  24182. *
  24183. * @param {?string} [output=null] - An optional output.
  24184. */
  24185. refresh( output = null ) {
  24186. if ( output !== null ) {
  24187. this.getOutput( output ).refresh();
  24188. } else {
  24189. this._refresh();
  24190. }
  24191. }
  24192. /**
  24193. * Returns an object representation of the script.
  24194. *
  24195. * @return {Object} The result object.
  24196. */
  24197. getObject() {
  24198. if ( this.needsUpdate ) this.dispose();
  24199. if ( this._object !== null ) return this._object;
  24200. //
  24201. const refresh = () => this.refresh();
  24202. const setOutput = ( id, value ) => this.setOutput( id, value );
  24203. const parameters = new Parameters( this );
  24204. const THREE = ScriptableNodeResources.get( 'THREE' );
  24205. const TSL = ScriptableNodeResources.get( 'TSL' );
  24206. const method = this.getMethod();
  24207. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  24208. this._object = method( ...params );
  24209. const layout = this._object.layout;
  24210. if ( layout ) {
  24211. if ( layout.cache === false ) {
  24212. this._local.clear();
  24213. }
  24214. // default output
  24215. this._output.outputType = layout.outputType || null;
  24216. if ( Array.isArray( layout.elements ) ) {
  24217. for ( const element of layout.elements ) {
  24218. const id = element.id || element.name;
  24219. if ( element.inputType ) {
  24220. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  24221. this.getParameter( id ).inputType = element.inputType;
  24222. }
  24223. if ( element.outputType ) {
  24224. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  24225. this.getOutput( id ).outputType = element.outputType;
  24226. }
  24227. }
  24228. }
  24229. }
  24230. return this._object;
  24231. }
  24232. deserialize( data ) {
  24233. super.deserialize( data );
  24234. for ( const name in this.parameters ) {
  24235. let valueNode = this.parameters[ name ];
  24236. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24237. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  24238. }
  24239. }
  24240. /**
  24241. * Returns the layout of the script.
  24242. *
  24243. * @return {Object} The script's layout.
  24244. */
  24245. getLayout() {
  24246. return this.getObject().layout;
  24247. }
  24248. /**
  24249. * Returns default node output of the script.
  24250. *
  24251. * @return {Node} The default node output.
  24252. */
  24253. getDefaultOutputNode() {
  24254. const output = this.getDefaultOutput().value;
  24255. if ( output && output.isNode ) {
  24256. return output;
  24257. }
  24258. return float();
  24259. }
  24260. /**
  24261. * Returns default output of the script.
  24262. *
  24263. * @return {ScriptableValueNode} The default output.
  24264. */
  24265. getDefaultOutput() {
  24266. return this._exec()._output;
  24267. }
  24268. /**
  24269. * Returns a function created from the node's script.
  24270. *
  24271. * @return {Function} The function representing the node's code.
  24272. */
  24273. getMethod() {
  24274. if ( this.needsUpdate ) this.dispose();
  24275. if ( this._method !== null ) return this._method;
  24276. //
  24277. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  24278. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  24279. const properties = interfaceProps.join( ', ' );
  24280. const declarations = 'var ' + properties + '; var output = {};\n';
  24281. const returns = '\nreturn { ...output, ' + properties + ' };';
  24282. const code = declarations + this.codeNode.code + returns;
  24283. //
  24284. this._method = new Function( ...parametersProps, code );
  24285. return this._method;
  24286. }
  24287. /**
  24288. * Frees all internal resources.
  24289. */
  24290. dispose() {
  24291. if ( this._method === null ) return;
  24292. if ( this._object && typeof this._object.dispose === 'function' ) {
  24293. this._object.dispose();
  24294. }
  24295. this._method = null;
  24296. this._object = null;
  24297. this._source = null;
  24298. this._value = null;
  24299. this._needsOutputUpdate = true;
  24300. this._output.value = null;
  24301. this._outputs = {};
  24302. }
  24303. setup() {
  24304. return this.getDefaultOutputNode();
  24305. }
  24306. getCacheKey( force ) {
  24307. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  24308. for ( const param in this.parameters ) {
  24309. values.push( this.parameters[ param ].getCacheKey( force ) );
  24310. }
  24311. return hashArray( values );
  24312. }
  24313. set needsUpdate( value ) {
  24314. if ( value === true ) this.dispose();
  24315. }
  24316. get needsUpdate() {
  24317. return this.source !== this._source;
  24318. }
  24319. /**
  24320. * Executes the `main` function of the script.
  24321. *
  24322. * @private
  24323. * @return {ScriptableNode} A reference to this node.
  24324. */
  24325. _exec() {
  24326. if ( this.codeNode === null ) return this;
  24327. if ( this._needsOutputUpdate === true ) {
  24328. this._value = this.call( 'main' );
  24329. this._needsOutputUpdate = false;
  24330. }
  24331. this._output.value = this._value;
  24332. return this;
  24333. }
  24334. /**
  24335. * Executes the refresh.
  24336. *
  24337. * @private
  24338. */
  24339. _refresh() {
  24340. this.needsUpdate = true;
  24341. this._exec();
  24342. this._output.refresh();
  24343. }
  24344. }
  24345. /**
  24346. * TSL function for creating a scriptable node.
  24347. *
  24348. * @tsl
  24349. * @function
  24350. * @param {?CodeNode} [codeNode=null] - The code node.
  24351. * @param {Object} [parameters={}] - The parameters definition.
  24352. * @returns {ScriptableNode}
  24353. */
  24354. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  24355. /**
  24356. * Returns a node that represents the `z` coordinate in view space
  24357. * for the current fragment. It's a different representation of the
  24358. * default depth value.
  24359. *
  24360. * This value can be part of a computation that defines how the fog
  24361. * density increases when moving away from the camera.
  24362. *
  24363. * @param {NodeBuilder} builder - The current node builder.
  24364. * @return {Node} The viewZ node.
  24365. */
  24366. function getViewZNode( builder ) {
  24367. let viewZ;
  24368. const getViewZ = builder.context.getViewZ;
  24369. if ( getViewZ !== undefined ) {
  24370. viewZ = getViewZ( this );
  24371. }
  24372. return ( viewZ || positionView.z ).negate();
  24373. }
  24374. /**
  24375. * Constructs a new range factor node.
  24376. *
  24377. * @tsl
  24378. * @function
  24379. * @param {Node} near - Defines the near value.
  24380. * @param {Node} far - Defines the far value.
  24381. */
  24382. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  24383. const viewZ = getViewZNode( builder );
  24384. return smoothstep( near, far, viewZ );
  24385. } );
  24386. /**
  24387. * Represents an exponential squared fog. This type of fog gives
  24388. * a clear view near the camera and a faster than exponentially
  24389. * densening fog farther from the camera.
  24390. *
  24391. * @tsl
  24392. * @function
  24393. * @param {Node} density - Defines the fog density.
  24394. */
  24395. const densityFogFactor = Fn( ( [ density ], builder ) => {
  24396. const viewZ = getViewZNode( builder );
  24397. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  24398. } );
  24399. /**
  24400. * This class can be used to configure a fog for the scene.
  24401. * Nodes of this type are assigned to `Scene.fogNode`.
  24402. *
  24403. * @tsl
  24404. * @function
  24405. * @param {Node} color - Defines the color of the fog.
  24406. * @param {Node} factor - Defines how the fog is factored in the scene.
  24407. */
  24408. const fog = Fn( ( [ color, factor ] ) => {
  24409. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  24410. } );
  24411. // Deprecated
  24412. /**
  24413. * @tsl
  24414. * @function
  24415. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  24416. *
  24417. * @param {Node} color
  24418. * @param {Node} near
  24419. * @param {Node} far
  24420. * @returns {Function}
  24421. */
  24422. function rangeFog( color, near, far ) { // @deprecated, r171
  24423. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  24424. return fog( color, rangeFogFactor( near, far ) );
  24425. }
  24426. /**
  24427. * @tsl
  24428. * @function
  24429. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  24430. *
  24431. * @param {Node} color
  24432. * @param {Node} density
  24433. * @returns {Function}
  24434. */
  24435. function densityFog( color, density ) { // @deprecated, r171
  24436. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  24437. return fog( color, densityFogFactor( density ) );
  24438. }
  24439. let min = null;
  24440. let max = null;
  24441. /**
  24442. * `RangeNode` generates random instanced attribute data in a defined range.
  24443. * An exemplary use case for this utility node is to generate random per-instance
  24444. * colors:
  24445. * ```js
  24446. * const material = new MeshBasicNodeMaterial();
  24447. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  24448. * const mesh = new InstancedMesh( geometry, material, count );
  24449. * ```
  24450. * @augments Node
  24451. */
  24452. class RangeNode extends Node {
  24453. static get type() {
  24454. return 'RangeNode';
  24455. }
  24456. /**
  24457. * Constructs a new range node.
  24458. *
  24459. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24460. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24461. */
  24462. constructor( minNode = float(), maxNode = float() ) {
  24463. super();
  24464. /**
  24465. * A node defining the lower bound of the range.
  24466. *
  24467. * @type {Node<any>}
  24468. * @default float()
  24469. */
  24470. this.minNode = minNode;
  24471. /**
  24472. * A node defining the upper bound of the range.
  24473. *
  24474. * @type {Node<any>}
  24475. * @default float()
  24476. */
  24477. this.maxNode = maxNode;
  24478. }
  24479. /**
  24480. * Returns the vector length which is computed based on the range definition.
  24481. *
  24482. * @param {NodeBuilder} builder - The current node builder.
  24483. * @return {number} The vector length.
  24484. */
  24485. getVectorLength( builder ) {
  24486. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  24487. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  24488. return minLength > maxLength ? minLength : maxLength;
  24489. }
  24490. /**
  24491. * This method is overwritten since the node type is inferred from range definition.
  24492. *
  24493. * @param {NodeBuilder} builder - The current node builder.
  24494. * @return {string} The node type.
  24495. */
  24496. getNodeType( builder ) {
  24497. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  24498. }
  24499. setup( builder ) {
  24500. const object = builder.object;
  24501. let output = null;
  24502. if ( object.count > 1 ) {
  24503. const minValue = this.minNode.value;
  24504. const maxValue = this.maxNode.value;
  24505. const minLength = builder.getTypeLength( getValueType( minValue ) );
  24506. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  24507. min = min || new Vector4();
  24508. max = max || new Vector4();
  24509. min.setScalar( 0 );
  24510. max.setScalar( 0 );
  24511. if ( minLength === 1 ) min.setScalar( minValue );
  24512. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  24513. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  24514. if ( maxLength === 1 ) max.setScalar( maxValue );
  24515. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  24516. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  24517. const stride = 4;
  24518. const length = stride * object.count;
  24519. const array = new Float32Array( length );
  24520. for ( let i = 0; i < length; i ++ ) {
  24521. const index = i % stride;
  24522. const minElementValue = min.getComponent( index );
  24523. const maxElementValue = max.getComponent( index );
  24524. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  24525. }
  24526. const nodeType = this.getNodeType( builder );
  24527. if ( object.count <= 4096 ) {
  24528. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  24529. } else {
  24530. // TODO: Improve anonymous buffer attribute creation removing this part
  24531. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  24532. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  24533. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  24534. }
  24535. } else {
  24536. output = float( 0 );
  24537. }
  24538. return output;
  24539. }
  24540. }
  24541. /**
  24542. * TSL function for creating a range node.
  24543. *
  24544. * @tsl
  24545. * @function
  24546. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24547. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24548. * @returns {RangeNode}
  24549. */
  24550. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  24551. /**
  24552. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  24553. * about the currently running dispatch and/or the device it is running on.
  24554. *
  24555. * This node can only be used with a WebGPU backend.
  24556. *
  24557. * @augments Node
  24558. */
  24559. class ComputeBuiltinNode extends Node {
  24560. static get type() {
  24561. return 'ComputeBuiltinNode';
  24562. }
  24563. /**
  24564. * Constructs a new compute builtin node.
  24565. *
  24566. * @param {string} builtinName - The built-in name.
  24567. * @param {string} nodeType - The node type.
  24568. */
  24569. constructor( builtinName, nodeType ) {
  24570. super( nodeType );
  24571. /**
  24572. * The built-in name.
  24573. *
  24574. * @private
  24575. * @type {string}
  24576. */
  24577. this._builtinName = builtinName;
  24578. }
  24579. /**
  24580. * This method is overwritten since hash is derived from the built-in name.
  24581. *
  24582. * @param {NodeBuilder} builder - The current node builder.
  24583. * @return {string} The hash.
  24584. */
  24585. getHash( builder ) {
  24586. return this.getBuiltinName( builder );
  24587. }
  24588. /**
  24589. * This method is overwritten since the node type is simply derived from `nodeType`..
  24590. *
  24591. * @param {NodeBuilder} builder - The current node builder.
  24592. * @return {string} The node type.
  24593. */
  24594. getNodeType( /*builder*/ ) {
  24595. return this.nodeType;
  24596. }
  24597. /**
  24598. * Sets the builtin name.
  24599. *
  24600. * @param {string} builtinName - The built-in name.
  24601. * @return {ComputeBuiltinNode} A reference to this node.
  24602. */
  24603. setBuiltinName( builtinName ) {
  24604. this._builtinName = builtinName;
  24605. return this;
  24606. }
  24607. /**
  24608. * Returns the builtin name.
  24609. *
  24610. * @param {NodeBuilder} builder - The current node builder.
  24611. * @return {string} The builtin name.
  24612. */
  24613. getBuiltinName( /*builder*/ ) {
  24614. return this._builtinName;
  24615. }
  24616. /**
  24617. * Whether the current node builder has the builtin or not.
  24618. *
  24619. * @param {NodeBuilder} builder - The current node builder.
  24620. */
  24621. hasBuiltin( builder ) {
  24622. builder.hasBuiltin( this._builtinName );
  24623. }
  24624. generate( builder, output ) {
  24625. const builtinName = this.getBuiltinName( builder );
  24626. const nodeType = this.getNodeType( builder );
  24627. if ( builder.shaderStage === 'compute' ) {
  24628. return builder.format( builtinName, nodeType, output );
  24629. } else {
  24630. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  24631. return builder.generateConst( nodeType );
  24632. }
  24633. }
  24634. serialize( data ) {
  24635. super.serialize( data );
  24636. data.global = this.global;
  24637. data._builtinName = this._builtinName;
  24638. }
  24639. deserialize( data ) {
  24640. super.deserialize( data );
  24641. this.global = data.global;
  24642. this._builtinName = data._builtinName;
  24643. }
  24644. }
  24645. /**
  24646. * TSL function for creating a compute builtin node.
  24647. *
  24648. * @tsl
  24649. * @function
  24650. * @param {string} name - The built-in name.
  24651. * @param {string} nodeType - The node type.
  24652. * @returns {ComputeBuiltinNode}
  24653. */
  24654. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  24655. /**
  24656. * Represents the number of workgroups dispatched by the compute shader.
  24657. * ```js
  24658. * // Run 512 invocations/threads with a workgroup size of 128.
  24659. * const computeFn = Fn(() => {
  24660. *
  24661. * // numWorkgroups.x = 4
  24662. * storageBuffer.element(0).assign(numWorkgroups.x)
  24663. *
  24664. * })().compute(512, [128]);
  24665. *
  24666. * // Run 512 invocations/threads with the default workgroup size of 64.
  24667. * const computeFn = Fn(() => {
  24668. *
  24669. * // numWorkgroups.x = 8
  24670. * storageBuffer.element(0).assign(numWorkgroups.x)
  24671. *
  24672. * })().compute(512);
  24673. * ```
  24674. *
  24675. * @tsl
  24676. * @type {ComputeBuiltinNode<uvec3>}
  24677. */
  24678. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  24679. /**
  24680. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  24681. * ```js
  24682. * // Execute 12 compute threads with a workgroup size of 3.
  24683. * const computeFn = Fn( () => {
  24684. *
  24685. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24686. *
  24687. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24688. *
  24689. * } ).Else( () => {
  24690. *
  24691. * storageBuffer.element( instanceIndex ).assign( 0 );
  24692. *
  24693. * } );
  24694. *
  24695. * } )().compute( 12, [ 3 ] );
  24696. *
  24697. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24698. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24699. * ```
  24700. *
  24701. * @tsl
  24702. * @type {ComputeBuiltinNode<uvec3>}
  24703. */
  24704. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24705. /**
  24706. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  24707. *
  24708. * @tsl
  24709. * @type {ComputeBuiltinNode<uvec3>}
  24710. */
  24711. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24712. /**
  24713. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  24714. *
  24715. * @tsl
  24716. * @type {ComputeBuiltinNode<uvec3>}
  24717. */
  24718. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24719. /**
  24720. * A device dependent variable that exposes the size of the current invocation's subgroup.
  24721. *
  24722. * @tsl
  24723. * @type {ComputeBuiltinNode<uint>}
  24724. */
  24725. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24726. /**
  24727. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24728. *
  24729. * This node can only be used with a WebGPU backend.
  24730. *
  24731. * @augments Node
  24732. */
  24733. class BarrierNode extends Node {
  24734. /**
  24735. * Constructs a new barrier node.
  24736. *
  24737. * @param {string} scope - The scope defines the behavior of the node.
  24738. */
  24739. constructor( scope ) {
  24740. super();
  24741. this.scope = scope;
  24742. }
  24743. generate( builder ) {
  24744. const { scope } = this;
  24745. const { renderer } = builder;
  24746. if ( renderer.backend.isWebGLBackend === true ) {
  24747. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24748. } else {
  24749. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24750. }
  24751. }
  24752. }
  24753. /**
  24754. * TSL function for creating a barrier node.
  24755. *
  24756. * @tsl
  24757. * @function
  24758. * @param {string} scope - The scope defines the behavior of the node..
  24759. * @returns {BarrierNode}
  24760. */
  24761. const barrier = nodeProxy( BarrierNode );
  24762. /**
  24763. * TSL function for creating a workgroup barrier. All compute shader
  24764. * invocations must wait for each invocation within a workgroup to
  24765. * complete before the barrier can be surpassed.
  24766. *
  24767. * @tsl
  24768. * @function
  24769. * @returns {BarrierNode}
  24770. */
  24771. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24772. /**
  24773. * TSL function for creating a storage barrier. All invocations must
  24774. * wait for each access to variables within the 'storage' address space
  24775. * to complete before the barrier can be passed.
  24776. *
  24777. * @tsl
  24778. * @function
  24779. * @returns {BarrierNode}
  24780. */
  24781. const storageBarrier = () => barrier( 'storage' ).append();
  24782. /**
  24783. * TSL function for creating a texture barrier. All invocations must
  24784. * wait for each access to variables within the 'texture' address space
  24785. * to complete before the barrier can be passed.
  24786. *
  24787. * @tsl
  24788. * @function
  24789. * @returns {BarrierNode}
  24790. */
  24791. const textureBarrier = () => barrier( 'texture' ).append();
  24792. /**
  24793. * Represents an element of a 'workgroup' scoped buffer.
  24794. *
  24795. * @augments ArrayElementNode
  24796. */
  24797. class WorkgroupInfoElementNode extends ArrayElementNode {
  24798. /**
  24799. * Constructs a new workgroup info element node.
  24800. *
  24801. * @param {Node} workgroupInfoNode - The workgroup info node.
  24802. * @param {Node} indexNode - The index node that defines the element access.
  24803. */
  24804. constructor( workgroupInfoNode, indexNode ) {
  24805. super( workgroupInfoNode, indexNode );
  24806. /**
  24807. * This flag can be used for type testing.
  24808. *
  24809. * @type {boolean}
  24810. * @readonly
  24811. * @default true
  24812. */
  24813. this.isWorkgroupInfoElementNode = true;
  24814. }
  24815. generate( builder, output ) {
  24816. let snippet;
  24817. const isAssignContext = builder.context.assign;
  24818. snippet = super.generate( builder );
  24819. if ( isAssignContext !== true ) {
  24820. const type = this.getNodeType( builder );
  24821. snippet = builder.format( snippet, type, output );
  24822. }
  24823. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24824. return snippet;
  24825. }
  24826. }
  24827. /**
  24828. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24829. * context of a compute shader. Typically, workgroup scoped buffers are
  24830. * created to hold data that is transferred from a global storage scope into
  24831. * a local workgroup scope. For invocations within a workgroup, data
  24832. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24833. * than similar access operations on globally accessible storage buffers.
  24834. *
  24835. * This node can only be used with a WebGPU backend.
  24836. *
  24837. * @augments Node
  24838. */
  24839. class WorkgroupInfoNode extends Node {
  24840. /**
  24841. * Constructs a new buffer scoped to type scope.
  24842. *
  24843. * @param {string} scope - TODO.
  24844. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  24845. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  24846. */
  24847. constructor( scope, bufferType, bufferCount = 0 ) {
  24848. super( bufferType );
  24849. /**
  24850. * The buffer type.
  24851. *
  24852. * @type {string}
  24853. */
  24854. this.bufferType = bufferType;
  24855. /**
  24856. * The buffer count.
  24857. *
  24858. * @type {number}
  24859. * @default 0
  24860. */
  24861. this.bufferCount = bufferCount;
  24862. /**
  24863. * This flag can be used for type testing.
  24864. *
  24865. * @type {boolean}
  24866. * @readonly
  24867. * @default true
  24868. */
  24869. this.isWorkgroupInfoNode = true;
  24870. /**
  24871. * The data type of the array buffer.
  24872. *
  24873. * @type {string}
  24874. */
  24875. this.elementType = bufferType;
  24876. /**
  24877. * TODO.
  24878. *
  24879. * @type {string}
  24880. */
  24881. this.scope = scope;
  24882. }
  24883. /**
  24884. * Sets the name/label of this node.
  24885. *
  24886. * @param {string} name - The name to set.
  24887. * @return {WorkgroupInfoNode} A reference to this node.
  24888. */
  24889. label( name ) {
  24890. this.name = name;
  24891. return this;
  24892. }
  24893. /**
  24894. * Sets the scope of this node.
  24895. *
  24896. * @param {string} scope - The scope to set.
  24897. * @return {WorkgroupInfoNode} A reference to this node.
  24898. */
  24899. setScope( scope ) {
  24900. this.scope = scope;
  24901. return this;
  24902. }
  24903. /**
  24904. * The data type of the array buffer.
  24905. *
  24906. * @return {string} The element type.
  24907. */
  24908. getElementType() {
  24909. return this.elementType;
  24910. }
  24911. /**
  24912. * Overwrites the default implementation since the input type
  24913. * is inferred from the scope.
  24914. *
  24915. * @param {NodeBuilder} builder - The current node builder.
  24916. * @return {string} The input type.
  24917. */
  24918. getInputType( /*builder*/ ) {
  24919. return `${this.scope}Array`;
  24920. }
  24921. /**
  24922. * This method can be used to access elements via an index node.
  24923. *
  24924. * @param {IndexNode} indexNode - indexNode.
  24925. * @return {WorkgroupInfoElementNode} A reference to an element.
  24926. */
  24927. element( indexNode ) {
  24928. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24929. }
  24930. generate( builder ) {
  24931. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24932. }
  24933. }
  24934. /**
  24935. * TSL function for creating a workgroup info node.
  24936. * Creates a new 'workgroup' scoped array buffer.
  24937. *
  24938. * @tsl
  24939. * @function
  24940. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  24941. * @param {number} [count=0] - The number of elements in the buffer.
  24942. * @returns {WorkgroupInfoNode}
  24943. */
  24944. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24945. /**
  24946. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24947. * within a shader. In an atomic function, any modification to an atomic variable will
  24948. * occur as an indivisible step with a defined order relative to other modifications.
  24949. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24950. * atomic operations will not interfere with each other.
  24951. *
  24952. * This node can only be used with a WebGPU backend.
  24953. *
  24954. * @augments TempNode
  24955. */
  24956. class AtomicFunctionNode extends TempNode {
  24957. static get type() {
  24958. return 'AtomicFunctionNode';
  24959. }
  24960. /**
  24961. * Constructs a new atomic function node.
  24962. *
  24963. * @param {string} method - The signature of the atomic function to construct.
  24964. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24965. * @param {Node} valueNode - The value that mutates the atomic variable.
  24966. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24967. */
  24968. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24969. super( 'uint' );
  24970. /**
  24971. * The signature of the atomic function to construct.
  24972. *
  24973. * @type {string}
  24974. */
  24975. this.method = method;
  24976. /**
  24977. * An atomic variable or element of an atomic buffer.
  24978. *
  24979. * @type {Node}
  24980. */
  24981. this.pointerNode = pointerNode;
  24982. /**
  24983. * A value that modifies the atomic variable.
  24984. *
  24985. * @type {Node}
  24986. */
  24987. this.valueNode = valueNode;
  24988. /**
  24989. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24990. *
  24991. * @type {?Node}
  24992. * @default null
  24993. */
  24994. this.storeNode = storeNode;
  24995. }
  24996. /**
  24997. * Overwrites the default implementation to return the type of
  24998. * the pointer node.
  24999. *
  25000. * @param {NodeBuilder} builder - The current node builder.
  25001. * @return {string} The input type.
  25002. */
  25003. getInputType( builder ) {
  25004. return this.pointerNode.getNodeType( builder );
  25005. }
  25006. /**
  25007. * Overwritten since the node type is inferred from the input type.
  25008. *
  25009. * @param {NodeBuilder} builder - The current node builder.
  25010. * @return {string} The node type.
  25011. */
  25012. getNodeType( builder ) {
  25013. return this.getInputType( builder );
  25014. }
  25015. generate( builder ) {
  25016. const method = this.method;
  25017. const type = this.getNodeType( builder );
  25018. const inputType = this.getInputType( builder );
  25019. const a = this.pointerNode;
  25020. const b = this.valueNode;
  25021. const params = [];
  25022. params.push( `&${ a.build( builder, inputType ) }` );
  25023. if ( b !== null ) {
  25024. params.push( b.build( builder, inputType ) );
  25025. }
  25026. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  25027. if ( this.storeNode !== null ) {
  25028. const varSnippet = this.storeNode.build( builder, inputType );
  25029. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  25030. } else {
  25031. builder.addLineFlowCode( methodSnippet, this );
  25032. }
  25033. }
  25034. }
  25035. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  25036. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  25037. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  25038. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  25039. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  25040. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  25041. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  25042. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  25043. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  25044. /**
  25045. * TSL function for creating an atomic function node.
  25046. *
  25047. * @tsl
  25048. * @function
  25049. * @param {string} method - The signature of the atomic function to construct.
  25050. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25051. * @param {Node} valueNode - The value that mutates the atomic variable.
  25052. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25053. * @returns {AtomicFunctionNode}
  25054. */
  25055. const atomicNode = nodeProxy( AtomicFunctionNode );
  25056. /**
  25057. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  25058. *
  25059. * @tsl
  25060. * @function
  25061. * @param {string} method - The signature of the atomic function to construct.
  25062. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25063. * @param {Node} valueNode - The value that mutates the atomic variable.
  25064. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25065. * @returns {AtomicFunctionNode}
  25066. */
  25067. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  25068. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  25069. node.append();
  25070. return node;
  25071. };
  25072. /**
  25073. * Loads the value stored in the atomic variable.
  25074. *
  25075. * @tsl
  25076. * @function
  25077. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25078. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25079. * @returns {AtomicFunctionNode}
  25080. */
  25081. const atomicLoad = ( pointerNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null, storeNode );
  25082. /**
  25083. * Stores a value in the atomic variable.
  25084. *
  25085. * @tsl
  25086. * @function
  25087. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25088. * @param {Node} valueNode - The value that mutates the atomic variable.
  25089. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25090. * @returns {AtomicFunctionNode}
  25091. */
  25092. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  25093. /**
  25094. * Increments the value stored in the atomic variable.
  25095. *
  25096. * @tsl
  25097. * @function
  25098. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25099. * @param {Node} valueNode - The value that mutates the atomic variable.
  25100. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25101. * @returns {AtomicFunctionNode}
  25102. */
  25103. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  25104. /**
  25105. * Decrements the value stored in the atomic variable.
  25106. *
  25107. * @tsl
  25108. * @function
  25109. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25110. * @param {Node} valueNode - The value that mutates the atomic variable.
  25111. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25112. * @returns {AtomicFunctionNode}
  25113. */
  25114. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  25115. /**
  25116. * Stores in an atomic variable the maximum between its current value and a parameter.
  25117. *
  25118. * @tsl
  25119. * @function
  25120. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25121. * @param {Node} valueNode - The value that mutates the atomic variable.
  25122. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25123. * @returns {AtomicFunctionNode}
  25124. */
  25125. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  25126. /**
  25127. * Stores in an atomic variable the minimum between its current value and a parameter.
  25128. *
  25129. * @tsl
  25130. * @function
  25131. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25132. * @param {Node} valueNode - The value that mutates the atomic variable.
  25133. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25134. * @returns {AtomicFunctionNode}
  25135. */
  25136. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  25137. /**
  25138. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  25139. *
  25140. * @tsl
  25141. * @function
  25142. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25143. * @param {Node} valueNode - The value that mutates the atomic variable.
  25144. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25145. * @returns {AtomicFunctionNode}
  25146. */
  25147. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  25148. /**
  25149. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  25150. *
  25151. * @tsl
  25152. * @function
  25153. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25154. * @param {Node} valueNode - The value that mutates the atomic variable.
  25155. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25156. * @returns {AtomicFunctionNode}
  25157. */
  25158. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  25159. /**
  25160. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  25161. *
  25162. * @tsl
  25163. * @function
  25164. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25165. * @param {Node} valueNode - The value that mutates the atomic variable.
  25166. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25167. * @returns {AtomicFunctionNode}
  25168. */
  25169. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  25170. let uniformsLib;
  25171. function getLightData( light ) {
  25172. uniformsLib = uniformsLib || new WeakMap();
  25173. let uniforms = uniformsLib.get( light );
  25174. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  25175. return uniforms;
  25176. }
  25177. /**
  25178. * TSL function for getting a shadow matrix uniform node for the given light.
  25179. *
  25180. * @tsl
  25181. * @function
  25182. * @param {Light} light -The light source.
  25183. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  25184. */
  25185. function lightShadowMatrix( light ) {
  25186. const data = getLightData( light );
  25187. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25188. if ( light.castShadow !== true ) {
  25189. light.shadow.updateMatrices( light );
  25190. }
  25191. return light.shadow.matrix;
  25192. } ) );
  25193. }
  25194. /**
  25195. * TSL function for getting projected uv coordinates for the given light.
  25196. * Relevant when using maps with spot lights.
  25197. *
  25198. * @tsl
  25199. * @function
  25200. * @param {Light} light -The light source.
  25201. * @returns {Node<vec3>} The projected uvs.
  25202. */
  25203. function lightProjectionUV( light ) {
  25204. const data = getLightData( light );
  25205. if ( data.projectionUV === undefined ) {
  25206. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  25207. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  25208. }
  25209. return data.projectionUV;
  25210. }
  25211. /**
  25212. * TSL function for getting the position in world space for the given light.
  25213. *
  25214. * @tsl
  25215. * @function
  25216. * @param {Light} light -The light source.
  25217. * @returns {UniformNode<vec3>} The light's position in world space.
  25218. */
  25219. function lightPosition( light ) {
  25220. const data = getLightData( light );
  25221. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  25222. }
  25223. /**
  25224. * TSL function for getting the light target position in world space for the given light.
  25225. *
  25226. * @tsl
  25227. * @function
  25228. * @param {Light} light -The light source.
  25229. * @returns {UniformNode<vec3>} The light target position in world space.
  25230. */
  25231. function lightTargetPosition( light ) {
  25232. const data = getLightData( light );
  25233. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  25234. }
  25235. /**
  25236. * TSL function for getting the position in view space for the given light.
  25237. *
  25238. * @tsl
  25239. * @function
  25240. * @param {Light} light -The light source.
  25241. * @returns {UniformNode<vec3>} The light's position in view space.
  25242. */
  25243. function lightViewPosition( light ) {
  25244. const data = getLightData( light );
  25245. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  25246. self.value = self.value || new Vector3();
  25247. self.value.setFromMatrixPosition( light.matrixWorld );
  25248. self.value.applyMatrix4( camera.matrixWorldInverse );
  25249. } ) );
  25250. }
  25251. /**
  25252. * TSL function for getting the light target direction for the given light.
  25253. *
  25254. * @tsl
  25255. * @function
  25256. * @param {Light} light -The light source.
  25257. * @returns {Node<vec3>} The light's target direction.
  25258. */
  25259. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  25260. const sortLights = ( lights ) => {
  25261. return lights.sort( ( a, b ) => a.id - b.id );
  25262. };
  25263. const getLightNodeById = ( id, lightNodes ) => {
  25264. for ( const lightNode of lightNodes ) {
  25265. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  25266. return lightNode;
  25267. }
  25268. }
  25269. return null;
  25270. };
  25271. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  25272. /**
  25273. * This node represents the scene's lighting and manages the lighting model's life cycle
  25274. * for the current build 3D object. It is responsible for computing the total outgoing
  25275. * light in a given lighting context.
  25276. *
  25277. * @augments Node
  25278. */
  25279. class LightsNode extends Node {
  25280. static get type() {
  25281. return 'LightsNode';
  25282. }
  25283. /**
  25284. * Constructs a new lights node.
  25285. */
  25286. constructor() {
  25287. super( 'vec3' );
  25288. /**
  25289. * A node representing the total diffuse light.
  25290. *
  25291. * @type {Node<vec3>}
  25292. */
  25293. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  25294. /**
  25295. * A node representing the total specular light.
  25296. *
  25297. * @type {Node<vec3>}
  25298. */
  25299. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  25300. /**
  25301. * A node representing the outgoing light.
  25302. *
  25303. * @type {Node<vec3>}
  25304. */
  25305. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  25306. /**
  25307. * An array representing the lights in the scene.
  25308. *
  25309. * @private
  25310. * @type {Array<Light>}
  25311. */
  25312. this._lights = [];
  25313. /**
  25314. * For each light in the scene, this node will create a
  25315. * corresponding light node.
  25316. *
  25317. * @private
  25318. * @type {?Array<LightingNode>}
  25319. * @default null
  25320. */
  25321. this._lightNodes = null;
  25322. /**
  25323. * A hash for identifying the current light nodes setup.
  25324. *
  25325. * @private
  25326. * @type {?string}
  25327. * @default null
  25328. */
  25329. this._lightNodesHash = null;
  25330. /**
  25331. * `LightsNode` sets this property to `true` by default.
  25332. *
  25333. * @type {boolean}
  25334. * @default true
  25335. */
  25336. this.global = true;
  25337. }
  25338. /**
  25339. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25340. * light IDs into the cache key.
  25341. *
  25342. * @return {number} The custom cache key.
  25343. */
  25344. customCacheKey() {
  25345. const lightIDs = [];
  25346. const lights = this._lights;
  25347. for ( let i = 0; i < lights.length; i ++ ) {
  25348. lightIDs.push( lights[ i ].id );
  25349. }
  25350. return hashArray( lightIDs );
  25351. }
  25352. /**
  25353. * Computes a hash value for identifying the current light nodes setup.
  25354. *
  25355. * @param {NodeBuilder} builder - A reference to the current node builder.
  25356. * @return {string} The computed hash.
  25357. */
  25358. getHash( builder ) {
  25359. if ( this._lightNodesHash === null ) {
  25360. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25361. const hash = [];
  25362. for ( const lightNode of this._lightNodes ) {
  25363. hash.push( lightNode.getSelf().getHash() );
  25364. }
  25365. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25366. }
  25367. return this._lightNodesHash;
  25368. }
  25369. analyze( builder ) {
  25370. const properties = builder.getDataFromNode( this );
  25371. for ( const node of properties.nodes ) {
  25372. node.build( builder );
  25373. }
  25374. }
  25375. /**
  25376. * Creates lighting nodes for each scene light. This makes it possible to further
  25377. * process lights in the node system.
  25378. *
  25379. * @param {NodeBuilder} builder - A reference to the current node builder.
  25380. */
  25381. setupLightsNode( builder ) {
  25382. const lightNodes = [];
  25383. const previousLightNodes = this._lightNodes;
  25384. const lights = sortLights( this._lights );
  25385. const nodeLibrary = builder.renderer.library;
  25386. for ( const light of lights ) {
  25387. if ( light.isNode ) {
  25388. lightNodes.push( nodeObject( light ) );
  25389. } else {
  25390. let lightNode = null;
  25391. if ( previousLightNodes !== null ) {
  25392. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  25393. }
  25394. if ( lightNode === null ) {
  25395. // find the corresponding node type for a given light
  25396. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25397. if ( lightNodeClass === null ) {
  25398. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25399. continue;
  25400. }
  25401. let lightNode = null;
  25402. if ( ! _lightsNodeRef.has( light ) ) {
  25403. lightNode = nodeObject( new lightNodeClass( light ) );
  25404. _lightsNodeRef.set( light, lightNode );
  25405. } else {
  25406. lightNode = _lightsNodeRef.get( light );
  25407. }
  25408. lightNodes.push( lightNode );
  25409. }
  25410. }
  25411. }
  25412. this._lightNodes = lightNodes;
  25413. }
  25414. /**
  25415. * Setups the internal lights by building all respective
  25416. * light nodes.
  25417. *
  25418. * @param {NodeBuilder} builder - A reference to the current node builder.
  25419. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  25420. */
  25421. setupLights( builder, lightNodes ) {
  25422. for ( const lightNode of lightNodes ) {
  25423. lightNode.build( builder );
  25424. }
  25425. }
  25426. /**
  25427. * The implementation makes sure that for each light in the scene
  25428. * there is a corresponding light node. By building the light nodes
  25429. * and evaluating the lighting model the outgoing light is computed.
  25430. *
  25431. * @param {NodeBuilder} builder - A reference to the current node builder.
  25432. * @return {Node<vec3>} A node representing the outgoing light.
  25433. */
  25434. setup( builder ) {
  25435. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25436. const context = builder.context;
  25437. const lightingModel = context.lightingModel;
  25438. let outgoingLightNode = this.outgoingLightNode;
  25439. if ( lightingModel ) {
  25440. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25441. context.outgoingLight = outgoingLightNode;
  25442. const stack = builder.addStack();
  25443. //
  25444. const properties = builder.getDataFromNode( this );
  25445. properties.nodes = stack.nodes;
  25446. //
  25447. lightingModel.start( context, stack, builder );
  25448. // lights
  25449. this.setupLights( builder, _lightNodes );
  25450. //
  25451. lightingModel.indirect( context, stack, builder );
  25452. //
  25453. const { backdrop, backdropAlpha } = context;
  25454. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25455. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25456. if ( backdrop !== null ) {
  25457. if ( backdropAlpha !== null ) {
  25458. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25459. } else {
  25460. totalDiffuse = vec3( backdrop );
  25461. }
  25462. context.material.transparent = true;
  25463. }
  25464. totalDiffuseNode.assign( totalDiffuse );
  25465. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25466. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25467. //
  25468. lightingModel.finish( context, stack, builder );
  25469. //
  25470. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25471. }
  25472. return outgoingLightNode;
  25473. }
  25474. /**
  25475. * Configures this node with an array of lights.
  25476. *
  25477. * @param {Array<Light>} lights - An array of lights.
  25478. * @return {LightsNode} A reference to this node.
  25479. */
  25480. setLights( lights ) {
  25481. this._lights = lights;
  25482. this._lightNodes = null;
  25483. this._lightNodesHash = null;
  25484. return this;
  25485. }
  25486. /**
  25487. * Returns an array of the scene's lights.
  25488. *
  25489. * @return {Array<Light>} The scene's lights.
  25490. */
  25491. getLights() {
  25492. return this._lights;
  25493. }
  25494. /**
  25495. * Whether the scene has lights or not.
  25496. *
  25497. * @type {boolean}
  25498. */
  25499. get hasLights() {
  25500. return this._lights.length > 0;
  25501. }
  25502. }
  25503. /**
  25504. * TSL function for creating an instance of `LightsNode` and configuring
  25505. * it with the given array of lights.
  25506. *
  25507. * @tsl
  25508. * @function
  25509. * @param {Array<Light>} lights - An array of lights.
  25510. * @return {LightsNode} The created lights node.
  25511. */
  25512. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  25513. /**
  25514. * Base class for all shadow nodes.
  25515. *
  25516. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  25517. * Lighting nodes might share the same shadow node type or use specific ones depending on
  25518. * their requirements.
  25519. *
  25520. * @augments Node
  25521. */
  25522. class ShadowBaseNode extends Node {
  25523. static get type() {
  25524. return 'ShadowBaseNode';
  25525. }
  25526. /**
  25527. * Constructs a new shadow base node.
  25528. *
  25529. * @param {Light} light - The shadow casting light.
  25530. */
  25531. constructor( light ) {
  25532. super();
  25533. /**
  25534. * The shadow casting light.
  25535. *
  25536. * @type {Light}
  25537. */
  25538. this.light = light;
  25539. /**
  25540. * Overwritten since shadows are updated by default per render.
  25541. *
  25542. * @type {string}
  25543. * @default 'render'
  25544. */
  25545. this.updateBeforeType = NodeUpdateType.RENDER;
  25546. /**
  25547. * This flag can be used for type testing.
  25548. *
  25549. * @type {boolean}
  25550. * @readonly
  25551. * @default true
  25552. */
  25553. this.isShadowBaseNode = true;
  25554. }
  25555. /**
  25556. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  25557. *
  25558. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  25559. */
  25560. setupShadowPosition( { material } ) {
  25561. // Use assign inside an Fn()
  25562. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  25563. }
  25564. /**
  25565. * Can be called when the shadow isn't required anymore. That can happen when
  25566. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  25567. * to `false`.
  25568. */
  25569. dispose() {
  25570. this.updateBeforeType = NodeUpdateType.NONE;
  25571. }
  25572. }
  25573. /**
  25574. * TSL object that represents the vertex position in world space during the shadow pass.
  25575. *
  25576. * @tsl
  25577. * @type {Node<vec3>}
  25578. */
  25579. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  25580. /**
  25581. * Saves the state of the given renderer and stores it into the given state object.
  25582. *
  25583. * If not state object is provided, the function creates one.
  25584. *
  25585. * @function
  25586. * @param {Renderer} renderer - The renderer.
  25587. * @param {Object} [state={}] - The state.
  25588. * @return {Object} The state.
  25589. */
  25590. function saveRendererState( renderer, state = {} ) {
  25591. state.toneMapping = renderer.toneMapping;
  25592. state.toneMappingExposure = renderer.toneMappingExposure;
  25593. state.outputColorSpace = renderer.outputColorSpace;
  25594. state.renderTarget = renderer.getRenderTarget();
  25595. state.activeCubeFace = renderer.getActiveCubeFace();
  25596. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25597. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25598. state.pixelRatio = renderer.getPixelRatio();
  25599. state.mrt = renderer.getMRT();
  25600. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25601. state.clearAlpha = renderer.getClearAlpha();
  25602. state.autoClear = renderer.autoClear;
  25603. state.scissorTest = renderer.getScissorTest();
  25604. return state;
  25605. }
  25606. /**
  25607. * Saves the state of the given renderer and stores it into the given state object.
  25608. * Besides, the function also resets the state of the renderer to its default values.
  25609. *
  25610. * If not state object is provided, the function creates one.
  25611. *
  25612. * @function
  25613. * @param {Renderer} renderer - The renderer.
  25614. * @param {Object} [state={}] - The state.
  25615. * @return {Object} The state.
  25616. */
  25617. function resetRendererState( renderer, state ) {
  25618. state = saveRendererState( renderer, state );
  25619. renderer.setMRT( null );
  25620. renderer.setRenderObjectFunction( null );
  25621. renderer.setClearColor( 0x000000, 1 );
  25622. renderer.autoClear = true;
  25623. return state;
  25624. }
  25625. /**
  25626. * Restores the state of the given renderer from the given state object.
  25627. *
  25628. * @function
  25629. * @param {Renderer} renderer - The renderer.
  25630. * @param {Object} state - The state to restore.
  25631. */
  25632. function restoreRendererState( renderer, state ) {
  25633. renderer.toneMapping = state.toneMapping;
  25634. renderer.toneMappingExposure = state.toneMappingExposure;
  25635. renderer.outputColorSpace = state.outputColorSpace;
  25636. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25637. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25638. renderer.setPixelRatio( state.pixelRatio );
  25639. renderer.setMRT( state.mrt );
  25640. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25641. renderer.autoClear = state.autoClear;
  25642. renderer.setScissorTest( state.scissorTest );
  25643. }
  25644. /**
  25645. * Saves the state of the given scene and stores it into the given state object.
  25646. *
  25647. * If not state object is provided, the function creates one.
  25648. *
  25649. * @function
  25650. * @param {Scene} scene - The scene.
  25651. * @param {Object} [state={}] - The state.
  25652. * @return {Object} The state.
  25653. */
  25654. function saveSceneState( scene, state = {} ) {
  25655. state.background = scene.background;
  25656. state.backgroundNode = scene.backgroundNode;
  25657. state.overrideMaterial = scene.overrideMaterial;
  25658. return state;
  25659. }
  25660. /**
  25661. * Saves the state of the given scene and stores it into the given state object.
  25662. * Besides, the function also resets the state of the scene to its default values.
  25663. *
  25664. * If not state object is provided, the function creates one.
  25665. *
  25666. * @function
  25667. * @param {Scene} scene - The scene.
  25668. * @param {Object} [state={}] - The state.
  25669. * @return {Object} The state.
  25670. */
  25671. function resetSceneState( scene, state ) {
  25672. state = saveSceneState( scene, state );
  25673. scene.background = null;
  25674. scene.backgroundNode = null;
  25675. scene.overrideMaterial = null;
  25676. return state;
  25677. }
  25678. /**
  25679. * Restores the state of the given scene from the given state object.
  25680. *
  25681. * @function
  25682. * @param {Scene} scene - The scene.
  25683. * @param {Object} state - The state to restore.
  25684. */
  25685. function restoreSceneState( scene, state ) {
  25686. scene.background = state.background;
  25687. scene.backgroundNode = state.backgroundNode;
  25688. scene.overrideMaterial = state.overrideMaterial;
  25689. }
  25690. /**
  25691. * Saves the state of the given renderer and scene and stores it into the given state object.
  25692. *
  25693. * If not state object is provided, the function creates one.
  25694. *
  25695. * @function
  25696. * @param {Renderer} renderer - The renderer.
  25697. * @param {Scene} scene - The scene.
  25698. * @param {Object} [state={}] - The state.
  25699. * @return {Object} The state.
  25700. */
  25701. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25702. state = saveRendererState( renderer, state );
  25703. state = saveSceneState( scene, state );
  25704. return state;
  25705. }
  25706. /**
  25707. * Saves the state of the given renderer and scene and stores it into the given state object.
  25708. * Besides, the function also resets the state of the renderer and scene to its default values.
  25709. *
  25710. * If not state object is provided, the function creates one.
  25711. *
  25712. * @function
  25713. * @param {Renderer} renderer - The renderer.
  25714. * @param {Scene} scene - The scene.
  25715. * @param {Object} [state={}] - The state.
  25716. * @return {Object} The state.
  25717. */
  25718. function resetRendererAndSceneState( renderer, scene, state ) {
  25719. state = resetRendererState( renderer, state );
  25720. state = resetSceneState( scene, state );
  25721. return state;
  25722. }
  25723. /**
  25724. * Restores the state of the given renderer and scene from the given state object.
  25725. *
  25726. * @function
  25727. * @param {Renderer} renderer - The renderer.
  25728. * @param {Scene} scene - The scene.
  25729. * @param {Object} state - The state to restore.
  25730. */
  25731. function restoreRendererAndSceneState( renderer, scene, state ) {
  25732. restoreRendererState( renderer, state );
  25733. restoreSceneState( scene, state );
  25734. }
  25735. var RendererUtils = /*#__PURE__*/Object.freeze({
  25736. __proto__: null,
  25737. resetRendererAndSceneState: resetRendererAndSceneState,
  25738. resetRendererState: resetRendererState,
  25739. resetSceneState: resetSceneState,
  25740. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25741. restoreRendererState: restoreRendererState,
  25742. restoreSceneState: restoreSceneState,
  25743. saveRendererAndSceneState: saveRendererAndSceneState,
  25744. saveRendererState: saveRendererState,
  25745. saveSceneState: saveSceneState
  25746. });
  25747. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25748. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25749. let dist = positionWorld.sub( position ).length();
  25750. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25751. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25752. return dist;
  25753. } );
  25754. const linearShadowDistance = ( light ) => {
  25755. const camera = light.shadow.camera;
  25756. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25757. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25758. const referencePosition = objectPosition( light );
  25759. return linearDistance( referencePosition, nearDistance, farDistance );
  25760. };
  25761. const getShadowMaterial = ( light ) => {
  25762. let material = shadowMaterialLib.get( light );
  25763. if ( material === undefined ) {
  25764. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25765. material = new NodeMaterial();
  25766. material.colorNode = vec4( 0, 0, 0, 1 );
  25767. material.depthNode = depthNode;
  25768. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25769. material.name = 'ShadowMaterial';
  25770. material.fog = false;
  25771. shadowMaterialLib.set( light, material );
  25772. }
  25773. return material;
  25774. };
  25775. /**
  25776. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25777. * with a binary `[0,1]` result.
  25778. *
  25779. * @method
  25780. * @param {Object} inputs - The input parameter object.
  25781. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25782. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25783. * @return {Node<float>} The filtering result.
  25784. */
  25785. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25786. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25787. } );
  25788. /**
  25789. * A shadow filtering function performing PCF filtering.
  25790. *
  25791. * @method
  25792. * @param {Object} inputs - The input parameter object.
  25793. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25794. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25795. * @param {LightShadow} inputs.shadow - The light shadow.
  25796. * @return {Node<float>} The filtering result.
  25797. */
  25798. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25799. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25800. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25801. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25802. const texelSize = vec2( 1 ).div( mapSize );
  25803. const dx0 = texelSize.x.negate().mul( radius );
  25804. const dy0 = texelSize.y.negate().mul( radius );
  25805. const dx1 = texelSize.x.mul( radius );
  25806. const dy1 = texelSize.y.mul( radius );
  25807. const dx2 = dx0.div( 2 );
  25808. const dy2 = dy0.div( 2 );
  25809. const dx3 = dx1.div( 2 );
  25810. const dy3 = dy1.div( 2 );
  25811. return add(
  25812. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25813. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25814. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25815. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25816. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25817. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25818. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25819. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25820. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25821. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25822. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25823. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25824. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25825. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25826. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25827. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25828. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25829. ).mul( 1 / 17 );
  25830. } );
  25831. /**
  25832. * A shadow filtering function performing PCF soft filtering.
  25833. *
  25834. * @method
  25835. * @param {Object} inputs - The input parameter object.
  25836. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25837. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25838. * @param {LightShadow} inputs.shadow - The light shadow.
  25839. * @return {Node<float>} The filtering result.
  25840. */
  25841. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25842. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25843. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25844. const texelSize = vec2( 1 ).div( mapSize );
  25845. const dx = texelSize.x;
  25846. const dy = texelSize.y;
  25847. const uv = shadowCoord.xy;
  25848. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25849. uv.subAssign( f.mul( texelSize ) );
  25850. return add(
  25851. depthCompare( uv, shadowCoord.z ),
  25852. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25853. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25854. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25855. mix(
  25856. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25857. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25858. f.x
  25859. ),
  25860. mix(
  25861. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25862. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25863. f.x
  25864. ),
  25865. mix(
  25866. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25867. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25868. f.y
  25869. ),
  25870. mix(
  25871. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25872. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25873. f.y
  25874. ),
  25875. mix(
  25876. mix(
  25877. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25878. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25879. f.x
  25880. ),
  25881. mix(
  25882. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25883. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25884. f.x
  25885. ),
  25886. f.y
  25887. )
  25888. ).mul( 1 / 9 );
  25889. } );
  25890. /**
  25891. * A shadow filtering function performing VSM filtering.
  25892. *
  25893. * @method
  25894. * @param {Object} inputs - The input parameter object.
  25895. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25896. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25897. * @return {Node<float>} The filtering result.
  25898. */
  25899. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25900. const occlusion = float( 1 ).toVar();
  25901. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25902. const hardShadow = step( shadowCoord.z, distribution.x );
  25903. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25904. const distance = shadowCoord.z.sub( distribution.x );
  25905. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25906. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25907. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25908. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25909. } );
  25910. return occlusion;
  25911. } );
  25912. /**
  25913. * Represents the shader code for the first VSM render pass.
  25914. *
  25915. * @method
  25916. * @param {Object} inputs - The input parameter object.
  25917. * @param {Node<float>} inputs.samples - The number of samples
  25918. * @param {Node<float>} inputs.radius - The radius.
  25919. * @param {Node<float>} inputs.size - The size.
  25920. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25921. * @return {Node<vec2>} The VSM output.
  25922. */
  25923. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25924. const mean = float( 0 ).toVar();
  25925. const squaredMean = float( 0 ).toVar();
  25926. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25927. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25928. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25929. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25930. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25931. mean.addAssign( depth );
  25932. squaredMean.addAssign( depth.mul( depth ) );
  25933. } );
  25934. mean.divAssign( samples );
  25935. squaredMean.divAssign( samples );
  25936. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25937. return vec2( mean, std_dev );
  25938. } );
  25939. /**
  25940. * Represents the shader code for the second VSM render pass.
  25941. *
  25942. * @method
  25943. * @param {Object} inputs - The input parameter object.
  25944. * @param {Node<float>} inputs.samples - The number of samples
  25945. * @param {Node<float>} inputs.radius - The radius.
  25946. * @param {Node<float>} inputs.size - The size.
  25947. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25948. * @return {Node<vec2>} The VSM output.
  25949. */
  25950. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25951. const mean = float( 0 ).toVar();
  25952. const squaredMean = float( 0 ).toVar();
  25953. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25954. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25955. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25956. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25957. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25958. mean.addAssign( distribution.x );
  25959. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25960. } );
  25961. mean.divAssign( samples );
  25962. squaredMean.divAssign( samples );
  25963. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25964. return vec2( mean, std_dev );
  25965. } );
  25966. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25967. //
  25968. let _rendererState;
  25969. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25970. /**
  25971. * Represents the default shadow implementation for lighting nodes.
  25972. *
  25973. * @augments ShadowBaseNode
  25974. */
  25975. class ShadowNode extends ShadowBaseNode {
  25976. static get type() {
  25977. return 'ShadowNode';
  25978. }
  25979. /**
  25980. * Constructs a new shadow node.
  25981. *
  25982. * @param {Light} light - The shadow casting light.
  25983. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  25984. */
  25985. constructor( light, shadow = null ) {
  25986. super( light );
  25987. /**
  25988. * The light shadow which defines the properties light's
  25989. * shadow.
  25990. *
  25991. * @type {?LightShadow}
  25992. * @default null
  25993. */
  25994. this.shadow = shadow || light.shadow;
  25995. /**
  25996. * A reference to the shadow map which is a render target.
  25997. *
  25998. * @type {?RenderTarget}
  25999. * @default null
  26000. */
  26001. this.shadowMap = null;
  26002. /**
  26003. * Only relevant for VSM shadows. Render target for the
  26004. * first VSM render pass.
  26005. *
  26006. * @type {?RenderTarget}
  26007. * @default null
  26008. */
  26009. this.vsmShadowMapVertical = null;
  26010. /**
  26011. * Only relevant for VSM shadows. Render target for the
  26012. * second VSM render pass.
  26013. *
  26014. * @type {?RenderTarget}
  26015. * @default null
  26016. */
  26017. this.vsmShadowMapHorizontal = null;
  26018. /**
  26019. * Only relevant for VSM shadows. Node material which
  26020. * is used to render the first VSM pass.
  26021. *
  26022. * @type {?NodeMaterial}
  26023. * @default null
  26024. */
  26025. this.vsmMaterialVertical = null;
  26026. /**
  26027. * Only relevant for VSM shadows. Node material which
  26028. * is used to render the second VSM pass.
  26029. *
  26030. * @type {?NodeMaterial}
  26031. * @default null
  26032. */
  26033. this.vsmMaterialHorizontal = null;
  26034. /**
  26035. * A reference to the output node which defines the
  26036. * final result of this shadow node.
  26037. *
  26038. * @type {?Node}
  26039. * @private
  26040. * @default null
  26041. */
  26042. this._node = null;
  26043. /**
  26044. * This flag can be used for type testing.
  26045. *
  26046. * @type {boolean}
  26047. * @readonly
  26048. * @default true
  26049. */
  26050. this.isShadowNode = true;
  26051. }
  26052. /**
  26053. * Setups the shadow filtering.
  26054. *
  26055. * @param {NodeBuilder} builder - A reference to the current node builder.
  26056. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26057. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26058. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26059. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26060. * @param {LightShadow} inputs.shadow - The light shadow.
  26061. * @return {Node<float>} The result node of the shadow filtering.
  26062. */
  26063. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  26064. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26065. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26066. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26067. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26068. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26069. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  26070. return frustumTest.select( shadowNode, float( 1 ) );
  26071. }
  26072. /**
  26073. * Setups the shadow coordinates.
  26074. *
  26075. * @param {NodeBuilder} builder - A reference to the current node builder.
  26076. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26077. * @return {Node<vec3>} The shadow coordinates.
  26078. */
  26079. setupShadowCoord( builder, shadowPosition ) {
  26080. const { shadow } = this;
  26081. const { renderer } = builder;
  26082. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26083. let shadowCoord = shadowPosition;
  26084. let coordZ;
  26085. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  26086. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26087. coordZ = shadowCoord.z;
  26088. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26089. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  26090. }
  26091. } else {
  26092. const w = shadowCoord.w;
  26093. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  26094. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  26095. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  26096. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  26097. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  26098. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  26099. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  26100. }
  26101. shadowCoord = vec3(
  26102. shadowCoord.x,
  26103. shadowCoord.y.oneMinus(), // follow webgpu standards
  26104. coordZ.add( bias )
  26105. );
  26106. return shadowCoord;
  26107. }
  26108. /**
  26109. * Returns the shadow filtering function for the given shadow type.
  26110. *
  26111. * @param {number} type - The shadow type.
  26112. * @return {Function} The filtering function.
  26113. */
  26114. getShadowFilterFn( type ) {
  26115. return _shadowFilterLib[ type ];
  26116. }
  26117. /**
  26118. * Setups the shadow output node.
  26119. *
  26120. * @param {NodeBuilder} builder - A reference to the current node builder.
  26121. * @return {Node<vec3>} The shadow output node.
  26122. */
  26123. setupShadow( builder ) {
  26124. const { renderer } = builder;
  26125. const { light, shadow } = this;
  26126. const shadowMapType = renderer.shadowMap.type;
  26127. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  26128. depthTexture.compareFunction = LessCompare;
  26129. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  26130. shadowMap.depthTexture = depthTexture;
  26131. shadow.camera.updateProjectionMatrix();
  26132. // VSM
  26133. if ( shadowMapType === VSMShadowMap ) {
  26134. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  26135. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26136. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26137. const shadowPassVertical = texture( depthTexture );
  26138. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  26139. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  26140. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26141. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26142. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  26143. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  26144. material.name = 'VSMVertical';
  26145. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  26146. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  26147. material.name = 'VSMHorizontal';
  26148. }
  26149. //
  26150. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  26151. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  26152. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  26153. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  26154. //
  26155. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  26156. if ( filterFn === null ) {
  26157. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  26158. }
  26159. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  26160. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  26161. const shadowColor = texture( shadowMap.texture, shadowCoord );
  26162. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  26163. this.shadowMap = shadowMap;
  26164. this.shadow.map = shadowMap;
  26165. return shadowOutput;
  26166. }
  26167. /**
  26168. * The implementation performs the setup of the output node. An output is only
  26169. * produces if shadow mapping is globally enabled in the renderer.
  26170. *
  26171. * @param {NodeBuilder} builder - A reference to the current node builder.
  26172. * @return {ShaderCallNodeInternal} The output node.
  26173. */
  26174. setup( builder ) {
  26175. if ( builder.renderer.shadowMap.enabled === false ) return;
  26176. return Fn( () => {
  26177. let node = this._node;
  26178. this.setupShadowPosition( builder );
  26179. if ( node === null ) {
  26180. this._node = node = this.setupShadow( builder );
  26181. }
  26182. if ( builder.material.shadowNode ) { // @deprecated, r171
  26183. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  26184. }
  26185. if ( builder.material.receivedShadowNode ) {
  26186. node = builder.material.receivedShadowNode( node );
  26187. }
  26188. return node;
  26189. } )();
  26190. }
  26191. /**
  26192. * Renders the shadow. The logic of this function could be included
  26193. * into {@link ShadowNode#updateShadow} however more specialized shadow
  26194. * nodes might require a custom shadow map rendering. By having a
  26195. * dedicated method, it's easier to overwrite the default behavior.
  26196. *
  26197. * @param {NodeFrame} frame - A reference to the current node frame.
  26198. */
  26199. renderShadow( frame ) {
  26200. const { shadow, shadowMap, light } = this;
  26201. const { renderer, scene } = frame;
  26202. shadow.updateMatrices( light );
  26203. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26204. renderer.render( scene, shadow.camera );
  26205. }
  26206. /**
  26207. * Updates the shadow.
  26208. *
  26209. * @param {NodeFrame} frame - A reference to the current node frame.
  26210. */
  26211. updateShadow( frame ) {
  26212. const { shadowMap, light, shadow } = this;
  26213. const { renderer, scene, camera } = frame;
  26214. const shadowType = renderer.shadowMap.type;
  26215. const depthVersion = shadowMap.depthTexture.version;
  26216. this._depthVersionCached = depthVersion;
  26217. shadow.camera.layers.mask = camera.layers.mask;
  26218. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26219. const currentMRT = renderer.getMRT();
  26220. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  26221. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  26222. scene.overrideMaterial = getShadowMaterial( light );
  26223. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  26224. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  26225. if ( useVelocity ) {
  26226. getDataFromObject( object ).useVelocity = true;
  26227. }
  26228. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  26229. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  26230. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  26231. }
  26232. } );
  26233. renderer.setRenderTarget( shadowMap );
  26234. this.renderShadow( frame );
  26235. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26236. // vsm blur pass
  26237. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  26238. this.vsmPass( renderer );
  26239. }
  26240. restoreRendererAndSceneState( renderer, scene, _rendererState );
  26241. }
  26242. /**
  26243. * For VSM additional render passes are required.
  26244. *
  26245. * @param {Renderer} renderer - A reference to the current renderer.
  26246. */
  26247. vsmPass( renderer ) {
  26248. const { shadow } = this;
  26249. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26250. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26251. renderer.setRenderTarget( this.vsmShadowMapVertical );
  26252. _quadMesh.material = this.vsmMaterialVertical;
  26253. _quadMesh.render( renderer );
  26254. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  26255. _quadMesh.material = this.vsmMaterialHorizontal;
  26256. _quadMesh.render( renderer );
  26257. }
  26258. /**
  26259. * Frees the internal resources of this shadow node.
  26260. */
  26261. dispose() {
  26262. this.shadowMap.dispose();
  26263. this.shadowMap = null;
  26264. if ( this.vsmShadowMapVertical !== null ) {
  26265. this.vsmShadowMapVertical.dispose();
  26266. this.vsmShadowMapVertical = null;
  26267. this.vsmMaterialVertical.dispose();
  26268. this.vsmMaterialVertical = null;
  26269. }
  26270. if ( this.vsmShadowMapHorizontal !== null ) {
  26271. this.vsmShadowMapHorizontal.dispose();
  26272. this.vsmShadowMapHorizontal = null;
  26273. this.vsmMaterialHorizontal.dispose();
  26274. this.vsmMaterialHorizontal = null;
  26275. }
  26276. super.dispose();
  26277. }
  26278. /**
  26279. * The implementation performs the update of the shadow map if necessary.
  26280. *
  26281. * @param {NodeFrame} frame - A reference to the current node frame.
  26282. */
  26283. updateBefore( frame ) {
  26284. const { shadow } = this;
  26285. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  26286. if ( needsUpdate ) {
  26287. this.updateShadow( frame );
  26288. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  26289. shadow.needsUpdate = false;
  26290. }
  26291. }
  26292. }
  26293. }
  26294. /**
  26295. * TSL function for creating an instance of `ShadowNode`.
  26296. *
  26297. * @tsl
  26298. * @function
  26299. * @param {Light} light - The shadow casting light.
  26300. * @param {LightShadow} shadow - The light shadow.
  26301. * @return {ShadowNode} The created shadow node.
  26302. */
  26303. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  26304. /**
  26305. * Base class for analytic light nodes.
  26306. *
  26307. * @augments LightingNode
  26308. */
  26309. class AnalyticLightNode extends LightingNode {
  26310. static get type() {
  26311. return 'AnalyticLightNode';
  26312. }
  26313. /**
  26314. * Constructs a new analytic light node.
  26315. *
  26316. * @param {?Light} [light=null] - The light source.
  26317. */
  26318. constructor( light = null ) {
  26319. super();
  26320. /**
  26321. * The light source.
  26322. *
  26323. * @type {?Light}
  26324. * @default null
  26325. */
  26326. this.light = light;
  26327. /**
  26328. * The light's color value.
  26329. *
  26330. * @type {Color}
  26331. */
  26332. this.color = new Color();
  26333. /**
  26334. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  26335. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  26336. *
  26337. * @type {Node}
  26338. */
  26339. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  26340. /**
  26341. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  26342. * The final color node is represented by a different node when using shadows.
  26343. *
  26344. * @type {?Node}
  26345. * @default null
  26346. */
  26347. this.baseColorNode = null;
  26348. /**
  26349. * Represents the light's shadow.
  26350. *
  26351. * @type {?ShadowNode}
  26352. * @default null
  26353. */
  26354. this.shadowNode = null;
  26355. /**
  26356. * Represents the light's shadow color.
  26357. *
  26358. * @type {?Node}
  26359. * @default null
  26360. */
  26361. this.shadowColorNode = null;
  26362. /**
  26363. * This flag can be used for type testing.
  26364. *
  26365. * @type {boolean}
  26366. * @readonly
  26367. * @default true
  26368. */
  26369. this.isAnalyticLightNode = true;
  26370. /**
  26371. * Overwritten since analytic light nodes are updated
  26372. * once per frame.
  26373. *
  26374. * @type {string}
  26375. * @default 'frame'
  26376. */
  26377. this.updateType = NodeUpdateType.FRAME;
  26378. }
  26379. /**
  26380. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  26381. * `light.id` and `light.castShadow` into the cache key.
  26382. *
  26383. * @return {number} The custom cache key.
  26384. */
  26385. customCacheKey() {
  26386. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  26387. }
  26388. getHash() {
  26389. return this.light.uuid;
  26390. }
  26391. /**
  26392. * Setups the shadow node for this light. The method exists so concrete light classes
  26393. * can setup different types of shadow nodes.
  26394. *
  26395. * @return {ShadowNode} The created shadow node.
  26396. */
  26397. setupShadowNode() {
  26398. return shadow( this.light );
  26399. }
  26400. /**
  26401. * Setups the shadow for this light. This method is only executed if the light
  26402. * cast shadows and the current build object receives shadows. It incorporates
  26403. * shadows into the lighting computation.
  26404. *
  26405. * @param {NodeBuilder} builder - The current node builder.
  26406. */
  26407. setupShadow( builder ) {
  26408. const { renderer } = builder;
  26409. if ( renderer.shadowMap.enabled === false ) return;
  26410. let shadowColorNode = this.shadowColorNode;
  26411. if ( shadowColorNode === null ) {
  26412. const customShadowNode = this.light.shadow.shadowNode;
  26413. let shadowNode;
  26414. if ( customShadowNode !== undefined ) {
  26415. shadowNode = nodeObject( customShadowNode );
  26416. } else {
  26417. shadowNode = this.setupShadowNode( builder );
  26418. }
  26419. this.shadowNode = shadowNode;
  26420. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  26421. this.baseColorNode = this.colorNode;
  26422. }
  26423. //
  26424. this.colorNode = shadowColorNode;
  26425. }
  26426. /**
  26427. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  26428. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  26429. * invocate the respective interface methods.
  26430. *
  26431. * @param {NodeBuilder} builder - The current node builder.
  26432. */
  26433. setup( builder ) {
  26434. this.colorNode = this.baseColorNode || this.colorNode;
  26435. if ( this.light.castShadow ) {
  26436. if ( builder.object.receiveShadow ) {
  26437. this.setupShadow( builder );
  26438. }
  26439. } else if ( this.shadowNode !== null ) {
  26440. this.shadowNode.dispose();
  26441. this.shadowNode = null;
  26442. this.shadowColorNode = null;
  26443. }
  26444. }
  26445. /**
  26446. * The update method is used to update light uniforms per frame.
  26447. * Potentially overwritten in concrete light nodes to update light
  26448. * specific uniforms.
  26449. *
  26450. * @param {NodeFrame} frame - A reference to the current node frame.
  26451. */
  26452. update( /*frame*/ ) {
  26453. const { light } = this;
  26454. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26455. }
  26456. }
  26457. /**
  26458. * Represents a `discard` shader operation in TSL.
  26459. *
  26460. * @method
  26461. * @param {Object} inputs - The input parameter object.
  26462. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  26463. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  26464. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  26465. * @return {Node<float>} The distance falloff.
  26466. */
  26467. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  26468. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  26469. // based upon Frostbite 3 Moving to Physically-based Rendering
  26470. // page 32, equation 26: E[window1]
  26471. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  26472. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  26473. return cutoffDistance.greaterThan( 0 ).select(
  26474. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  26475. distanceFalloff
  26476. );
  26477. } ); // validated
  26478. const _clearColor$2 = /*@__PURE__*/ new Color();
  26479. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  26480. // vector suitable for 2D texture mapping. This code uses the following layout for the
  26481. // 2D texture:
  26482. //
  26483. // xzXZ
  26484. // y Y
  26485. //
  26486. // Y - Positive y direction
  26487. // y - Negative y direction
  26488. // X - Positive x direction
  26489. // x - Negative x direction
  26490. // Z - Positive z direction
  26491. // z - Negative z direction
  26492. //
  26493. // Source and test bed:
  26494. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  26495. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  26496. const v = pos.toVar();
  26497. // Number of texels to avoid at the edge of each square
  26498. const absV = abs( v );
  26499. // Intersect unit cube
  26500. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  26501. absV.mulAssign( scaleToCube );
  26502. // Apply scale to avoid seams
  26503. // two texels less per square (one texel will do for NEAREST)
  26504. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  26505. // Unwrap
  26506. // space: -1 ... 1 range for each square
  26507. //
  26508. // #X## dim := ( 4 , 2 )
  26509. // # # center := ( 1 , 1 )
  26510. const planar = vec2( v.xy ).toVar();
  26511. const almostATexel = texelSizeY.mul( 1.5 );
  26512. const almostOne = almostATexel.oneMinus();
  26513. If( absV.z.greaterThanEqual( almostOne ), () => {
  26514. If( v.z.greaterThan( 0.0 ), () => {
  26515. planar.x.assign( sub( 4.0, v.x ) );
  26516. } );
  26517. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  26518. const signX = sign( v.x );
  26519. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  26520. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  26521. const signY = sign( v.y );
  26522. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  26523. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  26524. } );
  26525. // Transform to UV space
  26526. // scale := 0.5 / dim
  26527. // translate := ( center + 0.5 ) / dim
  26528. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  26529. } ).setLayout( {
  26530. name: 'cubeToUV',
  26531. type: 'vec2',
  26532. inputs: [
  26533. { name: 'pos', type: 'vec3' },
  26534. { name: 'texelSizeY', type: 'float' }
  26535. ]
  26536. } );
  26537. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  26538. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  26539. } );
  26540. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  26541. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26542. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  26543. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  26544. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  26545. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  26546. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  26547. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  26548. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  26549. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  26550. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  26551. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  26552. .mul( 1.0 / 9.0 );
  26553. } );
  26554. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  26555. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  26556. // the vector from the light to the world-space position of the fragment.
  26557. const lightToPosition = shadowCoord.xyz.toVar();
  26558. const lightToPositionLength = lightToPosition.length();
  26559. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  26560. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  26561. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26562. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  26563. const result = float( 1.0 ).toVar();
  26564. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  26565. // dp = normalized distance from light to fragment position
  26566. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  26567. dp.addAssign( bias );
  26568. // bd3D = base direction 3D
  26569. const bd3D = lightToPosition.normalize();
  26570. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  26571. // percentage-closer filtering
  26572. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  26573. } );
  26574. return result;
  26575. } );
  26576. const _viewport = /*@__PURE__*/ new Vector4();
  26577. const _viewportSize = /*@__PURE__*/ new Vector2();
  26578. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  26579. /**
  26580. * Represents the shadow implementation for point light nodes.
  26581. *
  26582. * @augments ShadowNode
  26583. */
  26584. class PointShadowNode extends ShadowNode {
  26585. static get type() {
  26586. return 'PointShadowNode';
  26587. }
  26588. /**
  26589. * Constructs a new point shadow node.
  26590. *
  26591. * @param {PointLight} light - The shadow casting point light.
  26592. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  26593. */
  26594. constructor( light, shadow = null ) {
  26595. super( light, shadow );
  26596. }
  26597. /**
  26598. * Overwrites the default implementation to return point light shadow specific
  26599. * filtering functions.
  26600. *
  26601. * @param {number} type - The shadow type.
  26602. * @return {Function} The filtering function.
  26603. */
  26604. getShadowFilterFn( type ) {
  26605. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  26606. }
  26607. /**
  26608. * Overwrites the default implementation so the unaltered shadow position is used.
  26609. *
  26610. * @param {NodeBuilder} builder - A reference to the current node builder.
  26611. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26612. * @return {Node<vec3>} The shadow coordinates.
  26613. */
  26614. setupShadowCoord( builder, shadowPosition ) {
  26615. return shadowPosition;
  26616. }
  26617. /**
  26618. * Overwrites the default implementation to only use point light specific
  26619. * shadow filter functions.
  26620. *
  26621. * @param {NodeBuilder} builder - A reference to the current node builder.
  26622. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26623. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26624. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  26625. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26626. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26627. * @param {LightShadow} inputs.shadow - The light shadow.
  26628. * @return {Node<float>} The result node of the shadow filtering.
  26629. */
  26630. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  26631. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  26632. }
  26633. /**
  26634. * Overwrites the default implementation with point light specific
  26635. * rendering code.
  26636. *
  26637. * @param {NodeFrame} frame - A reference to the current node frame.
  26638. */
  26639. renderShadow( frame ) {
  26640. const { shadow, shadowMap, light } = this;
  26641. const { renderer, scene } = frame;
  26642. const shadowFrameExtents = shadow.getFrameExtents();
  26643. _shadowMapSize.copy( shadow.mapSize );
  26644. _shadowMapSize.multiply( shadowFrameExtents );
  26645. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  26646. _viewportSize.copy( shadow.mapSize );
  26647. //
  26648. const previousAutoClear = renderer.autoClear;
  26649. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  26650. const previousClearAlpha = renderer.getClearAlpha();
  26651. renderer.autoClear = false;
  26652. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  26653. renderer.clear();
  26654. const viewportCount = shadow.getViewportCount();
  26655. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  26656. const viewport = shadow.getViewport( vp );
  26657. const x = _viewportSize.x * viewport.x;
  26658. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  26659. _viewport.set(
  26660. x,
  26661. y,
  26662. _viewportSize.x * viewport.z,
  26663. _viewportSize.y * viewport.w
  26664. );
  26665. shadowMap.viewport.copy( _viewport );
  26666. shadow.updateMatrices( light, vp );
  26667. renderer.render( scene, shadow.camera );
  26668. }
  26669. //
  26670. renderer.autoClear = previousAutoClear;
  26671. renderer.setClearColor( previousClearColor, previousClearAlpha );
  26672. }
  26673. }
  26674. /**
  26675. * TSL function for creating an instance of `PointShadowNode`.
  26676. *
  26677. * @tsl
  26678. * @function
  26679. * @param {PointLight} light - The shadow casting point light.
  26680. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  26681. * @return {PointShadowNode} The created point shadow node.
  26682. */
  26683. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  26684. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  26685. const lightingModel = builder.context.lightingModel;
  26686. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  26687. const lightDirection = lVector.normalize();
  26688. const lightDistance = lVector.length();
  26689. const lightAttenuation = getDistanceAttenuation( {
  26690. lightDistance,
  26691. cutoffDistance,
  26692. decayExponent
  26693. } );
  26694. const lightColor = color.mul( lightAttenuation );
  26695. const reflectedLight = builder.context.reflectedLight;
  26696. lightingModel.direct( {
  26697. lightDirection,
  26698. lightColor,
  26699. reflectedLight
  26700. }, builder.stack, builder );
  26701. } );
  26702. /**
  26703. * Module for representing point lights as nodes.
  26704. *
  26705. * @augments AnalyticLightNode
  26706. */
  26707. class PointLightNode extends AnalyticLightNode {
  26708. static get type() {
  26709. return 'PointLightNode';
  26710. }
  26711. /**
  26712. * Constructs a new point light node.
  26713. *
  26714. * @param {?PointLight} [light=null] - The point light source.
  26715. */
  26716. constructor( light = null ) {
  26717. super( light );
  26718. /**
  26719. * Uniform node representing the cutoff distance.
  26720. *
  26721. * @type {UniformNode<float>}
  26722. */
  26723. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26724. /**
  26725. * Uniform node representing the decay exponent.
  26726. *
  26727. * @type {UniformNode<float>}
  26728. */
  26729. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26730. }
  26731. /**
  26732. * Overwritten to updated point light specific uniforms.
  26733. *
  26734. * @param {NodeFrame} frame - A reference to the current node frame.
  26735. */
  26736. update( frame ) {
  26737. const { light } = this;
  26738. super.update( frame );
  26739. this.cutoffDistanceNode.value = light.distance;
  26740. this.decayExponentNode.value = light.decay;
  26741. }
  26742. /**
  26743. * Overwritten to setup point light specific shadow.
  26744. *
  26745. * @return {PointShadowNode}
  26746. */
  26747. setupShadowNode() {
  26748. return pointShadow( this.light );
  26749. }
  26750. setup( builder ) {
  26751. super.setup( builder );
  26752. directPointLight( {
  26753. color: this.colorNode,
  26754. lightViewPosition: lightViewPosition( this.light ),
  26755. cutoffDistance: this.cutoffDistanceNode,
  26756. decayExponent: this.decayExponentNode
  26757. } ).append();
  26758. }
  26759. }
  26760. /**
  26761. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26762. *
  26763. * @tsl
  26764. * @function
  26765. * @param {Node<vec2>} coord - The uv coordinates.
  26766. * @return {Node<float>} The result data.
  26767. */
  26768. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26769. const uv = coord.mul( 2.0 );
  26770. const cx = uv.x.floor();
  26771. const cy = uv.y.floor();
  26772. const result = cx.add( cy ).mod( 2.0 );
  26773. return result.sign();
  26774. } );
  26775. /**
  26776. * Generates a circle based on the uv coordinates.
  26777. *
  26778. * @tsl
  26779. * @function
  26780. * @param {Node<vec2>} coord - The uv to generate the circle.
  26781. * @return {Node<float>} The circle shape.
  26782. */
  26783. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26784. const alpha = float( 1 ).toVar();
  26785. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26786. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26787. const dlen = float( len2.fwidth() ).toVar();
  26788. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26789. } else {
  26790. len2.greaterThan( 1.0 ).discard();
  26791. }
  26792. return alpha;
  26793. } );
  26794. // Three.js Transpiler
  26795. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26796. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26797. const f = float( f_immutable ).toVar();
  26798. const t = float( t_immutable ).toVar();
  26799. const b = bool( b_immutable ).toVar();
  26800. return select( b, t, f );
  26801. } ).setLayout( {
  26802. name: 'mx_select',
  26803. type: 'float',
  26804. inputs: [
  26805. { name: 'b', type: 'bool' },
  26806. { name: 't', type: 'float' },
  26807. { name: 'f', type: 'float' }
  26808. ]
  26809. } );
  26810. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26811. const b = bool( b_immutable ).toVar();
  26812. const val = float( val_immutable ).toVar();
  26813. return select( b, val.negate(), val );
  26814. } ).setLayout( {
  26815. name: 'mx_negate_if',
  26816. type: 'float',
  26817. inputs: [
  26818. { name: 'val', type: 'float' },
  26819. { name: 'b', type: 'bool' }
  26820. ]
  26821. } );
  26822. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26823. const x = float( x_immutable ).toVar();
  26824. return int( floor( x ) );
  26825. } ).setLayout( {
  26826. name: 'mx_floor',
  26827. type: 'int',
  26828. inputs: [
  26829. { name: 'x', type: 'float' }
  26830. ]
  26831. } );
  26832. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26833. const x = float( x_immutable ).toVar();
  26834. i.assign( mx_floor( x ) );
  26835. return x.sub( float( i ) );
  26836. } );
  26837. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26838. const t = float( t_immutable ).toVar();
  26839. const s = float( s_immutable ).toVar();
  26840. const v3 = float( v3_immutable ).toVar();
  26841. const v2 = float( v2_immutable ).toVar();
  26842. const v1 = float( v1_immutable ).toVar();
  26843. const v0 = float( v0_immutable ).toVar();
  26844. const s1 = float( sub( 1.0, s ) ).toVar();
  26845. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26846. } ).setLayout( {
  26847. name: 'mx_bilerp_0',
  26848. type: 'float',
  26849. inputs: [
  26850. { name: 'v0', type: 'float' },
  26851. { name: 'v1', type: 'float' },
  26852. { name: 'v2', type: 'float' },
  26853. { name: 'v3', type: 'float' },
  26854. { name: 's', type: 'float' },
  26855. { name: 't', type: 'float' }
  26856. ]
  26857. } );
  26858. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26859. const t = float( t_immutable ).toVar();
  26860. const s = float( s_immutable ).toVar();
  26861. const v3 = vec3( v3_immutable ).toVar();
  26862. const v2 = vec3( v2_immutable ).toVar();
  26863. const v1 = vec3( v1_immutable ).toVar();
  26864. const v0 = vec3( v0_immutable ).toVar();
  26865. const s1 = float( sub( 1.0, s ) ).toVar();
  26866. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26867. } ).setLayout( {
  26868. name: 'mx_bilerp_1',
  26869. type: 'vec3',
  26870. inputs: [
  26871. { name: 'v0', type: 'vec3' },
  26872. { name: 'v1', type: 'vec3' },
  26873. { name: 'v2', type: 'vec3' },
  26874. { name: 'v3', type: 'vec3' },
  26875. { name: 's', type: 'float' },
  26876. { name: 't', type: 'float' }
  26877. ]
  26878. } );
  26879. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26880. 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 ] ) => {
  26881. const r = float( r_immutable ).toVar();
  26882. const t = float( t_immutable ).toVar();
  26883. const s = float( s_immutable ).toVar();
  26884. const v7 = float( v7_immutable ).toVar();
  26885. const v6 = float( v6_immutable ).toVar();
  26886. const v5 = float( v5_immutable ).toVar();
  26887. const v4 = float( v4_immutable ).toVar();
  26888. const v3 = float( v3_immutable ).toVar();
  26889. const v2 = float( v2_immutable ).toVar();
  26890. const v1 = float( v1_immutable ).toVar();
  26891. const v0 = float( v0_immutable ).toVar();
  26892. const s1 = float( sub( 1.0, s ) ).toVar();
  26893. const t1 = float( sub( 1.0, t ) ).toVar();
  26894. const r1 = float( sub( 1.0, r ) ).toVar();
  26895. 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 ) ) ) ) ) );
  26896. } ).setLayout( {
  26897. name: 'mx_trilerp_0',
  26898. type: 'float',
  26899. inputs: [
  26900. { name: 'v0', type: 'float' },
  26901. { name: 'v1', type: 'float' },
  26902. { name: 'v2', type: 'float' },
  26903. { name: 'v3', type: 'float' },
  26904. { name: 'v4', type: 'float' },
  26905. { name: 'v5', type: 'float' },
  26906. { name: 'v6', type: 'float' },
  26907. { name: 'v7', type: 'float' },
  26908. { name: 's', type: 'float' },
  26909. { name: 't', type: 'float' },
  26910. { name: 'r', type: 'float' }
  26911. ]
  26912. } );
  26913. 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 ] ) => {
  26914. const r = float( r_immutable ).toVar();
  26915. const t = float( t_immutable ).toVar();
  26916. const s = float( s_immutable ).toVar();
  26917. const v7 = vec3( v7_immutable ).toVar();
  26918. const v6 = vec3( v6_immutable ).toVar();
  26919. const v5 = vec3( v5_immutable ).toVar();
  26920. const v4 = vec3( v4_immutable ).toVar();
  26921. const v3 = vec3( v3_immutable ).toVar();
  26922. const v2 = vec3( v2_immutable ).toVar();
  26923. const v1 = vec3( v1_immutable ).toVar();
  26924. const v0 = vec3( v0_immutable ).toVar();
  26925. const s1 = float( sub( 1.0, s ) ).toVar();
  26926. const t1 = float( sub( 1.0, t ) ).toVar();
  26927. const r1 = float( sub( 1.0, r ) ).toVar();
  26928. 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 ) ) ) ) ) );
  26929. } ).setLayout( {
  26930. name: 'mx_trilerp_1',
  26931. type: 'vec3',
  26932. inputs: [
  26933. { name: 'v0', type: 'vec3' },
  26934. { name: 'v1', type: 'vec3' },
  26935. { name: 'v2', type: 'vec3' },
  26936. { name: 'v3', type: 'vec3' },
  26937. { name: 'v4', type: 'vec3' },
  26938. { name: 'v5', type: 'vec3' },
  26939. { name: 'v6', type: 'vec3' },
  26940. { name: 'v7', type: 'vec3' },
  26941. { name: 's', type: 'float' },
  26942. { name: 't', type: 'float' },
  26943. { name: 'r', type: 'float' }
  26944. ]
  26945. } );
  26946. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26947. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26948. const y = float( y_immutable ).toVar();
  26949. const x = float( x_immutable ).toVar();
  26950. const hash = uint( hash_immutable ).toVar();
  26951. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26952. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26953. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26954. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26955. } ).setLayout( {
  26956. name: 'mx_gradient_float_0',
  26957. type: 'float',
  26958. inputs: [
  26959. { name: 'hash', type: 'uint' },
  26960. { name: 'x', type: 'float' },
  26961. { name: 'y', type: 'float' }
  26962. ]
  26963. } );
  26964. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26965. const z = float( z_immutable ).toVar();
  26966. const y = float( y_immutable ).toVar();
  26967. const x = float( x_immutable ).toVar();
  26968. const hash = uint( hash_immutable ).toVar();
  26969. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26970. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26971. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26972. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26973. } ).setLayout( {
  26974. name: 'mx_gradient_float_1',
  26975. type: 'float',
  26976. inputs: [
  26977. { name: 'hash', type: 'uint' },
  26978. { name: 'x', type: 'float' },
  26979. { name: 'y', type: 'float' },
  26980. { name: 'z', type: 'float' }
  26981. ]
  26982. } );
  26983. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26984. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26985. const y = float( y_immutable ).toVar();
  26986. const x = float( x_immutable ).toVar();
  26987. const hash = uvec3( hash_immutable ).toVar();
  26988. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26989. } ).setLayout( {
  26990. name: 'mx_gradient_vec3_0',
  26991. type: 'vec3',
  26992. inputs: [
  26993. { name: 'hash', type: 'uvec3' },
  26994. { name: 'x', type: 'float' },
  26995. { name: 'y', type: 'float' }
  26996. ]
  26997. } );
  26998. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26999. const z = float( z_immutable ).toVar();
  27000. const y = float( y_immutable ).toVar();
  27001. const x = float( x_immutable ).toVar();
  27002. const hash = uvec3( hash_immutable ).toVar();
  27003. 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 ) );
  27004. } ).setLayout( {
  27005. name: 'mx_gradient_vec3_1',
  27006. type: 'vec3',
  27007. inputs: [
  27008. { name: 'hash', type: 'uvec3' },
  27009. { name: 'x', type: 'float' },
  27010. { name: 'y', type: 'float' },
  27011. { name: 'z', type: 'float' }
  27012. ]
  27013. } );
  27014. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  27015. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27016. const v = float( v_immutable ).toVar();
  27017. return mul( 0.6616, v );
  27018. } ).setLayout( {
  27019. name: 'mx_gradient_scale2d_0',
  27020. type: 'float',
  27021. inputs: [
  27022. { name: 'v', type: 'float' }
  27023. ]
  27024. } );
  27025. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27026. const v = float( v_immutable ).toVar();
  27027. return mul( 0.9820, v );
  27028. } ).setLayout( {
  27029. name: 'mx_gradient_scale3d_0',
  27030. type: 'float',
  27031. inputs: [
  27032. { name: 'v', type: 'float' }
  27033. ]
  27034. } );
  27035. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27036. const v = vec3( v_immutable ).toVar();
  27037. return mul( 0.6616, v );
  27038. } ).setLayout( {
  27039. name: 'mx_gradient_scale2d_1',
  27040. type: 'vec3',
  27041. inputs: [
  27042. { name: 'v', type: 'vec3' }
  27043. ]
  27044. } );
  27045. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  27046. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27047. const v = vec3( v_immutable ).toVar();
  27048. return mul( 0.9820, v );
  27049. } ).setLayout( {
  27050. name: 'mx_gradient_scale3d_1',
  27051. type: 'vec3',
  27052. inputs: [
  27053. { name: 'v', type: 'vec3' }
  27054. ]
  27055. } );
  27056. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  27057. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  27058. const k = int( k_immutable ).toVar();
  27059. const x = uint( x_immutable ).toVar();
  27060. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  27061. } ).setLayout( {
  27062. name: 'mx_rotl32',
  27063. type: 'uint',
  27064. inputs: [
  27065. { name: 'x', type: 'uint' },
  27066. { name: 'k', type: 'int' }
  27067. ]
  27068. } );
  27069. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  27070. a.subAssign( c );
  27071. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  27072. c.addAssign( b );
  27073. b.subAssign( a );
  27074. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  27075. a.addAssign( c );
  27076. c.subAssign( b );
  27077. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  27078. b.addAssign( a );
  27079. a.subAssign( c );
  27080. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  27081. c.addAssign( b );
  27082. b.subAssign( a );
  27083. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  27084. a.addAssign( c );
  27085. c.subAssign( b );
  27086. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  27087. b.addAssign( a );
  27088. } );
  27089. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  27090. const c = uint( c_immutable ).toVar();
  27091. const b = uint( b_immutable ).toVar();
  27092. const a = uint( a_immutable ).toVar();
  27093. c.bitXorAssign( b );
  27094. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  27095. a.bitXorAssign( c );
  27096. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  27097. b.bitXorAssign( a );
  27098. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  27099. c.bitXorAssign( b );
  27100. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  27101. a.bitXorAssign( c );
  27102. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  27103. b.bitXorAssign( a );
  27104. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  27105. c.bitXorAssign( b );
  27106. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  27107. return c;
  27108. } ).setLayout( {
  27109. name: 'mx_bjfinal',
  27110. type: 'uint',
  27111. inputs: [
  27112. { name: 'a', type: 'uint' },
  27113. { name: 'b', type: 'uint' },
  27114. { name: 'c', type: 'uint' }
  27115. ]
  27116. } );
  27117. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  27118. const bits = uint( bits_immutable ).toVar();
  27119. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  27120. } ).setLayout( {
  27121. name: 'mx_bits_to_01',
  27122. type: 'float',
  27123. inputs: [
  27124. { name: 'bits', type: 'uint' }
  27125. ]
  27126. } );
  27127. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  27128. const t = float( t_immutable ).toVar();
  27129. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  27130. } ).setLayout( {
  27131. name: 'mx_fade',
  27132. type: 'float',
  27133. inputs: [
  27134. { name: 't', type: 'float' }
  27135. ]
  27136. } );
  27137. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27138. const x = int( x_immutable ).toVar();
  27139. const len = uint( uint( 1 ) ).toVar();
  27140. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  27141. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  27142. } ).setLayout( {
  27143. name: 'mx_hash_int_0',
  27144. type: 'uint',
  27145. inputs: [
  27146. { name: 'x', type: 'int' }
  27147. ]
  27148. } );
  27149. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  27150. const y = int( y_immutable ).toVar();
  27151. const x = int( x_immutable ).toVar();
  27152. const len = uint( uint( 2 ) ).toVar();
  27153. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27154. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27155. a.addAssign( uint( x ) );
  27156. b.addAssign( uint( y ) );
  27157. return mx_bjfinal( a, b, c );
  27158. } ).setLayout( {
  27159. name: 'mx_hash_int_1',
  27160. type: 'uint',
  27161. inputs: [
  27162. { name: 'x', type: 'int' },
  27163. { name: 'y', type: 'int' }
  27164. ]
  27165. } );
  27166. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  27167. const z = int( z_immutable ).toVar();
  27168. const y = int( y_immutable ).toVar();
  27169. const x = int( x_immutable ).toVar();
  27170. const len = uint( uint( 3 ) ).toVar();
  27171. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27172. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27173. a.addAssign( uint( x ) );
  27174. b.addAssign( uint( y ) );
  27175. c.addAssign( uint( z ) );
  27176. return mx_bjfinal( a, b, c );
  27177. } ).setLayout( {
  27178. name: 'mx_hash_int_2',
  27179. type: 'uint',
  27180. inputs: [
  27181. { name: 'x', type: 'int' },
  27182. { name: 'y', type: 'int' },
  27183. { name: 'z', type: 'int' }
  27184. ]
  27185. } );
  27186. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  27187. const xx = int( xx_immutable ).toVar();
  27188. const z = int( z_immutable ).toVar();
  27189. const y = int( y_immutable ).toVar();
  27190. const x = int( x_immutable ).toVar();
  27191. const len = uint( uint( 4 ) ).toVar();
  27192. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27193. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27194. a.addAssign( uint( x ) );
  27195. b.addAssign( uint( y ) );
  27196. c.addAssign( uint( z ) );
  27197. mx_bjmix( a, b, c );
  27198. a.addAssign( uint( xx ) );
  27199. return mx_bjfinal( a, b, c );
  27200. } ).setLayout( {
  27201. name: 'mx_hash_int_3',
  27202. type: 'uint',
  27203. inputs: [
  27204. { name: 'x', type: 'int' },
  27205. { name: 'y', type: 'int' },
  27206. { name: 'z', type: 'int' },
  27207. { name: 'xx', type: 'int' }
  27208. ]
  27209. } );
  27210. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  27211. const yy = int( yy_immutable ).toVar();
  27212. const xx = int( xx_immutable ).toVar();
  27213. const z = int( z_immutable ).toVar();
  27214. const y = int( y_immutable ).toVar();
  27215. const x = int( x_immutable ).toVar();
  27216. const len = uint( uint( 5 ) ).toVar();
  27217. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27218. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27219. a.addAssign( uint( x ) );
  27220. b.addAssign( uint( y ) );
  27221. c.addAssign( uint( z ) );
  27222. mx_bjmix( a, b, c );
  27223. a.addAssign( uint( xx ) );
  27224. b.addAssign( uint( yy ) );
  27225. return mx_bjfinal( a, b, c );
  27226. } ).setLayout( {
  27227. name: 'mx_hash_int_4',
  27228. type: 'uint',
  27229. inputs: [
  27230. { name: 'x', type: 'int' },
  27231. { name: 'y', type: 'int' },
  27232. { name: 'z', type: 'int' },
  27233. { name: 'xx', type: 'int' },
  27234. { name: 'yy', type: 'int' }
  27235. ]
  27236. } );
  27237. 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 ] );
  27238. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  27239. const y = int( y_immutable ).toVar();
  27240. const x = int( x_immutable ).toVar();
  27241. const h = uint( mx_hash_int( x, y ) ).toVar();
  27242. const result = uvec3().toVar();
  27243. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  27244. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  27245. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  27246. return result;
  27247. } ).setLayout( {
  27248. name: 'mx_hash_vec3_0',
  27249. type: 'uvec3',
  27250. inputs: [
  27251. { name: 'x', type: 'int' },
  27252. { name: 'y', type: 'int' }
  27253. ]
  27254. } );
  27255. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  27256. const z = int( z_immutable ).toVar();
  27257. const y = int( y_immutable ).toVar();
  27258. const x = int( x_immutable ).toVar();
  27259. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  27260. const result = uvec3().toVar();
  27261. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  27262. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  27263. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  27264. return result;
  27265. } ).setLayout( {
  27266. name: 'mx_hash_vec3_1',
  27267. type: 'uvec3',
  27268. inputs: [
  27269. { name: 'x', type: 'int' },
  27270. { name: 'y', type: 'int' },
  27271. { name: 'z', type: 'int' }
  27272. ]
  27273. } );
  27274. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  27275. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27276. const p = vec2( p_immutable ).toVar();
  27277. const X = int().toVar(), Y = int().toVar();
  27278. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27279. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27280. const u = float( mx_fade( fx ) ).toVar();
  27281. const v = float( mx_fade( fy ) ).toVar();
  27282. 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();
  27283. return mx_gradient_scale2d( result );
  27284. } ).setLayout( {
  27285. name: 'mx_perlin_noise_float_0',
  27286. type: 'float',
  27287. inputs: [
  27288. { name: 'p', type: 'vec2' }
  27289. ]
  27290. } );
  27291. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27292. const p = vec3( p_immutable ).toVar();
  27293. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27294. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27295. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27296. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  27297. const u = float( mx_fade( fx ) ).toVar();
  27298. const v = float( mx_fade( fy ) ).toVar();
  27299. const w = float( mx_fade( fz ) ).toVar();
  27300. 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();
  27301. return mx_gradient_scale3d( result );
  27302. } ).setLayout( {
  27303. name: 'mx_perlin_noise_float_1',
  27304. type: 'float',
  27305. inputs: [
  27306. { name: 'p', type: 'vec3' }
  27307. ]
  27308. } );
  27309. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  27310. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27311. const p = vec2( p_immutable ).toVar();
  27312. const X = int().toVar(), Y = int().toVar();
  27313. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27314. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27315. const u = float( mx_fade( fx ) ).toVar();
  27316. const v = float( mx_fade( fy ) ).toVar();
  27317. 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();
  27318. return mx_gradient_scale2d( result );
  27319. } ).setLayout( {
  27320. name: 'mx_perlin_noise_vec3_0',
  27321. type: 'vec3',
  27322. inputs: [
  27323. { name: 'p', type: 'vec2' }
  27324. ]
  27325. } );
  27326. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27327. const p = vec3( p_immutable ).toVar();
  27328. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27329. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27330. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27331. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  27332. const u = float( mx_fade( fx ) ).toVar();
  27333. const v = float( mx_fade( fy ) ).toVar();
  27334. const w = float( mx_fade( fz ) ).toVar();
  27335. 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();
  27336. return mx_gradient_scale3d( result );
  27337. } ).setLayout( {
  27338. name: 'mx_perlin_noise_vec3_1',
  27339. type: 'vec3',
  27340. inputs: [
  27341. { name: 'p', type: 'vec3' }
  27342. ]
  27343. } );
  27344. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  27345. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27346. const p = float( p_immutable ).toVar();
  27347. const ix = int( mx_floor( p ) ).toVar();
  27348. return mx_bits_to_01( mx_hash_int( ix ) );
  27349. } ).setLayout( {
  27350. name: 'mx_cell_noise_float_0',
  27351. type: 'float',
  27352. inputs: [
  27353. { name: 'p', type: 'float' }
  27354. ]
  27355. } );
  27356. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27357. const p = vec2( p_immutable ).toVar();
  27358. const ix = int( mx_floor( p.x ) ).toVar();
  27359. const iy = int( mx_floor( p.y ) ).toVar();
  27360. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  27361. } ).setLayout( {
  27362. name: 'mx_cell_noise_float_1',
  27363. type: 'float',
  27364. inputs: [
  27365. { name: 'p', type: 'vec2' }
  27366. ]
  27367. } );
  27368. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27369. const p = vec3( p_immutable ).toVar();
  27370. const ix = int( mx_floor( p.x ) ).toVar();
  27371. const iy = int( mx_floor( p.y ) ).toVar();
  27372. const iz = int( mx_floor( p.z ) ).toVar();
  27373. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  27374. } ).setLayout( {
  27375. name: 'mx_cell_noise_float_2',
  27376. type: 'float',
  27377. inputs: [
  27378. { name: 'p', type: 'vec3' }
  27379. ]
  27380. } );
  27381. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27382. const p = vec4( p_immutable ).toVar();
  27383. const ix = int( mx_floor( p.x ) ).toVar();
  27384. const iy = int( mx_floor( p.y ) ).toVar();
  27385. const iz = int( mx_floor( p.z ) ).toVar();
  27386. const iw = int( mx_floor( p.w ) ).toVar();
  27387. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  27388. } ).setLayout( {
  27389. name: 'mx_cell_noise_float_3',
  27390. type: 'float',
  27391. inputs: [
  27392. { name: 'p', type: 'vec4' }
  27393. ]
  27394. } );
  27395. 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 ] );
  27396. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27397. const p = float( p_immutable ).toVar();
  27398. const ix = int( mx_floor( p ) ).toVar();
  27399. 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 ) ) ) );
  27400. } ).setLayout( {
  27401. name: 'mx_cell_noise_vec3_0',
  27402. type: 'vec3',
  27403. inputs: [
  27404. { name: 'p', type: 'float' }
  27405. ]
  27406. } );
  27407. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27408. const p = vec2( p_immutable ).toVar();
  27409. const ix = int( mx_floor( p.x ) ).toVar();
  27410. const iy = int( mx_floor( p.y ) ).toVar();
  27411. 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 ) ) ) );
  27412. } ).setLayout( {
  27413. name: 'mx_cell_noise_vec3_1',
  27414. type: 'vec3',
  27415. inputs: [
  27416. { name: 'p', type: 'vec2' }
  27417. ]
  27418. } );
  27419. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27420. const p = vec3( p_immutable ).toVar();
  27421. const ix = int( mx_floor( p.x ) ).toVar();
  27422. const iy = int( mx_floor( p.y ) ).toVar();
  27423. const iz = int( mx_floor( p.z ) ).toVar();
  27424. 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 ) ) ) );
  27425. } ).setLayout( {
  27426. name: 'mx_cell_noise_vec3_2',
  27427. type: 'vec3',
  27428. inputs: [
  27429. { name: 'p', type: 'vec3' }
  27430. ]
  27431. } );
  27432. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27433. const p = vec4( p_immutable ).toVar();
  27434. const ix = int( mx_floor( p.x ) ).toVar();
  27435. const iy = int( mx_floor( p.y ) ).toVar();
  27436. const iz = int( mx_floor( p.z ) ).toVar();
  27437. const iw = int( mx_floor( p.w ) ).toVar();
  27438. 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 ) ) ) );
  27439. } ).setLayout( {
  27440. name: 'mx_cell_noise_vec3_3',
  27441. type: 'vec3',
  27442. inputs: [
  27443. { name: 'p', type: 'vec4' }
  27444. ]
  27445. } );
  27446. 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 ] );
  27447. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27448. const diminish = float( diminish_immutable ).toVar();
  27449. const lacunarity = float( lacunarity_immutable ).toVar();
  27450. const octaves = int( octaves_immutable ).toVar();
  27451. const p = vec3( p_immutable ).toVar();
  27452. const result = float( 0.0 ).toVar();
  27453. const amplitude = float( 1.0 ).toVar();
  27454. Loop( octaves, () => {
  27455. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  27456. amplitude.mulAssign( diminish );
  27457. p.mulAssign( lacunarity );
  27458. } );
  27459. return result;
  27460. } ).setLayout( {
  27461. name: 'mx_fractal_noise_float',
  27462. type: 'float',
  27463. inputs: [
  27464. { name: 'p', type: 'vec3' },
  27465. { name: 'octaves', type: 'int' },
  27466. { name: 'lacunarity', type: 'float' },
  27467. { name: 'diminish', type: 'float' }
  27468. ]
  27469. } );
  27470. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27471. const diminish = float( diminish_immutable ).toVar();
  27472. const lacunarity = float( lacunarity_immutable ).toVar();
  27473. const octaves = int( octaves_immutable ).toVar();
  27474. const p = vec3( p_immutable ).toVar();
  27475. const result = vec3( 0.0 ).toVar();
  27476. const amplitude = float( 1.0 ).toVar();
  27477. Loop( octaves, () => {
  27478. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  27479. amplitude.mulAssign( diminish );
  27480. p.mulAssign( lacunarity );
  27481. } );
  27482. return result;
  27483. } ).setLayout( {
  27484. name: 'mx_fractal_noise_vec3',
  27485. type: 'vec3',
  27486. inputs: [
  27487. { name: 'p', type: 'vec3' },
  27488. { name: 'octaves', type: 'int' },
  27489. { name: 'lacunarity', type: 'float' },
  27490. { name: 'diminish', type: 'float' }
  27491. ]
  27492. } );
  27493. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27494. const diminish = float( diminish_immutable ).toVar();
  27495. const lacunarity = float( lacunarity_immutable ).toVar();
  27496. const octaves = int( octaves_immutable ).toVar();
  27497. const p = vec3( p_immutable ).toVar();
  27498. 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 ) );
  27499. } ).setLayout( {
  27500. name: 'mx_fractal_noise_vec2',
  27501. type: 'vec2',
  27502. inputs: [
  27503. { name: 'p', type: 'vec3' },
  27504. { name: 'octaves', type: 'int' },
  27505. { name: 'lacunarity', type: 'float' },
  27506. { name: 'diminish', type: 'float' }
  27507. ]
  27508. } );
  27509. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27510. const diminish = float( diminish_immutable ).toVar();
  27511. const lacunarity = float( lacunarity_immutable ).toVar();
  27512. const octaves = int( octaves_immutable ).toVar();
  27513. const p = vec3( p_immutable ).toVar();
  27514. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  27515. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  27516. return vec4( c, f );
  27517. } ).setLayout( {
  27518. name: 'mx_fractal_noise_vec4',
  27519. type: 'vec4',
  27520. inputs: [
  27521. { name: 'p', type: 'vec3' },
  27522. { name: 'octaves', type: 'int' },
  27523. { name: 'lacunarity', type: 'float' },
  27524. { name: 'diminish', type: 'float' }
  27525. ]
  27526. } );
  27527. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  27528. const metric = int( metric_immutable ).toVar();
  27529. const jitter = float( jitter_immutable ).toVar();
  27530. const yoff = int( yoff_immutable ).toVar();
  27531. const xoff = int( xoff_immutable ).toVar();
  27532. const y = int( y_immutable ).toVar();
  27533. const x = int( x_immutable ).toVar();
  27534. const p = vec2( p_immutable ).toVar();
  27535. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  27536. const off = vec2( tmp.x, tmp.y ).toVar();
  27537. off.subAssign( 0.5 );
  27538. off.mulAssign( jitter );
  27539. off.addAssign( 0.5 );
  27540. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  27541. const diff = vec2( cellpos.sub( p ) ).toVar();
  27542. If( metric.equal( int( 2 ) ), () => {
  27543. return abs( diff.x ).add( abs( diff.y ) );
  27544. } );
  27545. If( metric.equal( int( 3 ) ), () => {
  27546. return max$1( abs( diff.x ), abs( diff.y ) );
  27547. } );
  27548. return dot( diff, diff );
  27549. } ).setLayout( {
  27550. name: 'mx_worley_distance_0',
  27551. type: 'float',
  27552. inputs: [
  27553. { name: 'p', type: 'vec2' },
  27554. { name: 'x', type: 'int' },
  27555. { name: 'y', type: 'int' },
  27556. { name: 'xoff', type: 'int' },
  27557. { name: 'yoff', type: 'int' },
  27558. { name: 'jitter', type: 'float' },
  27559. { name: 'metric', type: 'int' }
  27560. ]
  27561. } );
  27562. 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 ] ) => {
  27563. const metric = int( metric_immutable ).toVar();
  27564. const jitter = float( jitter_immutable ).toVar();
  27565. const zoff = int( zoff_immutable ).toVar();
  27566. const yoff = int( yoff_immutable ).toVar();
  27567. const xoff = int( xoff_immutable ).toVar();
  27568. const z = int( z_immutable ).toVar();
  27569. const y = int( y_immutable ).toVar();
  27570. const x = int( x_immutable ).toVar();
  27571. const p = vec3( p_immutable ).toVar();
  27572. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  27573. off.subAssign( 0.5 );
  27574. off.mulAssign( jitter );
  27575. off.addAssign( 0.5 );
  27576. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  27577. const diff = vec3( cellpos.sub( p ) ).toVar();
  27578. If( metric.equal( int( 2 ) ), () => {
  27579. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  27580. } );
  27581. If( metric.equal( int( 3 ) ), () => {
  27582. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  27583. } );
  27584. return dot( diff, diff );
  27585. } ).setLayout( {
  27586. name: 'mx_worley_distance_1',
  27587. type: 'float',
  27588. inputs: [
  27589. { name: 'p', type: 'vec3' },
  27590. { name: 'x', type: 'int' },
  27591. { name: 'y', type: 'int' },
  27592. { name: 'z', type: 'int' },
  27593. { name: 'xoff', type: 'int' },
  27594. { name: 'yoff', type: 'int' },
  27595. { name: 'zoff', type: 'int' },
  27596. { name: 'jitter', type: 'float' },
  27597. { name: 'metric', type: 'int' }
  27598. ]
  27599. } );
  27600. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  27601. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27602. const metric = int( metric_immutable ).toVar();
  27603. const jitter = float( jitter_immutable ).toVar();
  27604. const p = vec2( p_immutable ).toVar();
  27605. const X = int().toVar(), Y = int().toVar();
  27606. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27607. const sqdist = float( 1e6 ).toVar();
  27608. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27609. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27610. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27611. sqdist.assign( min$1( sqdist, dist ) );
  27612. } );
  27613. } );
  27614. If( metric.equal( int( 0 ) ), () => {
  27615. sqdist.assign( sqrt( sqdist ) );
  27616. } );
  27617. return sqdist;
  27618. } ).setLayout( {
  27619. name: 'mx_worley_noise_float_0',
  27620. type: 'float',
  27621. inputs: [
  27622. { name: 'p', type: 'vec2' },
  27623. { name: 'jitter', type: 'float' },
  27624. { name: 'metric', type: 'int' }
  27625. ]
  27626. } );
  27627. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27628. const metric = int( metric_immutable ).toVar();
  27629. const jitter = float( jitter_immutable ).toVar();
  27630. const p = vec2( p_immutable ).toVar();
  27631. const X = int().toVar(), Y = int().toVar();
  27632. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27633. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27634. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27635. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27636. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27637. If( dist.lessThan( sqdist.x ), () => {
  27638. sqdist.y.assign( sqdist.x );
  27639. sqdist.x.assign( dist );
  27640. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27641. sqdist.y.assign( dist );
  27642. } );
  27643. } );
  27644. } );
  27645. If( metric.equal( int( 0 ) ), () => {
  27646. sqdist.assign( sqrt( sqdist ) );
  27647. } );
  27648. return sqdist;
  27649. } ).setLayout( {
  27650. name: 'mx_worley_noise_vec2_0',
  27651. type: 'vec2',
  27652. inputs: [
  27653. { name: 'p', type: 'vec2' },
  27654. { name: 'jitter', type: 'float' },
  27655. { name: 'metric', type: 'int' }
  27656. ]
  27657. } );
  27658. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27659. const metric = int( metric_immutable ).toVar();
  27660. const jitter = float( jitter_immutable ).toVar();
  27661. const p = vec2( p_immutable ).toVar();
  27662. const X = int().toVar(), Y = int().toVar();
  27663. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27664. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27665. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27666. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27667. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27668. If( dist.lessThan( sqdist.x ), () => {
  27669. sqdist.z.assign( sqdist.y );
  27670. sqdist.y.assign( sqdist.x );
  27671. sqdist.x.assign( dist );
  27672. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27673. sqdist.z.assign( sqdist.y );
  27674. sqdist.y.assign( dist );
  27675. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27676. sqdist.z.assign( dist );
  27677. } );
  27678. } );
  27679. } );
  27680. If( metric.equal( int( 0 ) ), () => {
  27681. sqdist.assign( sqrt( sqdist ) );
  27682. } );
  27683. return sqdist;
  27684. } ).setLayout( {
  27685. name: 'mx_worley_noise_vec3_0',
  27686. type: 'vec3',
  27687. inputs: [
  27688. { name: 'p', type: 'vec2' },
  27689. { name: 'jitter', type: 'float' },
  27690. { name: 'metric', type: 'int' }
  27691. ]
  27692. } );
  27693. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27694. const metric = int( metric_immutable ).toVar();
  27695. const jitter = float( jitter_immutable ).toVar();
  27696. const p = vec3( p_immutable ).toVar();
  27697. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27698. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27699. const sqdist = float( 1e6 ).toVar();
  27700. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27701. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27702. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27703. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27704. sqdist.assign( min$1( sqdist, dist ) );
  27705. } );
  27706. } );
  27707. } );
  27708. If( metric.equal( int( 0 ) ), () => {
  27709. sqdist.assign( sqrt( sqdist ) );
  27710. } );
  27711. return sqdist;
  27712. } ).setLayout( {
  27713. name: 'mx_worley_noise_float_1',
  27714. type: 'float',
  27715. inputs: [
  27716. { name: 'p', type: 'vec3' },
  27717. { name: 'jitter', type: 'float' },
  27718. { name: 'metric', type: 'int' }
  27719. ]
  27720. } );
  27721. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27722. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27723. const metric = int( metric_immutable ).toVar();
  27724. const jitter = float( jitter_immutable ).toVar();
  27725. const p = vec3( p_immutable ).toVar();
  27726. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27727. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27728. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27729. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27730. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27731. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27732. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27733. If( dist.lessThan( sqdist.x ), () => {
  27734. sqdist.y.assign( sqdist.x );
  27735. sqdist.x.assign( dist );
  27736. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27737. sqdist.y.assign( dist );
  27738. } );
  27739. } );
  27740. } );
  27741. } );
  27742. If( metric.equal( int( 0 ) ), () => {
  27743. sqdist.assign( sqrt( sqdist ) );
  27744. } );
  27745. return sqdist;
  27746. } ).setLayout( {
  27747. name: 'mx_worley_noise_vec2_1',
  27748. type: 'vec2',
  27749. inputs: [
  27750. { name: 'p', type: 'vec3' },
  27751. { name: 'jitter', type: 'float' },
  27752. { name: 'metric', type: 'int' }
  27753. ]
  27754. } );
  27755. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27756. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27757. const metric = int( metric_immutable ).toVar();
  27758. const jitter = float( jitter_immutable ).toVar();
  27759. const p = vec3( p_immutable ).toVar();
  27760. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27761. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27762. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27763. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27764. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27765. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27766. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27767. If( dist.lessThan( sqdist.x ), () => {
  27768. sqdist.z.assign( sqdist.y );
  27769. sqdist.y.assign( sqdist.x );
  27770. sqdist.x.assign( dist );
  27771. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27772. sqdist.z.assign( sqdist.y );
  27773. sqdist.y.assign( dist );
  27774. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27775. sqdist.z.assign( dist );
  27776. } );
  27777. } );
  27778. } );
  27779. } );
  27780. If( metric.equal( int( 0 ) ), () => {
  27781. sqdist.assign( sqrt( sqdist ) );
  27782. } );
  27783. return sqdist;
  27784. } ).setLayout( {
  27785. name: 'mx_worley_noise_vec3_1',
  27786. type: 'vec3',
  27787. inputs: [
  27788. { name: 'p', type: 'vec3' },
  27789. { name: 'jitter', type: 'float' },
  27790. { name: 'metric', type: 'int' }
  27791. ]
  27792. } );
  27793. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27794. // Three.js Transpiler
  27795. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27796. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27797. const s = hsv.y;
  27798. const v = hsv.z;
  27799. const result = vec3().toVar();
  27800. If( s.lessThan( 0.0001 ), () => {
  27801. result.assign( vec3( v, v, v ) );
  27802. } ).Else( () => {
  27803. let h = hsv.x;
  27804. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27805. const hi = int( trunc( h ) );
  27806. const f = h.sub( float( hi ) );
  27807. const p = v.mul( s.oneMinus() );
  27808. const q = v.mul( s.mul( f ).oneMinus() );
  27809. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27810. If( hi.equal( int( 0 ) ), () => {
  27811. result.assign( vec3( v, t, p ) );
  27812. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27813. result.assign( vec3( q, v, p ) );
  27814. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27815. result.assign( vec3( p, v, t ) );
  27816. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27817. result.assign( vec3( p, q, v ) );
  27818. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27819. result.assign( vec3( t, p, v ) );
  27820. } ).Else( () => {
  27821. result.assign( vec3( v, p, q ) );
  27822. } );
  27823. } );
  27824. return result;
  27825. } ).setLayout( {
  27826. name: 'mx_hsvtorgb',
  27827. type: 'vec3',
  27828. inputs: [
  27829. { name: 'hsv', type: 'vec3' }
  27830. ]
  27831. } );
  27832. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27833. const c = vec3( c_immutable ).toVar();
  27834. const r = float( c.x ).toVar();
  27835. const g = float( c.y ).toVar();
  27836. const b = float( c.z ).toVar();
  27837. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27838. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27839. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27840. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27841. v.assign( maxcomp );
  27842. If( maxcomp.greaterThan( 0.0 ), () => {
  27843. s.assign( delta.div( maxcomp ) );
  27844. } ).Else( () => {
  27845. s.assign( 0.0 );
  27846. } );
  27847. If( s.lessThanEqual( 0.0 ), () => {
  27848. h.assign( 0.0 );
  27849. } ).Else( () => {
  27850. If( r.greaterThanEqual( maxcomp ), () => {
  27851. h.assign( g.sub( b ).div( delta ) );
  27852. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27853. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27854. } ).Else( () => {
  27855. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27856. } );
  27857. h.mulAssign( 1.0 / 6.0 );
  27858. If( h.lessThan( 0.0 ), () => {
  27859. h.addAssign( 1.0 );
  27860. } );
  27861. } );
  27862. return vec3( h, s, v );
  27863. } ).setLayout( {
  27864. name: 'mx_rgbtohsv',
  27865. type: 'vec3',
  27866. inputs: [
  27867. { name: 'c', type: 'vec3' }
  27868. ]
  27869. } );
  27870. // Three.js Transpiler
  27871. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27872. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27873. const color = vec3( color_immutable ).toVar();
  27874. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27875. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27876. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27877. return mix( linSeg, powSeg, isAbove );
  27878. } ).setLayout( {
  27879. name: 'mx_srgb_texture_to_lin_rec709',
  27880. type: 'vec3',
  27881. inputs: [
  27882. { name: 'color', type: 'vec3' }
  27883. ]
  27884. } );
  27885. const mx_aastep = ( threshold, value ) => {
  27886. threshold = float( threshold );
  27887. value = float( value );
  27888. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27889. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27890. };
  27891. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27892. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27893. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27894. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27895. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27896. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27897. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27898. const mx_safepower = ( in1, in2 = 1 ) => {
  27899. in1 = float( in1 );
  27900. return in1.abs().pow( in2 ).mul( in1.sign() );
  27901. };
  27902. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27903. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27904. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27905. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27906. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27907. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27908. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27909. return noise_vec4.mul( amplitude ).add( pivot );
  27910. };
  27911. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27912. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27913. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27914. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27915. 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 );
  27916. 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 );
  27917. 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 );
  27918. 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 );
  27919. /**
  27920. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27921. *
  27922. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27923. *
  27924. * ```js
  27925. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27926. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27927. * ```
  27928. *
  27929. * @tsl
  27930. * @function
  27931. * @param {Node<vec3>} normal - The normal to correct.
  27932. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27933. * @param {Node<vec3>} cubePos - The cube position.
  27934. * @return {Node<vec3>} The parallax corrected normal.
  27935. */
  27936. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27937. const nDir = normalize( normal ).toVar( 'nDir' );
  27938. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27939. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27940. const rbminmax = vec3().toVar( 'rbminmax' );
  27941. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27942. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27943. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27944. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27945. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27946. return boxIntersection.sub( cubePos );
  27947. } );
  27948. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27949. // normal is assumed to have unit length
  27950. const x = normal.x, y = normal.y, z = normal.z;
  27951. // band 0
  27952. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27953. // band 1
  27954. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27955. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27956. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27957. // band 2
  27958. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27959. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27960. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27961. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27962. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27963. return result;
  27964. } );
  27965. // constants
  27966. var TSL = /*#__PURE__*/Object.freeze({
  27967. __proto__: null,
  27968. BRDF_GGX: BRDF_GGX,
  27969. BRDF_Lambert: BRDF_Lambert,
  27970. BasicShadowFilter: BasicShadowFilter,
  27971. Break: Break,
  27972. Const: Const,
  27973. Continue: Continue,
  27974. DFGApprox: DFGApprox,
  27975. D_GGX: D_GGX,
  27976. Discard: Discard,
  27977. EPSILON: EPSILON,
  27978. F_Schlick: F_Schlick,
  27979. Fn: Fn,
  27980. INFINITY: INFINITY,
  27981. If: If,
  27982. Loop: Loop,
  27983. NodeAccess: NodeAccess,
  27984. NodeShaderStage: NodeShaderStage,
  27985. NodeType: NodeType,
  27986. NodeUpdateType: NodeUpdateType,
  27987. PCFShadowFilter: PCFShadowFilter,
  27988. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27989. PI: PI,
  27990. PI2: PI2,
  27991. Return: Return,
  27992. Schlick_to_F0: Schlick_to_F0,
  27993. ScriptableNodeResources: ScriptableNodeResources,
  27994. ShaderNode: ShaderNode,
  27995. TBNViewMatrix: TBNViewMatrix,
  27996. VSMShadowFilter: VSMShadowFilter,
  27997. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27998. Var: Var,
  27999. abs: abs,
  28000. acesFilmicToneMapping: acesFilmicToneMapping,
  28001. acos: acos,
  28002. add: add,
  28003. addMethodChaining: addMethodChaining,
  28004. addNodeElement: addNodeElement,
  28005. agxToneMapping: agxToneMapping,
  28006. all: all,
  28007. alphaT: alphaT,
  28008. and: and,
  28009. anisotropy: anisotropy,
  28010. anisotropyB: anisotropyB,
  28011. anisotropyT: anisotropyT,
  28012. any: any,
  28013. append: append,
  28014. array: array,
  28015. arrayBuffer: arrayBuffer,
  28016. asin: asin,
  28017. assign: assign,
  28018. atan: atan,
  28019. atan2: atan2,
  28020. atomicAdd: atomicAdd,
  28021. atomicAnd: atomicAnd,
  28022. atomicFunc: atomicFunc,
  28023. atomicLoad: atomicLoad,
  28024. atomicMax: atomicMax,
  28025. atomicMin: atomicMin,
  28026. atomicOr: atomicOr,
  28027. atomicStore: atomicStore,
  28028. atomicSub: atomicSub,
  28029. atomicXor: atomicXor,
  28030. attenuationColor: attenuationColor,
  28031. attenuationDistance: attenuationDistance,
  28032. attribute: attribute,
  28033. attributeArray: attributeArray,
  28034. backgroundBlurriness: backgroundBlurriness,
  28035. backgroundIntensity: backgroundIntensity,
  28036. backgroundRotation: backgroundRotation,
  28037. batch: batch,
  28038. billboarding: billboarding,
  28039. bitAnd: bitAnd,
  28040. bitNot: bitNot,
  28041. bitOr: bitOr,
  28042. bitXor: bitXor,
  28043. bitangentGeometry: bitangentGeometry,
  28044. bitangentLocal: bitangentLocal,
  28045. bitangentView: bitangentView,
  28046. bitangentWorld: bitangentWorld,
  28047. bitcast: bitcast,
  28048. blendBurn: blendBurn,
  28049. blendColor: blendColor,
  28050. blendDodge: blendDodge,
  28051. blendOverlay: blendOverlay,
  28052. blendScreen: blendScreen,
  28053. blur: blur,
  28054. bool: bool,
  28055. buffer: buffer,
  28056. bufferAttribute: bufferAttribute,
  28057. bumpMap: bumpMap,
  28058. burn: burn,
  28059. bvec2: bvec2,
  28060. bvec3: bvec3,
  28061. bvec4: bvec4,
  28062. bypass: bypass,
  28063. cache: cache,
  28064. call: call,
  28065. cameraFar: cameraFar,
  28066. cameraIndex: cameraIndex,
  28067. cameraNear: cameraNear,
  28068. cameraNormalMatrix: cameraNormalMatrix,
  28069. cameraPosition: cameraPosition,
  28070. cameraProjectionMatrix: cameraProjectionMatrix,
  28071. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  28072. cameraViewMatrix: cameraViewMatrix,
  28073. cameraWorldMatrix: cameraWorldMatrix,
  28074. cbrt: cbrt,
  28075. cdl: cdl,
  28076. ceil: ceil,
  28077. checker: checker,
  28078. cineonToneMapping: cineonToneMapping,
  28079. clamp: clamp,
  28080. clearcoat: clearcoat,
  28081. clearcoatRoughness: clearcoatRoughness,
  28082. code: code,
  28083. color: color,
  28084. colorSpaceToWorking: colorSpaceToWorking,
  28085. colorToDirection: colorToDirection,
  28086. compute: compute,
  28087. cond: cond,
  28088. context: context,
  28089. convert: convert,
  28090. convertColorSpace: convertColorSpace,
  28091. convertToTexture: convertToTexture,
  28092. cos: cos,
  28093. cross: cross,
  28094. cubeTexture: cubeTexture,
  28095. dFdx: dFdx,
  28096. dFdy: dFdy,
  28097. dashSize: dashSize,
  28098. defaultBuildStages: defaultBuildStages,
  28099. defaultShaderStages: defaultShaderStages,
  28100. defined: defined,
  28101. degrees: degrees,
  28102. deltaTime: deltaTime,
  28103. densityFog: densityFog,
  28104. densityFogFactor: densityFogFactor,
  28105. depth: depth,
  28106. depthPass: depthPass,
  28107. difference: difference,
  28108. diffuseColor: diffuseColor,
  28109. directPointLight: directPointLight,
  28110. directionToColor: directionToColor,
  28111. dispersion: dispersion,
  28112. distance: distance,
  28113. div: div,
  28114. dodge: dodge,
  28115. dot: dot,
  28116. drawIndex: drawIndex,
  28117. dynamicBufferAttribute: dynamicBufferAttribute,
  28118. element: element,
  28119. emissive: emissive,
  28120. equal: equal,
  28121. equals: equals,
  28122. equirectUV: equirectUV,
  28123. exp: exp,
  28124. exp2: exp2,
  28125. expression: expression,
  28126. faceDirection: faceDirection,
  28127. faceForward: faceForward,
  28128. faceforward: faceforward,
  28129. float: float,
  28130. floor: floor,
  28131. fog: fog,
  28132. fract: fract,
  28133. frameGroup: frameGroup,
  28134. frameId: frameId,
  28135. frontFacing: frontFacing,
  28136. fwidth: fwidth,
  28137. gain: gain,
  28138. gapSize: gapSize,
  28139. getConstNodeType: getConstNodeType,
  28140. getCurrentStack: getCurrentStack,
  28141. getDirection: getDirection,
  28142. getDistanceAttenuation: getDistanceAttenuation,
  28143. getGeometryRoughness: getGeometryRoughness,
  28144. getNormalFromDepth: getNormalFromDepth,
  28145. getParallaxCorrectNormal: getParallaxCorrectNormal,
  28146. getRoughness: getRoughness,
  28147. getScreenPosition: getScreenPosition,
  28148. getShIrradianceAt: getShIrradianceAt,
  28149. getTextureIndex: getTextureIndex,
  28150. getViewPosition: getViewPosition,
  28151. globalId: globalId,
  28152. glsl: glsl,
  28153. glslFn: glslFn,
  28154. grayscale: grayscale,
  28155. greaterThan: greaterThan,
  28156. greaterThanEqual: greaterThanEqual,
  28157. hash: hash,
  28158. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  28159. highpModelViewMatrix: highpModelViewMatrix,
  28160. hue: hue,
  28161. instance: instance,
  28162. instanceIndex: instanceIndex,
  28163. instancedArray: instancedArray,
  28164. instancedBufferAttribute: instancedBufferAttribute,
  28165. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  28166. instancedMesh: instancedMesh,
  28167. int: int,
  28168. inverseSqrt: inverseSqrt,
  28169. inversesqrt: inversesqrt,
  28170. invocationLocalIndex: invocationLocalIndex,
  28171. invocationSubgroupIndex: invocationSubgroupIndex,
  28172. ior: ior,
  28173. iridescence: iridescence,
  28174. iridescenceIOR: iridescenceIOR,
  28175. iridescenceThickness: iridescenceThickness,
  28176. ivec2: ivec2,
  28177. ivec3: ivec3,
  28178. ivec4: ivec4,
  28179. js: js,
  28180. label: label,
  28181. length: length,
  28182. lengthSq: lengthSq,
  28183. lessThan: lessThan,
  28184. lessThanEqual: lessThanEqual,
  28185. lightPosition: lightPosition,
  28186. lightProjectionUV: lightProjectionUV,
  28187. lightShadowMatrix: lightShadowMatrix,
  28188. lightTargetDirection: lightTargetDirection,
  28189. lightTargetPosition: lightTargetPosition,
  28190. lightViewPosition: lightViewPosition,
  28191. lightingContext: lightingContext,
  28192. lights: lights,
  28193. linearDepth: linearDepth,
  28194. linearToneMapping: linearToneMapping,
  28195. localId: localId,
  28196. log: log,
  28197. log2: log2,
  28198. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  28199. loop: loop,
  28200. luminance: luminance,
  28201. mat2: mat2,
  28202. mat3: mat3,
  28203. mat4: mat4,
  28204. matcapUV: matcapUV,
  28205. materialAO: materialAO,
  28206. materialAlphaTest: materialAlphaTest,
  28207. materialAnisotropy: materialAnisotropy,
  28208. materialAnisotropyVector: materialAnisotropyVector,
  28209. materialAttenuationColor: materialAttenuationColor,
  28210. materialAttenuationDistance: materialAttenuationDistance,
  28211. materialClearcoat: materialClearcoat,
  28212. materialClearcoatNormal: materialClearcoatNormal,
  28213. materialClearcoatRoughness: materialClearcoatRoughness,
  28214. materialColor: materialColor,
  28215. materialDispersion: materialDispersion,
  28216. materialEmissive: materialEmissive,
  28217. materialIOR: materialIOR,
  28218. materialIridescence: materialIridescence,
  28219. materialIridescenceIOR: materialIridescenceIOR,
  28220. materialIridescenceThickness: materialIridescenceThickness,
  28221. materialLightMap: materialLightMap,
  28222. materialLineDashOffset: materialLineDashOffset,
  28223. materialLineDashSize: materialLineDashSize,
  28224. materialLineGapSize: materialLineGapSize,
  28225. materialLineScale: materialLineScale,
  28226. materialLineWidth: materialLineWidth,
  28227. materialMetalness: materialMetalness,
  28228. materialNormal: materialNormal,
  28229. materialOpacity: materialOpacity,
  28230. materialPointSize: materialPointSize,
  28231. materialReference: materialReference,
  28232. materialReflectivity: materialReflectivity,
  28233. materialRefractionRatio: materialRefractionRatio,
  28234. materialRotation: materialRotation,
  28235. materialRoughness: materialRoughness,
  28236. materialSheen: materialSheen,
  28237. materialSheenRoughness: materialSheenRoughness,
  28238. materialShininess: materialShininess,
  28239. materialSpecular: materialSpecular,
  28240. materialSpecularColor: materialSpecularColor,
  28241. materialSpecularIntensity: materialSpecularIntensity,
  28242. materialSpecularStrength: materialSpecularStrength,
  28243. materialThickness: materialThickness,
  28244. materialTransmission: materialTransmission,
  28245. max: max$1,
  28246. maxMipLevel: maxMipLevel,
  28247. mediumpModelViewMatrix: mediumpModelViewMatrix,
  28248. metalness: metalness,
  28249. min: min$1,
  28250. mix: mix,
  28251. mixElement: mixElement,
  28252. mod: mod,
  28253. modInt: modInt,
  28254. modelDirection: modelDirection,
  28255. modelNormalMatrix: modelNormalMatrix,
  28256. modelPosition: modelPosition,
  28257. modelScale: modelScale,
  28258. modelViewMatrix: modelViewMatrix,
  28259. modelViewPosition: modelViewPosition,
  28260. modelViewProjection: modelViewProjection,
  28261. modelWorldMatrix: modelWorldMatrix,
  28262. modelWorldMatrixInverse: modelWorldMatrixInverse,
  28263. morphReference: morphReference,
  28264. mrt: mrt,
  28265. mul: mul,
  28266. mx_aastep: mx_aastep,
  28267. mx_cell_noise_float: mx_cell_noise_float,
  28268. mx_contrast: mx_contrast,
  28269. mx_fractal_noise_float: mx_fractal_noise_float,
  28270. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  28271. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  28272. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  28273. mx_hsvtorgb: mx_hsvtorgb,
  28274. mx_noise_float: mx_noise_float,
  28275. mx_noise_vec3: mx_noise_vec3,
  28276. mx_noise_vec4: mx_noise_vec4,
  28277. mx_ramplr: mx_ramplr,
  28278. mx_ramptb: mx_ramptb,
  28279. mx_rgbtohsv: mx_rgbtohsv,
  28280. mx_safepower: mx_safepower,
  28281. mx_splitlr: mx_splitlr,
  28282. mx_splittb: mx_splittb,
  28283. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  28284. mx_transform_uv: mx_transform_uv,
  28285. mx_worley_noise_float: mx_worley_noise_float,
  28286. mx_worley_noise_vec2: mx_worley_noise_vec2,
  28287. mx_worley_noise_vec3: mx_worley_noise_vec3,
  28288. negate: negate,
  28289. neutralToneMapping: neutralToneMapping,
  28290. nodeArray: nodeArray,
  28291. nodeImmutable: nodeImmutable,
  28292. nodeObject: nodeObject,
  28293. nodeObjects: nodeObjects,
  28294. nodeProxy: nodeProxy,
  28295. normalFlat: normalFlat,
  28296. normalGeometry: normalGeometry,
  28297. normalLocal: normalLocal,
  28298. normalMap: normalMap,
  28299. normalView: normalView,
  28300. normalWorld: normalWorld,
  28301. normalize: normalize,
  28302. not: not,
  28303. notEqual: notEqual,
  28304. numWorkgroups: numWorkgroups,
  28305. objectDirection: objectDirection,
  28306. objectGroup: objectGroup,
  28307. objectPosition: objectPosition,
  28308. objectScale: objectScale,
  28309. objectViewPosition: objectViewPosition,
  28310. objectWorldMatrix: objectWorldMatrix,
  28311. oneMinus: oneMinus,
  28312. or: or,
  28313. orthographicDepthToViewZ: orthographicDepthToViewZ,
  28314. oscSawtooth: oscSawtooth,
  28315. oscSine: oscSine,
  28316. oscSquare: oscSquare,
  28317. oscTriangle: oscTriangle,
  28318. output: output,
  28319. outputStruct: outputStruct,
  28320. overlay: overlay,
  28321. overloadingFn: overloadingFn,
  28322. parabola: parabola,
  28323. parallaxDirection: parallaxDirection,
  28324. parallaxUV: parallaxUV,
  28325. parameter: parameter,
  28326. pass: pass,
  28327. passTexture: passTexture,
  28328. pcurve: pcurve,
  28329. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  28330. pmremTexture: pmremTexture,
  28331. pointUV: pointUV,
  28332. pointWidth: pointWidth,
  28333. positionGeometry: positionGeometry,
  28334. positionLocal: positionLocal,
  28335. positionPrevious: positionPrevious,
  28336. positionView: positionView,
  28337. positionViewDirection: positionViewDirection,
  28338. positionWorld: positionWorld,
  28339. positionWorldDirection: positionWorldDirection,
  28340. posterize: posterize,
  28341. pow: pow,
  28342. pow2: pow2,
  28343. pow3: pow3,
  28344. pow4: pow4,
  28345. property: property,
  28346. radians: radians,
  28347. rand: rand,
  28348. range: range,
  28349. rangeFog: rangeFog,
  28350. rangeFogFactor: rangeFogFactor,
  28351. reciprocal: reciprocal,
  28352. reference: reference,
  28353. referenceBuffer: referenceBuffer,
  28354. reflect: reflect,
  28355. reflectVector: reflectVector,
  28356. reflectView: reflectView,
  28357. reflector: reflector,
  28358. refract: refract,
  28359. refractVector: refractVector,
  28360. refractView: refractView,
  28361. reinhardToneMapping: reinhardToneMapping,
  28362. remainder: remainder,
  28363. remap: remap,
  28364. remapClamp: remapClamp,
  28365. renderGroup: renderGroup,
  28366. renderOutput: renderOutput,
  28367. rendererReference: rendererReference,
  28368. rotate: rotate,
  28369. rotateUV: rotateUV,
  28370. roughness: roughness,
  28371. round: round,
  28372. rtt: rtt,
  28373. sRGBTransferEOTF: sRGBTransferEOTF,
  28374. sRGBTransferOETF: sRGBTransferOETF,
  28375. sampler: sampler,
  28376. saturate: saturate,
  28377. saturation: saturation,
  28378. screen: screen,
  28379. screenCoordinate: screenCoordinate,
  28380. screenSize: screenSize,
  28381. screenUV: screenUV,
  28382. scriptable: scriptable,
  28383. scriptableValue: scriptableValue,
  28384. select: select,
  28385. setCurrentStack: setCurrentStack,
  28386. shaderStages: shaderStages,
  28387. shadow: shadow,
  28388. shadowPositionWorld: shadowPositionWorld,
  28389. shapeCircle: shapeCircle,
  28390. sharedUniformGroup: sharedUniformGroup,
  28391. sheen: sheen,
  28392. sheenRoughness: sheenRoughness,
  28393. shiftLeft: shiftLeft,
  28394. shiftRight: shiftRight,
  28395. shininess: shininess,
  28396. sign: sign,
  28397. sin: sin,
  28398. sinc: sinc,
  28399. skinning: skinning,
  28400. skinningReference: skinningReference,
  28401. smoothstep: smoothstep,
  28402. smoothstepElement: smoothstepElement,
  28403. specularColor: specularColor,
  28404. specularF90: specularF90,
  28405. spherizeUV: spherizeUV,
  28406. split: split,
  28407. spritesheetUV: spritesheetUV,
  28408. sqrt: sqrt,
  28409. stack: stack,
  28410. step: step,
  28411. storage: storage,
  28412. storageBarrier: storageBarrier,
  28413. storageObject: storageObject,
  28414. storageTexture: storageTexture,
  28415. string: string,
  28416. struct: struct,
  28417. sub: sub,
  28418. subgroupIndex: subgroupIndex,
  28419. subgroupSize: subgroupSize,
  28420. tan: tan,
  28421. tangentGeometry: tangentGeometry,
  28422. tangentLocal: tangentLocal,
  28423. tangentView: tangentView,
  28424. tangentWorld: tangentWorld,
  28425. temp: temp,
  28426. texture: texture,
  28427. texture3D: texture3D,
  28428. textureBarrier: textureBarrier,
  28429. textureBicubic: textureBicubic,
  28430. textureCubeUV: textureCubeUV,
  28431. textureLoad: textureLoad,
  28432. textureSize: textureSize,
  28433. textureStore: textureStore,
  28434. thickness: thickness,
  28435. time: time,
  28436. timerDelta: timerDelta,
  28437. timerGlobal: timerGlobal,
  28438. timerLocal: timerLocal,
  28439. toOutputColorSpace: toOutputColorSpace,
  28440. toWorkingColorSpace: toWorkingColorSpace,
  28441. toneMapping: toneMapping,
  28442. toneMappingExposure: toneMappingExposure,
  28443. toonOutlinePass: toonOutlinePass,
  28444. transformDirection: transformDirection,
  28445. transformNormal: transformNormal,
  28446. transformNormalToView: transformNormalToView,
  28447. transformedBentNormalView: transformedBentNormalView,
  28448. transformedBitangentView: transformedBitangentView,
  28449. transformedBitangentWorld: transformedBitangentWorld,
  28450. transformedClearcoatNormalView: transformedClearcoatNormalView,
  28451. transformedNormalView: transformedNormalView,
  28452. transformedNormalWorld: transformedNormalWorld,
  28453. transformedTangentView: transformedTangentView,
  28454. transformedTangentWorld: transformedTangentWorld,
  28455. transmission: transmission,
  28456. transpose: transpose,
  28457. triNoise3D: triNoise3D,
  28458. triplanarTexture: triplanarTexture,
  28459. triplanarTextures: triplanarTextures,
  28460. trunc: trunc,
  28461. tslFn: tslFn,
  28462. uint: uint,
  28463. uniform: uniform,
  28464. uniformArray: uniformArray,
  28465. uniformGroup: uniformGroup,
  28466. uniforms: uniforms,
  28467. userData: userData,
  28468. uv: uv,
  28469. uvec2: uvec2,
  28470. uvec3: uvec3,
  28471. uvec4: uvec4,
  28472. varying: varying,
  28473. varyingProperty: varyingProperty,
  28474. vec2: vec2,
  28475. vec3: vec3,
  28476. vec4: vec4,
  28477. vectorComponents: vectorComponents,
  28478. velocity: velocity,
  28479. vertexColor: vertexColor,
  28480. vertexIndex: vertexIndex,
  28481. vertexStage: vertexStage,
  28482. vibrance: vibrance,
  28483. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  28484. viewZToOrthographicDepth: viewZToOrthographicDepth,
  28485. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  28486. viewport: viewport,
  28487. viewportBottomLeft: viewportBottomLeft,
  28488. viewportCoordinate: viewportCoordinate,
  28489. viewportDepthTexture: viewportDepthTexture,
  28490. viewportLinearDepth: viewportLinearDepth,
  28491. viewportMipTexture: viewportMipTexture,
  28492. viewportResolution: viewportResolution,
  28493. viewportSafeUV: viewportSafeUV,
  28494. viewportSharedTexture: viewportSharedTexture,
  28495. viewportSize: viewportSize,
  28496. viewportTexture: viewportTexture,
  28497. viewportTopLeft: viewportTopLeft,
  28498. viewportUV: viewportUV,
  28499. wgsl: wgsl,
  28500. wgslFn: wgslFn,
  28501. workgroupArray: workgroupArray,
  28502. workgroupBarrier: workgroupBarrier,
  28503. workgroupId: workgroupId,
  28504. workingToColorSpace: workingToColorSpace,
  28505. xor: xor
  28506. });
  28507. const _clearColor$1 = /*@__PURE__*/ new Color4();
  28508. /**
  28509. * This renderer module manages the background.
  28510. *
  28511. * @private
  28512. * @augments DataMap
  28513. */
  28514. class Background extends DataMap {
  28515. /**
  28516. * Constructs a new background management component.
  28517. *
  28518. * @param {Renderer} renderer - The renderer.
  28519. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  28520. */
  28521. constructor( renderer, nodes ) {
  28522. super();
  28523. /**
  28524. * The renderer.
  28525. *
  28526. * @type {Renderer}
  28527. */
  28528. this.renderer = renderer;
  28529. /**
  28530. * Renderer component for managing nodes related logic.
  28531. *
  28532. * @type {Nodes}
  28533. */
  28534. this.nodes = nodes;
  28535. }
  28536. /**
  28537. * Updates the background for the given scene. Depending on how `Scene.background`
  28538. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  28539. * or add a mesh to the render list for rendering the background as a textured plane
  28540. * or skybox.
  28541. *
  28542. * @param {Scene} scene - The scene.
  28543. * @param {RenderList} renderList - The current render list.
  28544. * @param {RenderContext} renderContext - The current render context.
  28545. */
  28546. update( scene, renderList, renderContext ) {
  28547. const renderer = this.renderer;
  28548. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  28549. let forceClear = false;
  28550. if ( background === null ) {
  28551. // no background settings, use clear color configuration from the renderer
  28552. renderer._clearColor.getRGB( _clearColor$1 );
  28553. _clearColor$1.a = renderer._clearColor.a;
  28554. } else if ( background.isColor === true ) {
  28555. // background is an opaque color
  28556. background.getRGB( _clearColor$1 );
  28557. _clearColor$1.a = 1;
  28558. forceClear = true;
  28559. } else if ( background.isNode === true ) {
  28560. const sceneData = this.get( scene );
  28561. const backgroundNode = background;
  28562. _clearColor$1.copy( renderer._clearColor );
  28563. let backgroundMesh = sceneData.backgroundMesh;
  28564. if ( backgroundMesh === undefined ) {
  28565. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  28566. // @TODO: Add Texture2D support using node context
  28567. getUV: () => backgroundRotation.mul( normalWorld ),
  28568. getTextureLevel: () => backgroundBlurriness
  28569. } );
  28570. let viewProj = modelViewProjection;
  28571. viewProj = viewProj.setZ( viewProj.w );
  28572. const nodeMaterial = new NodeMaterial();
  28573. nodeMaterial.name = 'Background.material';
  28574. nodeMaterial.side = BackSide;
  28575. nodeMaterial.depthTest = false;
  28576. nodeMaterial.depthWrite = false;
  28577. nodeMaterial.fog = false;
  28578. nodeMaterial.lights = false;
  28579. nodeMaterial.vertexNode = viewProj;
  28580. nodeMaterial.colorNode = backgroundMeshNode;
  28581. sceneData.backgroundMeshNode = backgroundMeshNode;
  28582. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  28583. backgroundMesh.frustumCulled = false;
  28584. backgroundMesh.name = 'Background.mesh';
  28585. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  28586. this.matrixWorld.copyPosition( camera.matrixWorld );
  28587. };
  28588. }
  28589. const backgroundCacheKey = backgroundNode.getCacheKey();
  28590. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  28591. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  28592. sceneData.backgroundMeshNode.needsUpdate = true;
  28593. backgroundMesh.material.needsUpdate = true;
  28594. sceneData.backgroundCacheKey = backgroundCacheKey;
  28595. }
  28596. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  28597. } else {
  28598. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  28599. }
  28600. //
  28601. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  28602. if ( environmentBlendMode === 'additive' ) {
  28603. _clearColor$1.set( 0, 0, 0, 1 );
  28604. } else if ( environmentBlendMode === 'alpha-blend' ) {
  28605. _clearColor$1.set( 0, 0, 0, 0 );
  28606. }
  28607. //
  28608. if ( renderer.autoClear === true || forceClear === true ) {
  28609. const clearColorValue = renderContext.clearColorValue;
  28610. clearColorValue.r = _clearColor$1.r;
  28611. clearColorValue.g = _clearColor$1.g;
  28612. clearColorValue.b = _clearColor$1.b;
  28613. clearColorValue.a = _clearColor$1.a;
  28614. // premultiply alpha
  28615. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  28616. clearColorValue.r *= clearColorValue.a;
  28617. clearColorValue.g *= clearColorValue.a;
  28618. clearColorValue.b *= clearColorValue.a;
  28619. }
  28620. //
  28621. renderContext.depthClearValue = renderer._clearDepth;
  28622. renderContext.stencilClearValue = renderer._clearStencil;
  28623. renderContext.clearColor = renderer.autoClearColor === true;
  28624. renderContext.clearDepth = renderer.autoClearDepth === true;
  28625. renderContext.clearStencil = renderer.autoClearStencil === true;
  28626. } else {
  28627. renderContext.clearColor = false;
  28628. renderContext.clearDepth = false;
  28629. renderContext.clearStencil = false;
  28630. }
  28631. }
  28632. }
  28633. let _id$6 = 0;
  28634. /**
  28635. * A bind group represents a collection of bindings and thus a collection
  28636. * or resources. Bind groups are assigned to pipelines to provide them
  28637. * with the required resources (like uniform buffers or textures).
  28638. *
  28639. * @private
  28640. */
  28641. class BindGroup {
  28642. /**
  28643. * Constructs a new bind group.
  28644. *
  28645. * @param {string} name - The bind group's name.
  28646. * @param {Array<Binding>} bindings - An array of bindings.
  28647. * @param {number} index - The group index.
  28648. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  28649. */
  28650. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  28651. /**
  28652. * The bind group's name.
  28653. *
  28654. * @type {string}
  28655. */
  28656. this.name = name;
  28657. /**
  28658. * An array of bindings.
  28659. *
  28660. * @type {Array<Binding>}
  28661. */
  28662. this.bindings = bindings;
  28663. /**
  28664. * The group index.
  28665. *
  28666. * @type {number}
  28667. */
  28668. this.index = index;
  28669. /**
  28670. * An array of reference bindings.
  28671. *
  28672. * @type {Array<Binding>}
  28673. */
  28674. this.bindingsReference = bindingsReference;
  28675. /**
  28676. * The group's ID.
  28677. *
  28678. * @type {number}
  28679. */
  28680. this.id = _id$6 ++;
  28681. }
  28682. }
  28683. /**
  28684. * This module represents the state of a node builder after it was
  28685. * used to build the nodes for a render object. The state holds the
  28686. * results of the build for further processing in the renderer.
  28687. *
  28688. * Render objects with identical cache keys share the same node builder state.
  28689. *
  28690. * @private
  28691. */
  28692. class NodeBuilderState {
  28693. /**
  28694. * Constructs a new node builder state.
  28695. *
  28696. * @param {?string} vertexShader - The native vertex shader code.
  28697. * @param {?string} fragmentShader - The native fragment shader code.
  28698. * @param {?string} computeShader - The native compute shader code.
  28699. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  28700. * @param {Array<BindGroup>} bindings - An array of bind groups.
  28701. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  28702. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  28703. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  28704. * @param {NodeMaterialObserver} observer - A node material observer.
  28705. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  28706. */
  28707. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  28708. /**
  28709. * The native vertex shader code.
  28710. *
  28711. * @type {string}
  28712. */
  28713. this.vertexShader = vertexShader;
  28714. /**
  28715. * The native fragment shader code.
  28716. *
  28717. * @type {string}
  28718. */
  28719. this.fragmentShader = fragmentShader;
  28720. /**
  28721. * The native compute shader code.
  28722. *
  28723. * @type {string}
  28724. */
  28725. this.computeShader = computeShader;
  28726. /**
  28727. * An array with transform attribute objects.
  28728. * Only relevant when using compute shaders with WebGL 2.
  28729. *
  28730. * @type {Array<Object>}
  28731. */
  28732. this.transforms = transforms;
  28733. /**
  28734. * An array of node attributes representing
  28735. * the attributes of the shaders.
  28736. *
  28737. * @type {Array<NodeAttribute>}
  28738. */
  28739. this.nodeAttributes = nodeAttributes;
  28740. /**
  28741. * An array of bind groups representing the uniform or storage
  28742. * buffers, texture or samplers of the shader.
  28743. *
  28744. * @type {Array<BindGroup>}
  28745. */
  28746. this.bindings = bindings;
  28747. /**
  28748. * An array of nodes that implement their `update()` method.
  28749. *
  28750. * @type {Array<Node>}
  28751. */
  28752. this.updateNodes = updateNodes;
  28753. /**
  28754. * An array of nodes that implement their `updateBefore()` method.
  28755. *
  28756. * @type {Array<Node>}
  28757. */
  28758. this.updateBeforeNodes = updateBeforeNodes;
  28759. /**
  28760. * An array of nodes that implement their `updateAfter()` method.
  28761. *
  28762. * @type {Array<Node>}
  28763. */
  28764. this.updateAfterNodes = updateAfterNodes;
  28765. /**
  28766. * A node material observer.
  28767. *
  28768. * @type {NodeMaterialObserver}
  28769. */
  28770. this.observer = observer;
  28771. /**
  28772. * How often this state is used by render objects.
  28773. *
  28774. * @type {number}
  28775. */
  28776. this.usedTimes = 0;
  28777. }
  28778. /**
  28779. * This method is used to create a array of bind groups based
  28780. * on the existing bind groups of this state. Shared groups are
  28781. * not cloned.
  28782. *
  28783. * @return {Array<BindGroup>} A array of bind groups.
  28784. */
  28785. createBindings() {
  28786. const bindings = [];
  28787. for ( const instanceGroup of this.bindings ) {
  28788. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28789. if ( shared !== true ) {
  28790. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28791. bindings.push( bindingsGroup );
  28792. for ( const instanceBinding of instanceGroup.bindings ) {
  28793. bindingsGroup.bindings.push( instanceBinding.clone() );
  28794. }
  28795. } else {
  28796. bindings.push( instanceGroup );
  28797. }
  28798. }
  28799. return bindings;
  28800. }
  28801. }
  28802. /**
  28803. * {@link NodeBuilder} is going to create instances of this class during the build process
  28804. * of nodes. They represent the final shader attributes that are going to be generated
  28805. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28806. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28807. */
  28808. class NodeAttribute {
  28809. /**
  28810. * Constructs a new node attribute.
  28811. *
  28812. * @param {string} name - The name of the attribute.
  28813. * @param {string} type - The type of the attribute.
  28814. * @param {?Node} node - An optional reference to the node.
  28815. */
  28816. constructor( name, type, node = null ) {
  28817. /**
  28818. * This flag can be used for type testing.
  28819. *
  28820. * @type {boolean}
  28821. * @readonly
  28822. * @default true
  28823. */
  28824. this.isNodeAttribute = true;
  28825. /**
  28826. * The name of the attribute.
  28827. *
  28828. * @type {string}
  28829. */
  28830. this.name = name;
  28831. /**
  28832. * The type of the attribute.
  28833. *
  28834. * @type {string}
  28835. */
  28836. this.type = type;
  28837. /**
  28838. * An optional reference to the node.
  28839. *
  28840. * @type {?Node}
  28841. * @default null
  28842. */
  28843. this.node = node;
  28844. }
  28845. }
  28846. /**
  28847. * {@link NodeBuilder} is going to create instances of this class during the build process
  28848. * of nodes. They represent the final shader uniforms that are going to be generated
  28849. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28850. * for this purpose.
  28851. */
  28852. class NodeUniform {
  28853. /**
  28854. * Constructs a new node uniform.
  28855. *
  28856. * @param {string} name - The name of the uniform.
  28857. * @param {string} type - The type of the uniform.
  28858. * @param {UniformNode} node - An reference to the node.
  28859. */
  28860. constructor( name, type, node ) {
  28861. /**
  28862. * This flag can be used for type testing.
  28863. *
  28864. * @type {boolean}
  28865. * @readonly
  28866. * @default true
  28867. */
  28868. this.isNodeUniform = true;
  28869. /**
  28870. * The name of the uniform.
  28871. *
  28872. * @type {string}
  28873. */
  28874. this.name = name;
  28875. /**
  28876. * The type of the uniform.
  28877. *
  28878. * @type {string}
  28879. */
  28880. this.type = type;
  28881. /**
  28882. * An reference to the node.
  28883. *
  28884. * @type {UniformNode}
  28885. */
  28886. this.node = node.getSelf();
  28887. }
  28888. /**
  28889. * The value of the uniform node.
  28890. *
  28891. * @type {any}
  28892. */
  28893. get value() {
  28894. return this.node.value;
  28895. }
  28896. set value( val ) {
  28897. this.node.value = val;
  28898. }
  28899. /**
  28900. * The id of the uniform node.
  28901. *
  28902. * @type {number}
  28903. */
  28904. get id() {
  28905. return this.node.id;
  28906. }
  28907. /**
  28908. * The uniform node's group.
  28909. *
  28910. * @type {UniformGroupNode}
  28911. */
  28912. get groupNode() {
  28913. return this.node.groupNode;
  28914. }
  28915. }
  28916. /**
  28917. * {@link NodeBuilder} is going to create instances of this class during the build process
  28918. * of nodes. They represent the final shader variables that are going to be generated
  28919. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28920. * this purpose.
  28921. */
  28922. class NodeVar {
  28923. /**
  28924. * Constructs a new node variable.
  28925. *
  28926. * @param {string} name - The name of the variable.
  28927. * @param {string} type - The type of the variable.
  28928. * @param {boolean} [readOnly=false] - The read-only flag.
  28929. * @param {?number} [count=null] - The size.
  28930. */
  28931. constructor( name, type, readOnly = false, count = null ) {
  28932. /**
  28933. * This flag can be used for type testing.
  28934. *
  28935. * @type {boolean}
  28936. * @readonly
  28937. * @default true
  28938. */
  28939. this.isNodeVar = true;
  28940. /**
  28941. * The name of the variable.
  28942. *
  28943. * @type {string}
  28944. */
  28945. this.name = name;
  28946. /**
  28947. * The type of the variable.
  28948. *
  28949. * @type {string}
  28950. */
  28951. this.type = type;
  28952. /**
  28953. * The read-only flag.
  28954. *
  28955. * @type {boolean}
  28956. */
  28957. this.readOnly = readOnly;
  28958. /**
  28959. * The size.
  28960. *
  28961. * @type {?number}
  28962. */
  28963. this.count = count;
  28964. }
  28965. }
  28966. /**
  28967. * {@link NodeBuilder} is going to create instances of this class during the build process
  28968. * of nodes. They represent the final shader varyings that are going to be generated
  28969. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28970. * this purpose.
  28971. *
  28972. * @augments NodeVar
  28973. */
  28974. class NodeVarying extends NodeVar {
  28975. /**
  28976. * Constructs a new node varying.
  28977. *
  28978. * @param {string} name - The name of the varying.
  28979. * @param {string} type - The type of the varying.
  28980. */
  28981. constructor( name, type ) {
  28982. super( name, type );
  28983. /**
  28984. * Whether this varying requires interpolation or not. This property can be used
  28985. * to check if the varying can be optimized for a variable.
  28986. *
  28987. * @type {boolean}
  28988. * @default false
  28989. */
  28990. this.needsInterpolation = false;
  28991. /**
  28992. * This flag can be used for type testing.
  28993. *
  28994. * @type {boolean}
  28995. * @readonly
  28996. * @default true
  28997. */
  28998. this.isNodeVarying = true;
  28999. }
  29000. }
  29001. /**
  29002. * {@link NodeBuilder} is going to create instances of this class during the build process
  29003. * of nodes. They represent user-defined, native shader code portions that are going to be
  29004. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  29005. * for this purpose.
  29006. */
  29007. class NodeCode {
  29008. /**
  29009. * Constructs a new code node.
  29010. *
  29011. * @param {string} name - The name of the code.
  29012. * @param {string} type - The node type.
  29013. * @param {string} [code=''] - The native shader code.
  29014. */
  29015. constructor( name, type, code = '' ) {
  29016. /**
  29017. * The name of the code.
  29018. *
  29019. * @type {string}
  29020. */
  29021. this.name = name;
  29022. /**
  29023. * The node type.
  29024. *
  29025. * @type {string}
  29026. */
  29027. this.type = type;
  29028. /**
  29029. * The native shader code.
  29030. *
  29031. * @type {string}
  29032. * @default ''
  29033. */
  29034. this.code = code;
  29035. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29036. }
  29037. }
  29038. let _id$5 = 0;
  29039. /**
  29040. * This utility class is used in {@link NodeBuilder} as an internal
  29041. * cache data structure for node data.
  29042. */
  29043. class NodeCache {
  29044. /**
  29045. * Constructs a new node cache.
  29046. *
  29047. * @param {?NodeCache} parent - A reference to a parent cache.
  29048. */
  29049. constructor( parent = null ) {
  29050. /**
  29051. * The id of the cache.
  29052. *
  29053. * @type {number}
  29054. * @readonly
  29055. */
  29056. this.id = _id$5 ++;
  29057. /**
  29058. * A weak map for managing node data.
  29059. *
  29060. * @type {WeakMap<Node, Object>}
  29061. */
  29062. this.nodesData = new WeakMap();
  29063. /**
  29064. * Reference to a parent node cache.
  29065. *
  29066. * @type {?NodeCache}
  29067. * @default null
  29068. */
  29069. this.parent = parent;
  29070. }
  29071. /**
  29072. * Returns the data for the given node.
  29073. *
  29074. * @param {Node} node - The node.
  29075. * @return {?Object} The data for the node.
  29076. */
  29077. getData( node ) {
  29078. let data = this.nodesData.get( node );
  29079. if ( data === undefined && this.parent !== null ) {
  29080. data = this.parent.getData( node );
  29081. }
  29082. return data;
  29083. }
  29084. /**
  29085. * Sets the data for a given node.
  29086. *
  29087. * @param {Node} node - The node.
  29088. * @param {Object} data - The data that should be cached.
  29089. */
  29090. setData( node, data ) {
  29091. this.nodesData.set( node, data );
  29092. }
  29093. }
  29094. class StructType {
  29095. constructor( name, members ) {
  29096. this.name = name;
  29097. this.members = members;
  29098. this.output = false;
  29099. }
  29100. }
  29101. /**
  29102. * Abstract base class for uniforms.
  29103. *
  29104. * @abstract
  29105. * @private
  29106. */
  29107. class Uniform {
  29108. /**
  29109. * Constructs a new uniform.
  29110. *
  29111. * @param {string} name - The uniform's name.
  29112. * @param {any} value - The uniform's value.
  29113. */
  29114. constructor( name, value ) {
  29115. /**
  29116. * The uniform's name.
  29117. *
  29118. * @type {string}
  29119. */
  29120. this.name = name;
  29121. /**
  29122. * The uniform's value.
  29123. *
  29124. * @type {any}
  29125. */
  29126. this.value = value;
  29127. /**
  29128. * Used to build the uniform buffer according to the STD140 layout.
  29129. * Derived uniforms will set this property to a data type specific
  29130. * value.
  29131. *
  29132. * @type {number}
  29133. */
  29134. this.boundary = 0;
  29135. /**
  29136. * The item size. Derived uniforms will set this property to a data
  29137. * type specific value.
  29138. *
  29139. * @type {number}
  29140. */
  29141. this.itemSize = 0;
  29142. /**
  29143. * This property is set by {@link UniformsGroup} and marks
  29144. * the start position in the uniform buffer.
  29145. *
  29146. * @type {number}
  29147. */
  29148. this.offset = 0;
  29149. }
  29150. /**
  29151. * Sets the uniform's value.
  29152. *
  29153. * @param {any} value - The value to set.
  29154. */
  29155. setValue( value ) {
  29156. this.value = value;
  29157. }
  29158. /**
  29159. * Returns the uniform's value.
  29160. *
  29161. * @return {any} The value.
  29162. */
  29163. getValue() {
  29164. return this.value;
  29165. }
  29166. }
  29167. /**
  29168. * Represents a Number uniform.
  29169. *
  29170. * @private
  29171. * @augments Uniform
  29172. */
  29173. class NumberUniform extends Uniform {
  29174. /**
  29175. * Constructs a new Number uniform.
  29176. *
  29177. * @param {string} name - The uniform's name.
  29178. * @param {number} value - The uniform's value.
  29179. */
  29180. constructor( name, value = 0 ) {
  29181. super( name, value );
  29182. /**
  29183. * This flag can be used for type testing.
  29184. *
  29185. * @type {boolean}
  29186. * @readonly
  29187. * @default true
  29188. */
  29189. this.isNumberUniform = true;
  29190. this.boundary = 4;
  29191. this.itemSize = 1;
  29192. }
  29193. }
  29194. /**
  29195. * Represents a Vector2 uniform.
  29196. *
  29197. * @private
  29198. * @augments Uniform
  29199. */
  29200. class Vector2Uniform extends Uniform {
  29201. /**
  29202. * Constructs a new Number uniform.
  29203. *
  29204. * @param {string} name - The uniform's name.
  29205. * @param {Vector2} value - The uniform's value.
  29206. */
  29207. constructor( name, value = new Vector2() ) {
  29208. super( name, value );
  29209. /**
  29210. * This flag can be used for type testing.
  29211. *
  29212. * @type {boolean}
  29213. * @readonly
  29214. * @default true
  29215. */
  29216. this.isVector2Uniform = true;
  29217. this.boundary = 8;
  29218. this.itemSize = 2;
  29219. }
  29220. }
  29221. /**
  29222. * Represents a Vector3 uniform.
  29223. *
  29224. * @private
  29225. * @augments Uniform
  29226. */
  29227. class Vector3Uniform extends Uniform {
  29228. /**
  29229. * Constructs a new Number uniform.
  29230. *
  29231. * @param {string} name - The uniform's name.
  29232. * @param {Vector3} value - The uniform's value.
  29233. */
  29234. constructor( name, value = new Vector3() ) {
  29235. super( name, value );
  29236. /**
  29237. * This flag can be used for type testing.
  29238. *
  29239. * @type {boolean}
  29240. * @readonly
  29241. * @default true
  29242. */
  29243. this.isVector3Uniform = true;
  29244. this.boundary = 16;
  29245. this.itemSize = 3;
  29246. }
  29247. }
  29248. /**
  29249. * Represents a Vector4 uniform.
  29250. *
  29251. * @private
  29252. * @augments Uniform
  29253. */
  29254. class Vector4Uniform extends Uniform {
  29255. /**
  29256. * Constructs a new Number uniform.
  29257. *
  29258. * @param {string} name - The uniform's name.
  29259. * @param {Vector4} value - The uniform's value.
  29260. */
  29261. constructor( name, value = new Vector4() ) {
  29262. super( name, value );
  29263. /**
  29264. * This flag can be used for type testing.
  29265. *
  29266. * @type {boolean}
  29267. * @readonly
  29268. * @default true
  29269. */
  29270. this.isVector4Uniform = true;
  29271. this.boundary = 16;
  29272. this.itemSize = 4;
  29273. }
  29274. }
  29275. /**
  29276. * Represents a Color uniform.
  29277. *
  29278. * @private
  29279. * @augments Uniform
  29280. */
  29281. class ColorUniform extends Uniform {
  29282. /**
  29283. * Constructs a new Number uniform.
  29284. *
  29285. * @param {string} name - The uniform's name.
  29286. * @param {Color} value - The uniform's value.
  29287. */
  29288. constructor( name, value = new Color() ) {
  29289. super( name, value );
  29290. /**
  29291. * This flag can be used for type testing.
  29292. *
  29293. * @type {boolean}
  29294. * @readonly
  29295. * @default true
  29296. */
  29297. this.isColorUniform = true;
  29298. this.boundary = 16;
  29299. this.itemSize = 3;
  29300. }
  29301. }
  29302. /**
  29303. * Represents a Matrix2 uniform.
  29304. *
  29305. * @private
  29306. * @augments Uniform
  29307. */
  29308. class Matrix2Uniform extends Uniform {
  29309. /**
  29310. * Constructs a new Number uniform.
  29311. *
  29312. * @param {string} name - The uniform's name.
  29313. * @param {Matrix2} value - The uniform's value.
  29314. */
  29315. constructor( name, value = new Matrix2() ) {
  29316. super( name, value );
  29317. /**
  29318. * This flag can be used for type testing.
  29319. *
  29320. * @type {boolean}
  29321. * @readonly
  29322. * @default true
  29323. */
  29324. this.isMatrix2Uniform = true;
  29325. this.boundary = 16;
  29326. this.itemSize = 4;
  29327. }
  29328. }
  29329. /**
  29330. * Represents a Matrix3 uniform.
  29331. *
  29332. * @private
  29333. * @augments Uniform
  29334. */
  29335. class Matrix3Uniform extends Uniform {
  29336. /**
  29337. * Constructs a new Number uniform.
  29338. *
  29339. * @param {string} name - The uniform's name.
  29340. * @param {Matrix3} value - The uniform's value.
  29341. */
  29342. constructor( name, value = new Matrix3() ) {
  29343. super( name, value );
  29344. /**
  29345. * This flag can be used for type testing.
  29346. *
  29347. * @type {boolean}
  29348. * @readonly
  29349. * @default true
  29350. */
  29351. this.isMatrix3Uniform = true;
  29352. this.boundary = 48;
  29353. this.itemSize = 12;
  29354. }
  29355. }
  29356. /**
  29357. * Represents a Matrix4 uniform.
  29358. *
  29359. * @private
  29360. * @augments Uniform
  29361. */
  29362. class Matrix4Uniform extends Uniform {
  29363. /**
  29364. * Constructs a new Number uniform.
  29365. *
  29366. * @param {string} name - The uniform's name.
  29367. * @param {Matrix4} value - The uniform's value.
  29368. */
  29369. constructor( name, value = new Matrix4() ) {
  29370. super( name, value );
  29371. /**
  29372. * This flag can be used for type testing.
  29373. *
  29374. * @type {boolean}
  29375. * @readonly
  29376. * @default true
  29377. */
  29378. this.isMatrix4Uniform = true;
  29379. this.boundary = 64;
  29380. this.itemSize = 16;
  29381. }
  29382. }
  29383. /**
  29384. * A special form of Number uniform binding type.
  29385. * It's value is managed by a node object.
  29386. *
  29387. * @private
  29388. * @augments NumberUniform
  29389. */
  29390. class NumberNodeUniform extends NumberUniform {
  29391. /**
  29392. * Constructs a new node-based Number uniform.
  29393. *
  29394. * @param {NodeUniform} nodeUniform - The node uniform.
  29395. */
  29396. constructor( nodeUniform ) {
  29397. super( nodeUniform.name, nodeUniform.value );
  29398. /**
  29399. * The node uniform.
  29400. *
  29401. * @type {NodeUniform}
  29402. */
  29403. this.nodeUniform = nodeUniform;
  29404. }
  29405. /**
  29406. * Overwritten to return the value of the node uniform.
  29407. *
  29408. * @return {number} The value.
  29409. */
  29410. getValue() {
  29411. return this.nodeUniform.value;
  29412. }
  29413. /**
  29414. * Returns the node uniform data type.
  29415. *
  29416. * @return {string} The data type.
  29417. */
  29418. getType() {
  29419. return this.nodeUniform.type;
  29420. }
  29421. }
  29422. /**
  29423. * A special form of Vector2 uniform binding type.
  29424. * It's value is managed by a node object.
  29425. *
  29426. * @private
  29427. * @augments Vector2Uniform
  29428. */
  29429. class Vector2NodeUniform extends Vector2Uniform {
  29430. /**
  29431. * Constructs a new node-based Vector2 uniform.
  29432. *
  29433. * @param {NodeUniform} nodeUniform - The node uniform.
  29434. */
  29435. constructor( nodeUniform ) {
  29436. super( nodeUniform.name, nodeUniform.value );
  29437. /**
  29438. * The node uniform.
  29439. *
  29440. * @type {NodeUniform}
  29441. */
  29442. this.nodeUniform = nodeUniform;
  29443. }
  29444. /**
  29445. * Overwritten to return the value of the node uniform.
  29446. *
  29447. * @return {Vector2} The value.
  29448. */
  29449. getValue() {
  29450. return this.nodeUniform.value;
  29451. }
  29452. /**
  29453. * Returns the node uniform data type.
  29454. *
  29455. * @return {string} The data type.
  29456. */
  29457. getType() {
  29458. return this.nodeUniform.type;
  29459. }
  29460. }
  29461. /**
  29462. * A special form of Vector3 uniform binding type.
  29463. * It's value is managed by a node object.
  29464. *
  29465. * @private
  29466. * @augments Vector3Uniform
  29467. */
  29468. class Vector3NodeUniform extends Vector3Uniform {
  29469. /**
  29470. * Constructs a new node-based Vector3 uniform.
  29471. *
  29472. * @param {NodeUniform} nodeUniform - The node uniform.
  29473. */
  29474. constructor( nodeUniform ) {
  29475. super( nodeUniform.name, nodeUniform.value );
  29476. /**
  29477. * The node uniform.
  29478. *
  29479. * @type {NodeUniform}
  29480. */
  29481. this.nodeUniform = nodeUniform;
  29482. }
  29483. /**
  29484. * Overwritten to return the value of the node uniform.
  29485. *
  29486. * @return {Vector3} The value.
  29487. */
  29488. getValue() {
  29489. return this.nodeUniform.value;
  29490. }
  29491. /**
  29492. * Returns the node uniform data type.
  29493. *
  29494. * @return {string} The data type.
  29495. */
  29496. getType() {
  29497. return this.nodeUniform.type;
  29498. }
  29499. }
  29500. /**
  29501. * A special form of Vector4 uniform binding type.
  29502. * It's value is managed by a node object.
  29503. *
  29504. * @private
  29505. * @augments Vector4Uniform
  29506. */
  29507. class Vector4NodeUniform extends Vector4Uniform {
  29508. /**
  29509. * Constructs a new node-based Vector4 uniform.
  29510. *
  29511. * @param {NodeUniform} nodeUniform - The node uniform.
  29512. */
  29513. constructor( nodeUniform ) {
  29514. super( nodeUniform.name, nodeUniform.value );
  29515. /**
  29516. * The node uniform.
  29517. *
  29518. * @type {NodeUniform}
  29519. */
  29520. this.nodeUniform = nodeUniform;
  29521. }
  29522. /**
  29523. * Overwritten to return the value of the node uniform.
  29524. *
  29525. * @return {Vector4} The value.
  29526. */
  29527. getValue() {
  29528. return this.nodeUniform.value;
  29529. }
  29530. /**
  29531. * Returns the node uniform data type.
  29532. *
  29533. * @return {string} The data type.
  29534. */
  29535. getType() {
  29536. return this.nodeUniform.type;
  29537. }
  29538. }
  29539. /**
  29540. * A special form of Color uniform binding type.
  29541. * It's value is managed by a node object.
  29542. *
  29543. * @private
  29544. * @augments ColorUniform
  29545. */
  29546. class ColorNodeUniform extends ColorUniform {
  29547. /**
  29548. * Constructs a new node-based Color uniform.
  29549. *
  29550. * @param {NodeUniform} nodeUniform - The node uniform.
  29551. */
  29552. constructor( nodeUniform ) {
  29553. super( nodeUniform.name, nodeUniform.value );
  29554. /**
  29555. * The node uniform.
  29556. *
  29557. * @type {NodeUniform}
  29558. */
  29559. this.nodeUniform = nodeUniform;
  29560. }
  29561. /**
  29562. * Overwritten to return the value of the node uniform.
  29563. *
  29564. * @return {Color} The value.
  29565. */
  29566. getValue() {
  29567. return this.nodeUniform.value;
  29568. }
  29569. /**
  29570. * Returns the node uniform data type.
  29571. *
  29572. * @return {string} The data type.
  29573. */
  29574. getType() {
  29575. return this.nodeUniform.type;
  29576. }
  29577. }
  29578. /**
  29579. * A special form of Matrix2 uniform binding type.
  29580. * It's value is managed by a node object.
  29581. *
  29582. * @private
  29583. * @augments Matrix2Uniform
  29584. */
  29585. class Matrix2NodeUniform extends Matrix2Uniform {
  29586. /**
  29587. * Constructs a new node-based Matrix2 uniform.
  29588. *
  29589. * @param {NodeUniform} nodeUniform - The node uniform.
  29590. */
  29591. constructor( nodeUniform ) {
  29592. super( nodeUniform.name, nodeUniform.value );
  29593. /**
  29594. * The node uniform.
  29595. *
  29596. * @type {NodeUniform}
  29597. */
  29598. this.nodeUniform = nodeUniform;
  29599. }
  29600. /**
  29601. * Overwritten to return the value of the node uniform.
  29602. *
  29603. * @return {Matrix2} The value.
  29604. */
  29605. getValue() {
  29606. return this.nodeUniform.value;
  29607. }
  29608. /**
  29609. * Returns the node uniform data type.
  29610. *
  29611. * @return {string} The data type.
  29612. */
  29613. getType() {
  29614. return this.nodeUniform.type;
  29615. }
  29616. }
  29617. /**
  29618. * A special form of Matrix3 uniform binding type.
  29619. * It's value is managed by a node object.
  29620. *
  29621. * @private
  29622. * @augments Matrix3Uniform
  29623. */
  29624. class Matrix3NodeUniform extends Matrix3Uniform {
  29625. /**
  29626. * Constructs a new node-based Matrix3 uniform.
  29627. *
  29628. * @param {NodeUniform} nodeUniform - The node uniform.
  29629. */
  29630. constructor( nodeUniform ) {
  29631. super( nodeUniform.name, nodeUniform.value );
  29632. /**
  29633. * The node uniform.
  29634. *
  29635. * @type {NodeUniform}
  29636. */
  29637. this.nodeUniform = nodeUniform;
  29638. }
  29639. /**
  29640. * Overwritten to return the value of the node uniform.
  29641. *
  29642. * @return {Matrix3} The value.
  29643. */
  29644. getValue() {
  29645. return this.nodeUniform.value;
  29646. }
  29647. /**
  29648. * Returns the node uniform data type.
  29649. *
  29650. * @return {string} The data type.
  29651. */
  29652. getType() {
  29653. return this.nodeUniform.type;
  29654. }
  29655. }
  29656. /**
  29657. * A special form of Matrix4 uniform binding type.
  29658. * It's value is managed by a node object.
  29659. *
  29660. * @private
  29661. * @augments Matrix4Uniform
  29662. */
  29663. class Matrix4NodeUniform extends Matrix4Uniform {
  29664. /**
  29665. * Constructs a new node-based Matrix4 uniform.
  29666. *
  29667. * @param {NodeUniform} nodeUniform - The node uniform.
  29668. */
  29669. constructor( nodeUniform ) {
  29670. super( nodeUniform.name, nodeUniform.value );
  29671. /**
  29672. * The node uniform.
  29673. *
  29674. * @type {NodeUniform}
  29675. */
  29676. this.nodeUniform = nodeUniform;
  29677. }
  29678. /**
  29679. * Overwritten to return the value of the node uniform.
  29680. *
  29681. * @return {Matrix4} The value.
  29682. */
  29683. getValue() {
  29684. return this.nodeUniform.value;
  29685. }
  29686. /**
  29687. * Returns the node uniform data type.
  29688. *
  29689. * @return {string} The data type.
  29690. */
  29691. getType() {
  29692. return this.nodeUniform.type;
  29693. }
  29694. }
  29695. const LOD_MIN = 4;
  29696. // The standard deviations (radians) associated with the extra mips. These are
  29697. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29698. // geometric shadowing function. These sigma values squared must match the
  29699. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29700. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29701. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29702. // samples and exit early, but not recompile the shader.
  29703. const MAX_SAMPLES = 20;
  29704. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  29705. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29706. const _clearColor = /*@__PURE__*/ new Color();
  29707. let _oldTarget = null;
  29708. let _oldActiveCubeFace = 0;
  29709. let _oldActiveMipmapLevel = 0;
  29710. // Golden Ratio
  29711. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29712. const INV_PHI = 1 / PHI;
  29713. // Vertices of a dodecahedron (except the opposites, which represent the
  29714. // same axis), used as axis directions evenly spread on a sphere.
  29715. const _axisDirections = [
  29716. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29717. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29718. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29719. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29720. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29721. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29722. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  29723. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  29724. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  29725. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29726. ];
  29727. const _origin = /*@__PURE__*/ new Vector3();
  29728. // maps blur materials to their uniforms dictionary
  29729. const _uniformsMap = new WeakMap();
  29730. // WebGPU Face indices
  29731. const _faceLib = [
  29732. 3, 1, 5,
  29733. 0, 4, 2
  29734. ];
  29735. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29736. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  29737. /**
  29738. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29739. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29740. * blur to be quickly accessed based on material roughness. It is packed into a
  29741. * special CubeUV format that allows us to perform custom interpolation so that
  29742. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29743. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29744. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29745. * higher roughness levels. In this way we maintain resolution to smoothly
  29746. * interpolate diffuse lighting while limiting sampling computation.
  29747. *
  29748. * Paper: Fast, Accurate Image-Based Lighting:
  29749. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  29750. */
  29751. class PMREMGenerator {
  29752. constructor( renderer ) {
  29753. this._renderer = renderer;
  29754. this._pingPongRenderTarget = null;
  29755. this._lodMax = 0;
  29756. this._cubeSize = 0;
  29757. this._lodPlanes = [];
  29758. this._sizeLods = [];
  29759. this._sigmas = [];
  29760. this._lodMeshes = [];
  29761. this._blurMaterial = null;
  29762. this._cubemapMaterial = null;
  29763. this._equirectMaterial = null;
  29764. this._backgroundBox = null;
  29765. }
  29766. get _hasInitialized() {
  29767. return this._renderer.hasInitialized();
  29768. }
  29769. /**
  29770. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29771. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29772. * in radians to be applied to the scene before PMREM generation. Optional near
  29773. * and far planes ensure the scene is rendered in its entirety.
  29774. *
  29775. * @param {Scene} scene - The scene to be captured.
  29776. * @param {number} [sigma=0] - The blur radius in radians.
  29777. * @param {number} [near=0.1] - The near plane distance.
  29778. * @param {number} [far=100] - The far plane distance.
  29779. * @param {Object} [options={}] - The configuration options.
  29780. * @param {number} [options.size=256] - The texture size of the PMREM.
  29781. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  29782. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  29783. * @return {RenderTarget} The resulting PMREM.
  29784. * @see fromSceneAsync
  29785. */
  29786. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  29787. const {
  29788. size = 256,
  29789. position = _origin,
  29790. renderTarget = null,
  29791. } = options;
  29792. this._setSize( size );
  29793. if ( this._hasInitialized === false ) {
  29794. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29795. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29796. options.renderTarget = cubeUVRenderTarget;
  29797. this.fromSceneAsync( scene, sigma, near, far, options );
  29798. return cubeUVRenderTarget;
  29799. }
  29800. _oldTarget = this._renderer.getRenderTarget();
  29801. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29802. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29803. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29804. cubeUVRenderTarget.depthBuffer = true;
  29805. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  29806. if ( sigma > 0 ) {
  29807. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29808. }
  29809. this._applyPMREM( cubeUVRenderTarget );
  29810. this._cleanup( cubeUVRenderTarget );
  29811. return cubeUVRenderTarget;
  29812. }
  29813. /**
  29814. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29815. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29816. * in radians to be applied to the scene before PMREM generation. Optional near
  29817. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29818. * is placed at the origin).
  29819. *
  29820. * @param {Scene} scene - The scene to be captured.
  29821. * @param {number} [sigma=0] - The blur radius in radians.
  29822. * @param {number} [near=0.1] - The near plane distance.
  29823. * @param {number} [far=100] - The far plane distance.
  29824. * @param {Object} [options={}] - The configuration options.
  29825. * @param {number} [options.size=256] - The texture size of the PMREM.
  29826. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  29827. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  29828. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  29829. * @see fromScene
  29830. */
  29831. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  29832. if ( this._hasInitialized === false ) await this._renderer.init();
  29833. return this.fromScene( scene, sigma, near, far, options );
  29834. }
  29835. /**
  29836. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29837. * or HDR. The ideal input image size is 1k (1024 x 512),
  29838. * as this matches best with the 256 x 256 cubemap output.
  29839. *
  29840. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29841. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29842. * @return {RenderTarget} The resulting PMREM.
  29843. * @see fromEquirectangularAsync
  29844. */
  29845. fromEquirectangular( equirectangular, renderTarget = null ) {
  29846. if ( this._hasInitialized === false ) {
  29847. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29848. this._setSizeFromTexture( equirectangular );
  29849. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29850. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29851. return cubeUVRenderTarget;
  29852. }
  29853. return this._fromTexture( equirectangular, renderTarget );
  29854. }
  29855. /**
  29856. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29857. * or HDR. The ideal input image size is 1k (1024 x 512),
  29858. * as this matches best with the 256 x 256 cubemap output.
  29859. *
  29860. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29861. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29862. * @return {Promise<RenderTarget>} The resulting PMREM.
  29863. * @see fromEquirectangular
  29864. */
  29865. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29866. if ( this._hasInitialized === false ) await this._renderer.init();
  29867. return this._fromTexture( equirectangular, renderTarget );
  29868. }
  29869. /**
  29870. * Generates a PMREM from an cubemap texture, which can be either LDR
  29871. * or HDR. The ideal input cube size is 256 x 256,
  29872. * as this matches best with the 256 x 256 cubemap output.
  29873. *
  29874. * @param {Texture} cubemap - The cubemap texture to be converted.
  29875. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29876. * @return {RenderTarget} The resulting PMREM.
  29877. * @see fromCubemapAsync
  29878. */
  29879. fromCubemap( cubemap, renderTarget = null ) {
  29880. if ( this._hasInitialized === false ) {
  29881. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29882. this._setSizeFromTexture( cubemap );
  29883. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29884. this.fromCubemapAsync( cubemap, renderTarget );
  29885. return cubeUVRenderTarget;
  29886. }
  29887. return this._fromTexture( cubemap, renderTarget );
  29888. }
  29889. /**
  29890. * Generates a PMREM from an cubemap texture, which can be either LDR
  29891. * or HDR. The ideal input cube size is 256 x 256,
  29892. * with the 256 x 256 cubemap output.
  29893. *
  29894. * @param {Texture} cubemap - The cubemap texture to be converted.
  29895. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29896. * @return {Promise<RenderTarget>} The resulting PMREM.
  29897. * @see fromCubemap
  29898. */
  29899. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29900. if ( this._hasInitialized === false ) await this._renderer.init();
  29901. return this._fromTexture( cubemap, renderTarget );
  29902. }
  29903. /**
  29904. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29905. * your texture's network fetch for increased concurrency.
  29906. *
  29907. * @returns {Promise}
  29908. */
  29909. async compileCubemapShader() {
  29910. if ( this._cubemapMaterial === null ) {
  29911. this._cubemapMaterial = _getCubemapMaterial();
  29912. await this._compileMaterial( this._cubemapMaterial );
  29913. }
  29914. }
  29915. /**
  29916. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29917. * your texture's network fetch for increased concurrency.
  29918. *
  29919. * @returns {Promise}
  29920. */
  29921. async compileEquirectangularShader() {
  29922. if ( this._equirectMaterial === null ) {
  29923. this._equirectMaterial = _getEquirectMaterial();
  29924. await this._compileMaterial( this._equirectMaterial );
  29925. }
  29926. }
  29927. /**
  29928. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29929. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29930. * one of them will cause any others to also become unusable.
  29931. */
  29932. dispose() {
  29933. this._dispose();
  29934. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29935. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29936. if ( this._backgroundBox !== null ) {
  29937. this._backgroundBox.geometry.dispose();
  29938. this._backgroundBox.material.dispose();
  29939. }
  29940. }
  29941. // private interface
  29942. _setSizeFromTexture( texture ) {
  29943. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29944. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29945. } else { // Equirectangular
  29946. this._setSize( texture.image.width / 4 );
  29947. }
  29948. }
  29949. _setSize( cubeSize ) {
  29950. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29951. this._cubeSize = Math.pow( 2, this._lodMax );
  29952. }
  29953. _dispose() {
  29954. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29955. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29956. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29957. this._lodPlanes[ i ].dispose();
  29958. }
  29959. }
  29960. _cleanup( outputTarget ) {
  29961. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29962. outputTarget.scissorTest = false;
  29963. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29964. }
  29965. _fromTexture( texture, renderTarget ) {
  29966. this._setSizeFromTexture( texture );
  29967. _oldTarget = this._renderer.getRenderTarget();
  29968. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29969. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29970. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29971. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29972. this._applyPMREM( cubeUVRenderTarget );
  29973. this._cleanup( cubeUVRenderTarget );
  29974. return cubeUVRenderTarget;
  29975. }
  29976. _allocateTargets() {
  29977. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29978. const height = 4 * this._cubeSize;
  29979. const params = {
  29980. magFilter: LinearFilter,
  29981. minFilter: LinearFilter,
  29982. generateMipmaps: false,
  29983. type: HalfFloatType,
  29984. format: RGBAFormat,
  29985. colorSpace: LinearSRGBColorSpace,
  29986. //depthBuffer: false
  29987. };
  29988. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29989. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29990. if ( this._pingPongRenderTarget !== null ) {
  29991. this._dispose();
  29992. }
  29993. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29994. const { _lodMax } = this;
  29995. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29996. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29997. }
  29998. return cubeUVRenderTarget;
  29999. }
  30000. async _compileMaterial( material ) {
  30001. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30002. await this._renderer.compile( tmpMesh, _flatCamera );
  30003. }
  30004. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  30005. const cubeCamera = _cubeCamera;
  30006. cubeCamera.near = near;
  30007. cubeCamera.far = far;
  30008. // px, py, pz, nx, ny, nz
  30009. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  30010. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  30011. const renderer = this._renderer;
  30012. const originalAutoClear = renderer.autoClear;
  30013. renderer.getClearColor( _clearColor );
  30014. renderer.autoClear = false;
  30015. let backgroundBox = this._backgroundBox;
  30016. if ( backgroundBox === null ) {
  30017. const backgroundMaterial = new MeshBasicMaterial( {
  30018. name: 'PMREM.Background',
  30019. side: BackSide,
  30020. depthWrite: false,
  30021. depthTest: false
  30022. } );
  30023. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30024. }
  30025. let useSolidColor = false;
  30026. const background = scene.background;
  30027. if ( background ) {
  30028. if ( background.isColor ) {
  30029. backgroundBox.material.color.copy( background );
  30030. scene.background = null;
  30031. useSolidColor = true;
  30032. }
  30033. } else {
  30034. backgroundBox.material.color.copy( _clearColor );
  30035. useSolidColor = true;
  30036. }
  30037. renderer.setRenderTarget( cubeUVRenderTarget );
  30038. renderer.clear();
  30039. if ( useSolidColor ) {
  30040. renderer.render( backgroundBox, cubeCamera );
  30041. }
  30042. for ( let i = 0; i < 6; i ++ ) {
  30043. const col = i % 3;
  30044. if ( col === 0 ) {
  30045. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30046. cubeCamera.position.set( position.x, position.y, position.z );
  30047. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  30048. } else if ( col === 1 ) {
  30049. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30050. cubeCamera.position.set( position.x, position.y, position.z );
  30051. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  30052. } else {
  30053. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30054. cubeCamera.position.set( position.x, position.y, position.z );
  30055. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  30056. }
  30057. const size = this._cubeSize;
  30058. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30059. renderer.render( scene, cubeCamera );
  30060. }
  30061. renderer.autoClear = originalAutoClear;
  30062. scene.background = background;
  30063. }
  30064. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30065. const renderer = this._renderer;
  30066. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30067. if ( isCubeTexture ) {
  30068. if ( this._cubemapMaterial === null ) {
  30069. this._cubemapMaterial = _getCubemapMaterial( texture );
  30070. }
  30071. } else {
  30072. if ( this._equirectMaterial === null ) {
  30073. this._equirectMaterial = _getEquirectMaterial( texture );
  30074. }
  30075. }
  30076. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  30077. material.fragmentNode.value = texture;
  30078. const mesh = this._lodMeshes[ 0 ];
  30079. mesh.material = material;
  30080. const size = this._cubeSize;
  30081. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  30082. renderer.setRenderTarget( cubeUVRenderTarget );
  30083. renderer.render( mesh, _flatCamera );
  30084. }
  30085. _applyPMREM( cubeUVRenderTarget ) {
  30086. const renderer = this._renderer;
  30087. const autoClear = renderer.autoClear;
  30088. renderer.autoClear = false;
  30089. const n = this._lodPlanes.length;
  30090. for ( let i = 1; i < n; i ++ ) {
  30091. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  30092. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  30093. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  30094. }
  30095. renderer.autoClear = autoClear;
  30096. }
  30097. /**
  30098. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  30099. * vertically and horizontally, but this breaks down on a cube. Here we apply
  30100. * the blur latitudinally (around the poles), and then longitudinally (towards
  30101. * the poles) to approximate the orthogonally-separable blur. It is least
  30102. * accurate at the poles, but still does a decent job.
  30103. *
  30104. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  30105. * @param {number} lodIn - The input level-of-detail.
  30106. * @param {number} lodOut - The output level-of-detail.
  30107. * @param {number} sigma - The blur radius in radians.
  30108. * @param {Vector3} [poleAxis] - The pole axis.
  30109. */
  30110. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  30111. const pingPongRenderTarget = this._pingPongRenderTarget;
  30112. this._halfBlur(
  30113. cubeUVRenderTarget,
  30114. pingPongRenderTarget,
  30115. lodIn,
  30116. lodOut,
  30117. sigma,
  30118. 'latitudinal',
  30119. poleAxis );
  30120. this._halfBlur(
  30121. pingPongRenderTarget,
  30122. cubeUVRenderTarget,
  30123. lodOut,
  30124. lodOut,
  30125. sigma,
  30126. 'longitudinal',
  30127. poleAxis );
  30128. }
  30129. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  30130. const renderer = this._renderer;
  30131. const blurMaterial = this._blurMaterial;
  30132. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  30133. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  30134. }
  30135. // Number of standard deviations at which to cut off the discrete approximation.
  30136. const STANDARD_DEVIATIONS = 3;
  30137. const blurMesh = this._lodMeshes[ lodOut ];
  30138. blurMesh.material = blurMaterial;
  30139. const blurUniforms = _uniformsMap.get( blurMaterial );
  30140. const pixels = this._sizeLods[ lodIn ] - 1;
  30141. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  30142. const sigmaPixels = sigmaRadians / radiansPerPixel;
  30143. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  30144. if ( samples > MAX_SAMPLES ) {
  30145. console.warn( `sigmaRadians, ${
  30146. sigmaRadians}, is too large and will clip, as it requested ${
  30147. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  30148. }
  30149. const weights = [];
  30150. let sum = 0;
  30151. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  30152. const x = i / sigmaPixels;
  30153. const weight = Math.exp( - x * x / 2 );
  30154. weights.push( weight );
  30155. if ( i === 0 ) {
  30156. sum += weight;
  30157. } else if ( i < samples ) {
  30158. sum += 2 * weight;
  30159. }
  30160. }
  30161. for ( let i = 0; i < weights.length; i ++ ) {
  30162. weights[ i ] = weights[ i ] / sum;
  30163. }
  30164. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  30165. blurUniforms.envMap.value = targetIn.texture;
  30166. blurUniforms.samples.value = samples;
  30167. blurUniforms.weights.array = weights;
  30168. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  30169. if ( poleAxis ) {
  30170. blurUniforms.poleAxis.value = poleAxis;
  30171. }
  30172. const { _lodMax } = this;
  30173. blurUniforms.dTheta.value = radiansPerPixel;
  30174. blurUniforms.mipInt.value = _lodMax - lodIn;
  30175. const outputSize = this._sizeLods[ lodOut ];
  30176. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  30177. const y = 4 * ( this._cubeSize - outputSize );
  30178. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  30179. renderer.setRenderTarget( targetOut );
  30180. renderer.render( blurMesh, _flatCamera );
  30181. }
  30182. }
  30183. function _createPlanes( lodMax ) {
  30184. const lodPlanes = [];
  30185. const sizeLods = [];
  30186. const sigmas = [];
  30187. const lodMeshes = [];
  30188. let lod = lodMax;
  30189. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  30190. for ( let i = 0; i < totalLods; i ++ ) {
  30191. const sizeLod = Math.pow( 2, lod );
  30192. sizeLods.push( sizeLod );
  30193. let sigma = 1.0 / sizeLod;
  30194. if ( i > lodMax - LOD_MIN ) {
  30195. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  30196. } else if ( i === 0 ) {
  30197. sigma = 0;
  30198. }
  30199. sigmas.push( sigma );
  30200. const texelSize = 1.0 / ( sizeLod - 2 );
  30201. const min = - texelSize;
  30202. const max = 1 + texelSize;
  30203. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  30204. const cubeFaces = 6;
  30205. const vertices = 6;
  30206. const positionSize = 3;
  30207. const uvSize = 2;
  30208. const faceIndexSize = 1;
  30209. const position = new Float32Array( positionSize * vertices * cubeFaces );
  30210. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  30211. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  30212. for ( let face = 0; face < cubeFaces; face ++ ) {
  30213. const x = ( face % 3 ) * 2 / 3 - 1;
  30214. const y = face > 2 ? 0 : -1;
  30215. const coordinates = [
  30216. x, y, 0,
  30217. x + 2 / 3, y, 0,
  30218. x + 2 / 3, y + 1, 0,
  30219. x, y, 0,
  30220. x + 2 / 3, y + 1, 0,
  30221. x, y + 1, 0
  30222. ];
  30223. const faceIdx = _faceLib[ face ];
  30224. position.set( coordinates, positionSize * vertices * faceIdx );
  30225. uv.set( uv1, uvSize * vertices * faceIdx );
  30226. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  30227. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  30228. }
  30229. const planes = new BufferGeometry();
  30230. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  30231. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  30232. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  30233. lodPlanes.push( planes );
  30234. lodMeshes.push( new Mesh( planes, null ) );
  30235. if ( lod > LOD_MIN ) {
  30236. lod --;
  30237. }
  30238. }
  30239. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  30240. }
  30241. function _createRenderTarget( width, height, params ) {
  30242. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  30243. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  30244. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  30245. cubeUVRenderTarget.texture.isPMREMTexture = true;
  30246. cubeUVRenderTarget.scissorTest = true;
  30247. return cubeUVRenderTarget;
  30248. }
  30249. function _setViewport( target, x, y, width, height ) {
  30250. target.viewport.set( x, y, width, height );
  30251. target.scissor.set( x, y, width, height );
  30252. }
  30253. function _getMaterial( type ) {
  30254. const material = new NodeMaterial();
  30255. material.depthTest = false;
  30256. material.depthWrite = false;
  30257. material.blending = NoBlending;
  30258. material.name = `PMREM_${ type }`;
  30259. return material;
  30260. }
  30261. function _getBlurShader( lodMax, width, height ) {
  30262. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  30263. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  30264. const dTheta = uniform( 0 );
  30265. const n = float( MAX_SAMPLES );
  30266. const latitudinal = uniform( 0 ); // false, bool
  30267. const samples = uniform( 1 ); // int
  30268. const envMap = texture( null );
  30269. const mipInt = uniform( 0 ); // int
  30270. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  30271. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  30272. const CUBEUV_MAX_MIP = float( lodMax );
  30273. const materialUniforms = {
  30274. n,
  30275. latitudinal,
  30276. weights,
  30277. poleAxis,
  30278. outputDirection: _outputDirection,
  30279. dTheta,
  30280. samples,
  30281. envMap,
  30282. mipInt,
  30283. CUBEUV_TEXEL_WIDTH,
  30284. CUBEUV_TEXEL_HEIGHT,
  30285. CUBEUV_MAX_MIP
  30286. };
  30287. const material = _getMaterial( 'blur' );
  30288. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  30289. _uniformsMap.set( material, materialUniforms );
  30290. return material;
  30291. }
  30292. function _getCubemapMaterial( envTexture ) {
  30293. const material = _getMaterial( 'cubemap' );
  30294. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  30295. return material;
  30296. }
  30297. function _getEquirectMaterial( envTexture ) {
  30298. const material = _getMaterial( 'equirect' );
  30299. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  30300. return material;
  30301. }
  30302. const rendererCache = new WeakMap();
  30303. const typeFromArray = new Map( [
  30304. [ Int8Array, 'int' ],
  30305. [ Int16Array, 'int' ],
  30306. [ Int32Array, 'int' ],
  30307. [ Uint8Array, 'uint' ],
  30308. [ Uint16Array, 'uint' ],
  30309. [ Uint32Array, 'uint' ],
  30310. [ Float32Array, 'float' ]
  30311. ] );
  30312. const toFloat = ( value ) => {
  30313. if ( /e/g.test( value ) ) {
  30314. return String( value ).replace( /\+/g, '' );
  30315. } else {
  30316. value = Number( value );
  30317. return value + ( value % 1 ? '' : '.0' );
  30318. }
  30319. };
  30320. /**
  30321. * Base class for builders which generate a shader program based
  30322. * on a 3D object and its node material definition.
  30323. */
  30324. class NodeBuilder {
  30325. /**
  30326. * Constructs a new node builder.
  30327. *
  30328. * @param {Object3D} object - The 3D object.
  30329. * @param {Renderer} renderer - The current renderer.
  30330. * @param {NodeParser} parser - A reference to a node parser.
  30331. */
  30332. constructor( object, renderer, parser ) {
  30333. /**
  30334. * The 3D object.
  30335. *
  30336. * @type {Object3D}
  30337. */
  30338. this.object = object;
  30339. /**
  30340. * The material of the 3D object.
  30341. *
  30342. * @type {?Material}
  30343. */
  30344. this.material = ( object && object.material ) || null;
  30345. /**
  30346. * The geometry of the 3D object.
  30347. *
  30348. * @type {?BufferGeometry}
  30349. */
  30350. this.geometry = ( object && object.geometry ) || null;
  30351. /**
  30352. * The current renderer.
  30353. *
  30354. * @type {Renderer}
  30355. */
  30356. this.renderer = renderer;
  30357. /**
  30358. * A reference to a node parser.
  30359. *
  30360. * @type {NodeParser}
  30361. */
  30362. this.parser = parser;
  30363. /**
  30364. * The scene the 3D object belongs to.
  30365. *
  30366. * @type {?Scene}
  30367. * @default null
  30368. */
  30369. this.scene = null;
  30370. /**
  30371. * The camera the 3D object is rendered with.
  30372. *
  30373. * @type {?Camera}
  30374. * @default null
  30375. */
  30376. this.camera = null;
  30377. /**
  30378. * A list of all nodes the builder is processing
  30379. * for this 3D object.
  30380. *
  30381. * @type {Array<Node>}
  30382. */
  30383. this.nodes = [];
  30384. /**
  30385. * A list of all sequential nodes.
  30386. *
  30387. * @type {Array<Node>}
  30388. */
  30389. this.sequentialNodes = [];
  30390. /**
  30391. * A list of all nodes which {@link Node#update} method should be executed.
  30392. *
  30393. * @type {Array<Node>}
  30394. */
  30395. this.updateNodes = [];
  30396. /**
  30397. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  30398. *
  30399. * @type {Array<Node>}
  30400. */
  30401. this.updateBeforeNodes = [];
  30402. /**
  30403. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  30404. *
  30405. * @type {Array<Node>}
  30406. */
  30407. this.updateAfterNodes = [];
  30408. /**
  30409. * A dictionary that assigns each node to a unique hash.
  30410. *
  30411. * @type {Object<number,Node>}
  30412. */
  30413. this.hashNodes = {};
  30414. /**
  30415. * A reference to a node material observer.
  30416. *
  30417. * @type {?NodeMaterialObserver}
  30418. * @default null
  30419. */
  30420. this.observer = null;
  30421. /**
  30422. * A reference to the current lights node.
  30423. *
  30424. * @type {?LightsNode}
  30425. * @default null
  30426. */
  30427. this.lightsNode = null;
  30428. /**
  30429. * A reference to the current environment node.
  30430. *
  30431. * @type {?Node}
  30432. * @default null
  30433. */
  30434. this.environmentNode = null;
  30435. /**
  30436. * A reference to the current fog node.
  30437. *
  30438. * @type {?FogNode}
  30439. * @default null
  30440. */
  30441. this.fogNode = null;
  30442. /**
  30443. * The current clipping context.
  30444. *
  30445. * @type {?ClippingContext}
  30446. */
  30447. this.clippingContext = null;
  30448. /**
  30449. * The generated vertex shader.
  30450. *
  30451. * @type {?string}
  30452. */
  30453. this.vertexShader = null;
  30454. /**
  30455. * The generated fragment shader.
  30456. *
  30457. * @type {?string}
  30458. */
  30459. this.fragmentShader = null;
  30460. /**
  30461. * The generated compute shader.
  30462. *
  30463. * @type {?string}
  30464. */
  30465. this.computeShader = null;
  30466. /**
  30467. * Nodes used in the primary flow of code generation.
  30468. *
  30469. * @type {Object<string,Array<Node>>}
  30470. */
  30471. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30472. /**
  30473. * Nodes code from `.flowNodes`.
  30474. *
  30475. * @type {Object<string,string>}
  30476. */
  30477. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30478. /**
  30479. * This dictionary holds the node uniforms of the builder.
  30480. * The uniforms are maintained in an array for each shader stage.
  30481. *
  30482. * @type {Object}
  30483. */
  30484. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30485. /**
  30486. * This dictionary holds the output structs of the builder.
  30487. * The structs are maintained in an array for each shader stage.
  30488. *
  30489. * @type {Object}
  30490. */
  30491. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30492. /**
  30493. * This dictionary holds the bindings for each shader stage.
  30494. *
  30495. * @type {Object}
  30496. */
  30497. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30498. /**
  30499. * This dictionary maintains the binding indices per bind group.
  30500. *
  30501. * @type {Object}
  30502. */
  30503. this.bindingsIndexes = {};
  30504. /**
  30505. * Reference to the array of bind groups.
  30506. *
  30507. * @type {?Array<BindGroup>}
  30508. */
  30509. this.bindGroups = null;
  30510. /**
  30511. * This array holds the node attributes of this builder
  30512. * created via {@link AttributeNode}.
  30513. *
  30514. * @type {Array<NodeAttribute>}
  30515. */
  30516. this.attributes = [];
  30517. /**
  30518. * This array holds the node attributes of this builder
  30519. * created via {@link BufferAttributeNode}.
  30520. *
  30521. * @type {Array<NodeAttribute>}
  30522. */
  30523. this.bufferAttributes = [];
  30524. /**
  30525. * This array holds the node varyings of this builder.
  30526. *
  30527. * @type {Array<NodeVarying>}
  30528. */
  30529. this.varyings = [];
  30530. /**
  30531. * This dictionary holds the (native) node codes of this builder.
  30532. * The codes are maintained in an array for each shader stage.
  30533. *
  30534. * @type {Object<string,Array<NodeCode>>}
  30535. */
  30536. this.codes = {};
  30537. /**
  30538. * This dictionary holds the node variables of this builder.
  30539. * The variables are maintained in an array for each shader stage.
  30540. *
  30541. * @type {Object<string,Array<NodeVar>>}
  30542. */
  30543. this.vars = {};
  30544. /**
  30545. * Current code flow.
  30546. * All code generated in this stack will be stored in `.flow`.
  30547. *
  30548. * @type {{code: string}}
  30549. */
  30550. this.flow = { code: '' };
  30551. /**
  30552. * A chain of nodes.
  30553. * Used to check recursive calls in node-graph.
  30554. *
  30555. * @type {Array<Node>}
  30556. */
  30557. this.chaining = [];
  30558. /**
  30559. * The current stack.
  30560. * This reflects the current process in the code block hierarchy,
  30561. * it is useful to know if the current process is inside a conditional for example.
  30562. *
  30563. * @type {StackNode}
  30564. */
  30565. this.stack = stack();
  30566. /**
  30567. * List of stack nodes.
  30568. * The current stack hierarchy is stored in an array.
  30569. *
  30570. * @type {Array<StackNode>}
  30571. */
  30572. this.stacks = [];
  30573. /**
  30574. * A tab value. Used for shader string generation.
  30575. *
  30576. * @type {string}
  30577. * @default '\t'
  30578. */
  30579. this.tab = '\t';
  30580. /**
  30581. * Reference to the current function node.
  30582. *
  30583. * @type {?FunctionNode}
  30584. * @default null
  30585. */
  30586. this.currentFunctionNode = null;
  30587. /**
  30588. * The builder's context.
  30589. *
  30590. * @type {Object}
  30591. */
  30592. this.context = {
  30593. material: this.material
  30594. };
  30595. /**
  30596. * The builder's cache.
  30597. *
  30598. * @type {NodeCache}
  30599. */
  30600. this.cache = new NodeCache();
  30601. /**
  30602. * Since the {@link NodeBuilder#cache} might be temporarily
  30603. * overwritten by other caches, this member retains the reference
  30604. * to the builder's own cache.
  30605. *
  30606. * @type {NodeCache}
  30607. * @default this.cache
  30608. */
  30609. this.globalCache = this.cache;
  30610. this.flowsData = new WeakMap();
  30611. /**
  30612. * The current shader stage.
  30613. *
  30614. * @type {?('vertex'|'fragment'|'compute'|'any')}
  30615. */
  30616. this.shaderStage = null;
  30617. /**
  30618. * The current build stage.
  30619. *
  30620. * @type {?('setup'|'analyze'|'generate')}
  30621. */
  30622. this.buildStage = null;
  30623. /**
  30624. * Whether comparison in shader code are generated with methods or not.
  30625. *
  30626. * @type {boolean}
  30627. * @default false
  30628. */
  30629. this.useComparisonMethod = false;
  30630. }
  30631. /**
  30632. * Returns the bind groups of the current renderer.
  30633. *
  30634. * @return {ChainMap} The cache.
  30635. */
  30636. getBindGroupsCache() {
  30637. let bindGroupsCache = rendererCache.get( this.renderer );
  30638. if ( bindGroupsCache === undefined ) {
  30639. bindGroupsCache = new ChainMap();
  30640. rendererCache.set( this.renderer, bindGroupsCache );
  30641. }
  30642. return bindGroupsCache;
  30643. }
  30644. /**
  30645. * Factory method for creating an instance of {@link RenderTarget} with the given
  30646. * dimensions and options.
  30647. *
  30648. * @param {number} width - The width of the render target.
  30649. * @param {number} height - The height of the render target.
  30650. * @param {Object} options - The options of the render target.
  30651. * @return {RenderTarget} The render target.
  30652. */
  30653. createRenderTarget( width, height, options ) {
  30654. return new RenderTarget( width, height, options );
  30655. }
  30656. /**
  30657. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30658. * dimensions and options.
  30659. *
  30660. * @param {number} size - The size of the cube render target.
  30661. * @param {Object} options - The options of the cube render target.
  30662. * @return {CubeRenderTarget} The cube render target.
  30663. */
  30664. createCubeRenderTarget( size, options ) {
  30665. return new CubeRenderTarget( size, options );
  30666. }
  30667. /**
  30668. * Factory method for creating an instance of {@link PMREMGenerator}.
  30669. *
  30670. * @return {PMREMGenerator} The PMREM generator.
  30671. */
  30672. createPMREMGenerator() {
  30673. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30674. return new PMREMGenerator( this.renderer );
  30675. }
  30676. /**
  30677. * Whether the given node is included in the internal array of nodes or not.
  30678. *
  30679. * @param {Node} node - The node to test.
  30680. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  30681. */
  30682. includes( node ) {
  30683. return this.nodes.includes( node );
  30684. }
  30685. /**
  30686. * Returns the output struct name which is required by
  30687. * {@link OutputStructNode}.
  30688. *
  30689. * @abstract
  30690. * @return {string} The name of the output struct.
  30691. */
  30692. getOutputStructName() {}
  30693. /**
  30694. * Returns a bind group for the given group name and binding.
  30695. *
  30696. * @private
  30697. * @param {string} groupName - The group name.
  30698. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30699. * @return {BindGroup} The bind group
  30700. */
  30701. _getBindGroup( groupName, bindings ) {
  30702. const bindGroupsCache = this.getBindGroupsCache();
  30703. //
  30704. const bindingsArray = [];
  30705. let sharedGroup = true;
  30706. for ( const binding of bindings ) {
  30707. bindingsArray.push( binding );
  30708. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30709. }
  30710. //
  30711. let bindGroup;
  30712. if ( sharedGroup ) {
  30713. bindGroup = bindGroupsCache.get( bindingsArray );
  30714. if ( bindGroup === undefined ) {
  30715. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30716. bindGroupsCache.set( bindingsArray, bindGroup );
  30717. }
  30718. } else {
  30719. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30720. }
  30721. return bindGroup;
  30722. }
  30723. /**
  30724. * Returns an array of node uniform groups for the given group name and shader stage.
  30725. *
  30726. * @param {string} groupName - The group name.
  30727. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30728. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  30729. */
  30730. getBindGroupArray( groupName, shaderStage ) {
  30731. const bindings = this.bindings[ shaderStage ];
  30732. let bindGroup = bindings[ groupName ];
  30733. if ( bindGroup === undefined ) {
  30734. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30735. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30736. }
  30737. bindings[ groupName ] = bindGroup = [];
  30738. }
  30739. return bindGroup;
  30740. }
  30741. /**
  30742. * Returns a list bindings of all shader stages separated by groups.
  30743. *
  30744. * @return {Array<BindGroup>} The list of bindings.
  30745. */
  30746. getBindings() {
  30747. let bindingsGroups = this.bindGroups;
  30748. if ( bindingsGroups === null ) {
  30749. const groups = {};
  30750. const bindings = this.bindings;
  30751. for ( const shaderStage of shaderStages ) {
  30752. for ( const groupName in bindings[ shaderStage ] ) {
  30753. const uniforms = bindings[ shaderStage ][ groupName ];
  30754. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30755. groupUniforms.push( ...uniforms );
  30756. }
  30757. }
  30758. bindingsGroups = [];
  30759. for ( const groupName in groups ) {
  30760. const group = groups[ groupName ];
  30761. const bindingsGroup = this._getBindGroup( groupName, group );
  30762. bindingsGroups.push( bindingsGroup );
  30763. }
  30764. this.bindGroups = bindingsGroups;
  30765. }
  30766. return bindingsGroups;
  30767. }
  30768. /**
  30769. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30770. */
  30771. sortBindingGroups() {
  30772. const bindingsGroups = this.getBindings();
  30773. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30774. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30775. const bindingGroup = bindingsGroups[ i ];
  30776. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30777. bindingGroup.index = i;
  30778. }
  30779. }
  30780. /**
  30781. * The builder maintains each node in a hash-based dictionary.
  30782. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30783. *
  30784. * @param {Node} node - The node to add.
  30785. * @param {number} hash - The hash of the node.
  30786. */
  30787. setHashNode( node, hash ) {
  30788. this.hashNodes[ hash ] = node;
  30789. }
  30790. /**
  30791. * Adds a node to this builder.
  30792. *
  30793. * @param {Node} node - The node to add.
  30794. */
  30795. addNode( node ) {
  30796. if ( this.nodes.includes( node ) === false ) {
  30797. this.nodes.push( node );
  30798. this.setHashNode( node, node.getHash( this ) );
  30799. }
  30800. }
  30801. /**
  30802. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30803. * and need to follow a certain sequence in the calls to work correctly.
  30804. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30805. *
  30806. * @param {Node} node - The node to add.
  30807. */
  30808. addSequentialNode( node ) {
  30809. if ( this.sequentialNodes.includes( node ) === false ) {
  30810. this.sequentialNodes.push( node );
  30811. }
  30812. }
  30813. /**
  30814. * Checks the update types of nodes
  30815. */
  30816. buildUpdateNodes() {
  30817. for ( const node of this.nodes ) {
  30818. const updateType = node.getUpdateType();
  30819. if ( updateType !== NodeUpdateType.NONE ) {
  30820. this.updateNodes.push( node.getSelf() );
  30821. }
  30822. }
  30823. for ( const node of this.sequentialNodes ) {
  30824. const updateBeforeType = node.getUpdateBeforeType();
  30825. const updateAfterType = node.getUpdateAfterType();
  30826. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30827. this.updateBeforeNodes.push( node.getSelf() );
  30828. }
  30829. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30830. this.updateAfterNodes.push( node.getSelf() );
  30831. }
  30832. }
  30833. }
  30834. /**
  30835. * A reference the current node which is the
  30836. * last node in the chain of nodes.
  30837. *
  30838. * @type {Node}
  30839. */
  30840. get currentNode() {
  30841. return this.chaining[ this.chaining.length - 1 ];
  30842. }
  30843. /**
  30844. * Whether the given texture is filtered or not.
  30845. *
  30846. * @param {Texture} texture - The texture to check.
  30847. * @return {boolean} Whether the given texture is filtered or not.
  30848. */
  30849. isFilteredTexture( texture ) {
  30850. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30851. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30852. }
  30853. /**
  30854. * Adds the given node to the internal node chain.
  30855. * This is used to check recursive calls in node-graph.
  30856. *
  30857. * @param {Node} node - The node to add.
  30858. */
  30859. addChain( node ) {
  30860. /*
  30861. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30862. console.warn( 'Recursive node: ', node );
  30863. }
  30864. */
  30865. this.chaining.push( node );
  30866. }
  30867. /**
  30868. * Removes the given node from the internal node chain.
  30869. *
  30870. * @param {Node} node - The node to remove.
  30871. */
  30872. removeChain( node ) {
  30873. const lastChain = this.chaining.pop();
  30874. if ( lastChain !== node ) {
  30875. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30876. }
  30877. }
  30878. /**
  30879. * Returns the native shader method name for a given generic name. E.g.
  30880. * the method name `textureDimensions` matches the WGSL name but must be
  30881. * resolved to `textureSize` in GLSL.
  30882. *
  30883. * @abstract
  30884. * @param {string} method - The method name to resolve.
  30885. * @return {string} The resolved method name.
  30886. */
  30887. getMethod( method ) {
  30888. return method;
  30889. }
  30890. /**
  30891. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30892. *
  30893. * @param {number} hash - The hash of the node.
  30894. * @return {Node} The found node.
  30895. */
  30896. getNodeFromHash( hash ) {
  30897. return this.hashNodes[ hash ];
  30898. }
  30899. /**
  30900. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30901. *
  30902. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30903. * @param {Node} node - The node to add.
  30904. * @return {Node} The node.
  30905. */
  30906. addFlow( shaderStage, node ) {
  30907. this.flowNodes[ shaderStage ].push( node );
  30908. return node;
  30909. }
  30910. /**
  30911. * Sets builder's context.
  30912. *
  30913. * @param {Object} context - The context to set.
  30914. */
  30915. setContext( context ) {
  30916. this.context = context;
  30917. }
  30918. /**
  30919. * Returns the builder's current context.
  30920. *
  30921. * @return {Object} The builder's current context.
  30922. */
  30923. getContext() {
  30924. return this.context;
  30925. }
  30926. /**
  30927. * Gets a context used in shader construction that can be shared across different materials.
  30928. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30929. *
  30930. * @return {Object} The builder's current context without material.
  30931. */
  30932. getSharedContext() {
  30933. ({ ...this.context });
  30934. return this.context;
  30935. }
  30936. /**
  30937. * Sets builder's cache.
  30938. *
  30939. * @param {NodeCache} cache - The cache to set.
  30940. */
  30941. setCache( cache ) {
  30942. this.cache = cache;
  30943. }
  30944. /**
  30945. * Returns the builder's current cache.
  30946. *
  30947. * @return {NodeCache} The builder's current cache.
  30948. */
  30949. getCache() {
  30950. return this.cache;
  30951. }
  30952. /**
  30953. * Returns a cache for the given node.
  30954. *
  30955. * @param {Node} node - The node.
  30956. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30957. * @return {NodeCache} The cache.
  30958. */
  30959. getCacheFromNode( node, parent = true ) {
  30960. const data = this.getDataFromNode( node );
  30961. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30962. return data.cache;
  30963. }
  30964. /**
  30965. * Whether the requested feature is available or not.
  30966. *
  30967. * @abstract
  30968. * @param {string} name - The requested feature.
  30969. * @return {boolean} Whether the requested feature is supported or not.
  30970. */
  30971. isAvailable( /*name*/ ) {
  30972. return false;
  30973. }
  30974. /**
  30975. * Returns the vertexIndex input variable as a native shader string.
  30976. *
  30977. * @abstract
  30978. * @return {string} The instanceIndex shader string.
  30979. */
  30980. getVertexIndex() {
  30981. console.warn( 'Abstract function.' );
  30982. }
  30983. /**
  30984. * Returns the instanceIndex input variable as a native shader string.
  30985. *
  30986. * @abstract
  30987. * @return {string} The instanceIndex shader string.
  30988. */
  30989. getInstanceIndex() {
  30990. console.warn( 'Abstract function.' );
  30991. }
  30992. /**
  30993. * Returns the drawIndex input variable as a native shader string.
  30994. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30995. *
  30996. * @abstract
  30997. * @return {string} The drawIndex shader string.
  30998. */
  30999. getDrawIndex() {
  31000. console.warn( 'Abstract function.' );
  31001. }
  31002. /**
  31003. * Returns the frontFacing input variable as a native shader string.
  31004. *
  31005. * @abstract
  31006. * @return {string} The frontFacing shader string.
  31007. */
  31008. getFrontFacing() {
  31009. console.warn( 'Abstract function.' );
  31010. }
  31011. /**
  31012. * Returns the fragCoord input variable as a native shader string.
  31013. *
  31014. * @abstract
  31015. * @return {string} The fragCoord shader string.
  31016. */
  31017. getFragCoord() {
  31018. console.warn( 'Abstract function.' );
  31019. }
  31020. /**
  31021. * Whether to flip texture data along its vertical axis or not. WebGL needs
  31022. * this method evaluate to `true`, WebGPU to `false`.
  31023. *
  31024. * @abstract
  31025. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  31026. */
  31027. isFlipY() {
  31028. return false;
  31029. }
  31030. /**
  31031. * Calling this method increases the usage count for the given node by one.
  31032. *
  31033. * @param {Node} node - The node to increase the usage count for.
  31034. * @return {number} The updated usage count.
  31035. */
  31036. increaseUsage( node ) {
  31037. const nodeData = this.getDataFromNode( node );
  31038. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31039. return nodeData.usageCount;
  31040. }
  31041. /**
  31042. * Generates a texture sample shader string for the given texture data.
  31043. *
  31044. * @abstract
  31045. * @param {Texture} texture - The texture.
  31046. * @param {string} textureProperty - The texture property name.
  31047. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31048. * @return {string} The generated shader string.
  31049. */
  31050. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31051. console.warn( 'Abstract function.' );
  31052. }
  31053. /**
  31054. * Generates a texture LOD shader string for the given texture data.
  31055. *
  31056. * @abstract
  31057. * @param {Texture} texture - The texture.
  31058. * @param {string} textureProperty - The texture property name.
  31059. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31060. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  31061. * @param {string} levelSnippet - Snippet defining the mip level.
  31062. * @return {string} The generated shader string.
  31063. */
  31064. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  31065. console.warn( 'Abstract function.' );
  31066. }
  31067. /**
  31068. * Generates the array declaration string.
  31069. *
  31070. * @param {string} type - The type.
  31071. * @param {?number} [count] - The count.
  31072. * @return {string} The generated value as a shader string.
  31073. */
  31074. generateArrayDeclaration( type, count ) {
  31075. return this.getType( type ) + '[ ' + count + ' ]';
  31076. }
  31077. /**
  31078. * Generates the array shader string for the given type and value.
  31079. *
  31080. * @param {string} type - The type.
  31081. * @param {?number} [count] - The count.
  31082. * @param {?Array<Node>} [values=null] - The default values.
  31083. * @return {string} The generated value as a shader string.
  31084. */
  31085. generateArray( type, count, values = null ) {
  31086. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  31087. for ( let i = 0; i < count; i ++ ) {
  31088. const value = values ? values[ i ] : null;
  31089. if ( value !== null ) {
  31090. snippet += value.build( this, type );
  31091. } else {
  31092. snippet += this.generateConst( type );
  31093. }
  31094. if ( i < count - 1 ) snippet += ', ';
  31095. }
  31096. snippet += ' )';
  31097. return snippet;
  31098. }
  31099. /**
  31100. * Generates the struct shader string.
  31101. *
  31102. * @param {string} type - The type.
  31103. * @param {Array<Object>} [membersLayout] - The count.
  31104. * @param {?Array<Node>} [values=null] - The default values.
  31105. * @return {string} The generated value as a shader string.
  31106. */
  31107. generateStruct( type, membersLayout, values = null ) {
  31108. const snippets = [];
  31109. for ( const member of membersLayout ) {
  31110. const { name, type } = member;
  31111. if ( values && values[ name ] && values[ name ].isNode ) {
  31112. snippets.push( values[ name ].build( this, type ) );
  31113. } else {
  31114. snippets.push( this.generateConst( type ) );
  31115. }
  31116. }
  31117. return type + '( ' + snippets.join( ', ' ) + ' )';
  31118. }
  31119. /**
  31120. * Generates the shader string for the given type and value.
  31121. *
  31122. * @param {string} type - The type.
  31123. * @param {?any} [value=null] - The value.
  31124. * @return {string} The generated value as a shader string.
  31125. */
  31126. generateConst( type, value = null ) {
  31127. if ( value === null ) {
  31128. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31129. else if ( type === 'bool' ) value = false;
  31130. else if ( type === 'color' ) value = new Color();
  31131. else if ( type === 'vec2' ) value = new Vector2();
  31132. else if ( type === 'vec3' ) value = new Vector3();
  31133. else if ( type === 'vec4' ) value = new Vector4();
  31134. }
  31135. if ( type === 'float' ) return toFloat( value );
  31136. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31137. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31138. if ( type === 'bool' ) return value ? 'true' : 'false';
  31139. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31140. const typeLength = this.getTypeLength( type );
  31141. const componentType = this.getComponentType( type );
  31142. const generateConst = value => this.generateConst( componentType, value );
  31143. if ( typeLength === 2 ) {
  31144. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31145. } else if ( typeLength === 3 ) {
  31146. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31147. } else if ( typeLength === 4 ) {
  31148. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31149. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31150. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31151. } else if ( typeLength > 4 ) {
  31152. return `${ this.getType( type ) }()`;
  31153. }
  31154. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31155. }
  31156. /**
  31157. * It might be necessary to convert certain data types to different ones
  31158. * so this method can be used to hide the conversion.
  31159. *
  31160. * @param {string} type - The type.
  31161. * @return {string} The updated type.
  31162. */
  31163. getType( type ) {
  31164. if ( type === 'color' ) return 'vec3';
  31165. return type;
  31166. }
  31167. /**
  31168. * Whether the given attribute name is defined in the geometry or not.
  31169. *
  31170. * @param {string} name - The attribute name.
  31171. * @return {boolean} Whether the given attribute name is defined in the geometry.
  31172. */
  31173. hasGeometryAttribute( name ) {
  31174. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31175. }
  31176. /**
  31177. * Returns a node attribute for the given name and type.
  31178. *
  31179. * @param {string} name - The attribute's name.
  31180. * @param {string} type - The attribute's type.
  31181. * @return {NodeAttribute} The node attribute.
  31182. */
  31183. getAttribute( name, type ) {
  31184. const attributes = this.attributes;
  31185. // find attribute
  31186. for ( const attribute of attributes ) {
  31187. if ( attribute.name === name ) {
  31188. return attribute;
  31189. }
  31190. }
  31191. // create a new if no exist
  31192. const attribute = new NodeAttribute( name, type );
  31193. attributes.push( attribute );
  31194. return attribute;
  31195. }
  31196. /**
  31197. * Returns for the given node and shader stage the property name for the shader.
  31198. *
  31199. * @param {Node} node - The node.
  31200. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31201. * @return {string} The property name.
  31202. */
  31203. getPropertyName( node/*, shaderStage*/ ) {
  31204. return node.name;
  31205. }
  31206. /**
  31207. * Whether the given type is a vector type or not.
  31208. *
  31209. * @param {string} type - The type to check.
  31210. * @return {boolean} Whether the given type is a vector type or not.
  31211. */
  31212. isVector( type ) {
  31213. return /vec\d/.test( type );
  31214. }
  31215. /**
  31216. * Whether the given type is a matrix type or not.
  31217. *
  31218. * @param {string} type - The type to check.
  31219. * @return {boolean} Whether the given type is a matrix type or not.
  31220. */
  31221. isMatrix( type ) {
  31222. return /mat\d/.test( type );
  31223. }
  31224. /**
  31225. * Whether the given type is a reference type or not.
  31226. *
  31227. * @param {string} type - The type to check.
  31228. * @return {boolean} Whether the given type is a reference type or not.
  31229. */
  31230. isReference( type ) {
  31231. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31232. }
  31233. /**
  31234. * Checks if the given texture requires a manual conversion to the working color space.
  31235. *
  31236. * @abstract
  31237. * @param {Texture} texture - The texture to check.
  31238. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  31239. */
  31240. needsToWorkingColorSpace( /*texture*/ ) {
  31241. return false;
  31242. }
  31243. /**
  31244. * Returns the component type of a given texture.
  31245. *
  31246. * @param {Texture} texture - The texture.
  31247. * @return {string} The component type.
  31248. */
  31249. getComponentTypeFromTexture( texture ) {
  31250. const type = texture.type;
  31251. if ( texture.isDataTexture ) {
  31252. if ( type === IntType ) return 'int';
  31253. if ( type === UnsignedIntType ) return 'uint';
  31254. }
  31255. return 'float';
  31256. }
  31257. /**
  31258. * Returns the element type for a given type.
  31259. *
  31260. * @param {string} type - The type.
  31261. * @return {string} The element type.
  31262. */
  31263. getElementType( type ) {
  31264. if ( type === 'mat2' ) return 'vec2';
  31265. if ( type === 'mat3' ) return 'vec3';
  31266. if ( type === 'mat4' ) return 'vec4';
  31267. return this.getComponentType( type );
  31268. }
  31269. /**
  31270. * Returns the component type for a given type.
  31271. *
  31272. * @param {string} type - The type.
  31273. * @return {string} The component type.
  31274. */
  31275. getComponentType( type ) {
  31276. type = this.getVectorType( type );
  31277. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31278. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31279. if ( componentType === null ) return null;
  31280. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31281. if ( componentType[ 1 ] === 'i' ) return 'int';
  31282. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31283. return 'float';
  31284. }
  31285. /**
  31286. * Returns the vector type for a given type.
  31287. *
  31288. * @param {string} type - The type.
  31289. * @return {string} The vector type.
  31290. */
  31291. getVectorType( type ) {
  31292. if ( type === 'color' ) return 'vec3';
  31293. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31294. return type;
  31295. }
  31296. /**
  31297. * Returns the data type for the given the length and component type.
  31298. *
  31299. * @param {number} length - The length.
  31300. * @param {string} [componentType='float'] - The component type.
  31301. * @return {string} The type.
  31302. */
  31303. getTypeFromLength( length, componentType = 'float' ) {
  31304. if ( length === 1 ) return componentType;
  31305. let baseType = getTypeFromLength( length );
  31306. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31307. // fix edge case for mat2x2 being same size as vec4
  31308. if ( /mat2/.test( componentType ) === true ) {
  31309. baseType = baseType.replace( 'vec', 'mat' );
  31310. }
  31311. return prefix + baseType;
  31312. }
  31313. /**
  31314. * Returns the type for a given typed array.
  31315. *
  31316. * @param {TypedArray} array - The typed array.
  31317. * @return {string} The type.
  31318. */
  31319. getTypeFromArray( array ) {
  31320. return typeFromArray.get( array.constructor );
  31321. }
  31322. /**
  31323. * Returns the type for a given buffer attribute.
  31324. *
  31325. * @param {BufferAttribute} attribute - The buffer attribute.
  31326. * @return {string} The type.
  31327. */
  31328. getTypeFromAttribute( attribute ) {
  31329. let dataAttribute = attribute;
  31330. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31331. const array = dataAttribute.array;
  31332. const itemSize = attribute.itemSize;
  31333. const normalized = attribute.normalized;
  31334. let arrayType;
  31335. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31336. arrayType = this.getTypeFromArray( array );
  31337. }
  31338. return this.getTypeFromLength( itemSize, arrayType );
  31339. }
  31340. /**
  31341. * Returns the length for the given data type.
  31342. *
  31343. * @param {string} type - The data type.
  31344. * @return {number} The length.
  31345. */
  31346. getTypeLength( type ) {
  31347. const vecType = this.getVectorType( type );
  31348. const vecNum = /vec([2-4])/.exec( vecType );
  31349. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31350. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31351. if ( /mat2/.test( type ) === true ) return 4;
  31352. if ( /mat3/.test( type ) === true ) return 9;
  31353. if ( /mat4/.test( type ) === true ) return 16;
  31354. return 0;
  31355. }
  31356. /**
  31357. * Returns the vector type for a given matrix type.
  31358. *
  31359. * @param {string} type - The matrix type.
  31360. * @return {string} The vector type.
  31361. */
  31362. getVectorFromMatrix( type ) {
  31363. return type.replace( 'mat', 'vec' );
  31364. }
  31365. /**
  31366. * For a given type this method changes the component type to the
  31367. * given value. E.g. `vec4` should be changed to the new component type
  31368. * `uint` which results in `uvec4`.
  31369. *
  31370. * @param {string} type - The type.
  31371. * @param {string} newComponentType - The new component type.
  31372. * @return {string} The new type.
  31373. */
  31374. changeComponentType( type, newComponentType ) {
  31375. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31376. }
  31377. /**
  31378. * Returns the integer type pendant for the given type.
  31379. *
  31380. * @param {string} type - The type.
  31381. * @return {string} The integer type.
  31382. */
  31383. getIntegerType( type ) {
  31384. const componentType = this.getComponentType( type );
  31385. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31386. return this.changeComponentType( type, 'int' );
  31387. }
  31388. /**
  31389. * Adds a stack node to the internal stack.
  31390. *
  31391. * @return {StackNode} The added stack node.
  31392. */
  31393. addStack() {
  31394. this.stack = stack( this.stack );
  31395. this.stacks.push( getCurrentStack() || this.stack );
  31396. setCurrentStack( this.stack );
  31397. return this.stack;
  31398. }
  31399. /**
  31400. * Removes the last stack node from the internal stack.
  31401. *
  31402. * @return {StackNode} The removed stack node.
  31403. */
  31404. removeStack() {
  31405. const lastStack = this.stack;
  31406. this.stack = lastStack.parent;
  31407. setCurrentStack( this.stacks.pop() );
  31408. return lastStack;
  31409. }
  31410. /**
  31411. * The builder maintains (cached) data for each node during the building process. This method
  31412. * can be used to get these data for a specific shader stage and cache.
  31413. *
  31414. * @param {Node} node - The node to get the data for.
  31415. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31416. * @param {?NodeCache} cache - An optional cache.
  31417. * @return {Object} The node data.
  31418. */
  31419. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31420. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31421. let nodeData = cache.getData( node );
  31422. if ( nodeData === undefined ) {
  31423. nodeData = {};
  31424. cache.setData( node, nodeData );
  31425. }
  31426. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31427. return nodeData[ shaderStage ];
  31428. }
  31429. /**
  31430. * Returns the properties for the given node and shader stage.
  31431. *
  31432. * @param {Node} node - The node to get the properties for.
  31433. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  31434. * @return {Object} The node properties.
  31435. */
  31436. getNodeProperties( node, shaderStage = 'any' ) {
  31437. const nodeData = this.getDataFromNode( node, shaderStage );
  31438. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31439. }
  31440. /**
  31441. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  31442. *
  31443. * @param {BufferAttributeNode} node - The buffer attribute node.
  31444. * @param {string} type - The node type.
  31445. * @return {NodeAttribute} The node attribute.
  31446. */
  31447. getBufferAttributeFromNode( node, type ) {
  31448. const nodeData = this.getDataFromNode( node );
  31449. let bufferAttribute = nodeData.bufferAttribute;
  31450. if ( bufferAttribute === undefined ) {
  31451. const index = this.uniforms.index ++;
  31452. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31453. this.bufferAttributes.push( bufferAttribute );
  31454. nodeData.bufferAttribute = bufferAttribute;
  31455. }
  31456. return bufferAttribute;
  31457. }
  31458. /**
  31459. * Returns an instance of {@link StructType} for the given output struct node.
  31460. *
  31461. * @param {OutputStructNode} node - The output struct node.
  31462. * @param {Array<Object>} membersLayout - The output struct types.
  31463. * @param {?string} [name=null] - The name of the struct.
  31464. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31465. * @return {StructType} The struct type attribute.
  31466. */
  31467. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  31468. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31469. let structType = nodeData.structType;
  31470. if ( structType === undefined ) {
  31471. const index = this.structs.index ++;
  31472. if ( name === null ) name = 'StructType' + index;
  31473. structType = new StructType( name, membersLayout );
  31474. this.structs[ shaderStage ].push( structType );
  31475. nodeData.structType = structType;
  31476. }
  31477. return structType;
  31478. }
  31479. /**
  31480. * Returns an instance of {@link StructType} for the given output struct node.
  31481. *
  31482. * @param {OutputStructNode} node - The output struct node.
  31483. * @param {Array<Object>} membersLayout - The output struct types.
  31484. * @return {StructType} The struct type attribute.
  31485. */
  31486. getOutputStructTypeFromNode( node, membersLayout ) {
  31487. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  31488. structType.output = true;
  31489. return structType;
  31490. }
  31491. /**
  31492. * Returns an instance of {@link NodeUniform} for the given uniform node.
  31493. *
  31494. * @param {UniformNode} node - The uniform node.
  31495. * @param {string} type - The uniform type.
  31496. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31497. * @param {?string} name - The name of the uniform.
  31498. * @return {NodeUniform} The node uniform.
  31499. */
  31500. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31501. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31502. let nodeUniform = nodeData.uniform;
  31503. if ( nodeUniform === undefined ) {
  31504. const index = this.uniforms.index ++;
  31505. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31506. this.uniforms[ shaderStage ].push( nodeUniform );
  31507. nodeData.uniform = nodeUniform;
  31508. }
  31509. return nodeUniform;
  31510. }
  31511. /**
  31512. * Returns the array length.
  31513. *
  31514. * @param {Node} node - The node.
  31515. * @return {?number} The array length.
  31516. */
  31517. getArrayCount( node ) {
  31518. let count = null;
  31519. if ( node.isArrayNode ) count = node.count;
  31520. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  31521. return count;
  31522. }
  31523. /**
  31524. * Returns an instance of {@link NodeVar} for the given variable node.
  31525. *
  31526. * @param {VarNode} node - The variable node.
  31527. * @param {?string} name - The variable's name.
  31528. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  31529. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31530. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  31531. *
  31532. * @return {NodeVar} The node variable.
  31533. */
  31534. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  31535. const nodeData = this.getDataFromNode( node, shaderStage );
  31536. let nodeVar = nodeData.variable;
  31537. if ( nodeVar === undefined ) {
  31538. const idNS = readOnly ? '_const' : '_var';
  31539. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31540. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  31541. if ( name === null ) {
  31542. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  31543. this.vars[ idNS ] ++;
  31544. }
  31545. //
  31546. const count = this.getArrayCount( node );
  31547. nodeVar = new NodeVar( name, type, readOnly, count );
  31548. if ( ! readOnly ) {
  31549. vars.push( nodeVar );
  31550. }
  31551. nodeData.variable = nodeVar;
  31552. }
  31553. return nodeVar;
  31554. }
  31555. /**
  31556. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  31557. *
  31558. * @param {Node} node - The varying node.
  31559. * @return {boolean} Returns true if deterministic.
  31560. */
  31561. isDeterministic( node ) {
  31562. if ( node.isMathNode ) {
  31563. return this.isDeterministic( node.aNode ) &&
  31564. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  31565. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  31566. } else if ( node.isOperatorNode ) {
  31567. return this.isDeterministic( node.aNode ) &&
  31568. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  31569. } else if ( node.isArrayNode ) {
  31570. if ( node.values !== null ) {
  31571. for ( const n of node.values ) {
  31572. if ( ! this.isDeterministic( n ) ) {
  31573. return false;
  31574. }
  31575. }
  31576. }
  31577. return true;
  31578. } else if ( node.isConstNode ) {
  31579. return true;
  31580. }
  31581. return false;
  31582. }
  31583. /**
  31584. * Returns an instance of {@link NodeVarying} for the given varying node.
  31585. *
  31586. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  31587. * @param {?string} name - The varying's name.
  31588. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  31589. * @return {NodeVar} The node varying.
  31590. */
  31591. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31592. const nodeData = this.getDataFromNode( node, 'any' );
  31593. let nodeVarying = nodeData.varying;
  31594. if ( nodeVarying === undefined ) {
  31595. const varyings = this.varyings;
  31596. const index = varyings.length;
  31597. if ( name === null ) name = 'nodeVarying' + index;
  31598. nodeVarying = new NodeVarying( name, type );
  31599. varyings.push( nodeVarying );
  31600. nodeData.varying = nodeVarying;
  31601. }
  31602. return nodeVarying;
  31603. }
  31604. /**
  31605. * Returns an instance of {@link NodeCode} for the given code node.
  31606. *
  31607. * @param {CodeNode} node - The code node.
  31608. * @param {string} type - The node type.
  31609. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31610. * @return {NodeCode} The node code.
  31611. */
  31612. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31613. const nodeData = this.getDataFromNode( node );
  31614. let nodeCode = nodeData.code;
  31615. if ( nodeCode === undefined ) {
  31616. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31617. const index = codes.length;
  31618. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31619. codes.push( nodeCode );
  31620. nodeData.code = nodeCode;
  31621. }
  31622. return nodeCode;
  31623. }
  31624. /**
  31625. * Adds a code flow based on the code-block hierarchy.
  31626. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31627. * is only used inside one of these conditionals in the current shader stage.
  31628. *
  31629. * @param {Node} node - The node to add.
  31630. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31631. */
  31632. addFlowCodeHierarchy( node, nodeBlock ) {
  31633. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31634. let needsFlowCode = true;
  31635. let nodeBlockHierarchy = nodeBlock;
  31636. while ( nodeBlockHierarchy ) {
  31637. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31638. needsFlowCode = false;
  31639. break;
  31640. }
  31641. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31642. }
  31643. if ( needsFlowCode ) {
  31644. for ( const flowCode of flowCodes ) {
  31645. this.addLineFlowCode( flowCode );
  31646. }
  31647. }
  31648. }
  31649. /**
  31650. * Add a inline-code to the current flow code-block.
  31651. *
  31652. * @param {Node} node - The node to add.
  31653. * @param {string} code - The code to add.
  31654. * @param {Node} nodeBlock - Current ConditionalNode
  31655. */
  31656. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31657. const nodeData = this.getDataFromNode( node );
  31658. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31659. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31660. flowCodes.push( code );
  31661. codeBlock.set( nodeBlock, true );
  31662. }
  31663. /**
  31664. * Add a inline-code to the current flow.
  31665. *
  31666. * @param {string} code - The code to add.
  31667. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31668. * @return {NodeBuilder} A reference to this node builder.
  31669. */
  31670. addLineFlowCode( code, node = null ) {
  31671. if ( code === '' ) return this;
  31672. if ( node !== null && this.context.nodeBlock ) {
  31673. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31674. }
  31675. code = this.tab + code;
  31676. if ( ! /;\s*$/.test( code ) ) {
  31677. code = code + ';\n';
  31678. }
  31679. this.flow.code += code;
  31680. return this;
  31681. }
  31682. /**
  31683. * Adds a code to the current code flow.
  31684. *
  31685. * @param {string} code - Shader code.
  31686. * @return {NodeBuilder} A reference to this node builder.
  31687. */
  31688. addFlowCode( code ) {
  31689. this.flow.code += code;
  31690. return this;
  31691. }
  31692. /**
  31693. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31694. * Typically used in codes with If,Else.
  31695. *
  31696. * @return {NodeBuilder} A reference to this node builder.
  31697. */
  31698. addFlowTab() {
  31699. this.tab += '\t';
  31700. return this;
  31701. }
  31702. /**
  31703. * Removes a tab.
  31704. *
  31705. * @return {NodeBuilder} A reference to this node builder.
  31706. */
  31707. removeFlowTab() {
  31708. this.tab = this.tab.slice( 0, -1 );
  31709. return this;
  31710. }
  31711. /**
  31712. * Gets the current flow data based on a Node.
  31713. *
  31714. * @param {Node} node - Node that the flow was started.
  31715. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31716. * @return {Object} The flow data.
  31717. */
  31718. getFlowData( node/*, shaderStage*/ ) {
  31719. return this.flowsData.get( node );
  31720. }
  31721. /**
  31722. * Executes the node flow based on a root node to generate the final shader code.
  31723. *
  31724. * @param {Node} node - The node to execute.
  31725. * @return {Object} The code flow.
  31726. */
  31727. flowNode( node ) {
  31728. const output = node.getNodeType( this );
  31729. const flowData = this.flowChildNode( node, output );
  31730. this.flowsData.set( node, flowData );
  31731. return flowData;
  31732. }
  31733. /**
  31734. * Includes a node in the current function node.
  31735. *
  31736. * @param {Node} node - The node to include.
  31737. * @returns {void}
  31738. */
  31739. addInclude( node ) {
  31740. if ( this.currentFunctionNode !== null ) {
  31741. this.currentFunctionNode.includes.push( node );
  31742. }
  31743. }
  31744. /**
  31745. * Returns the native shader operator name for a given generic name.
  31746. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31747. *
  31748. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  31749. * @return {FunctionNode} The build function node.
  31750. */
  31751. buildFunctionNode( shaderNode ) {
  31752. const fn = new FunctionNode();
  31753. const previous = this.currentFunctionNode;
  31754. this.currentFunctionNode = fn;
  31755. fn.code = this.buildFunctionCode( shaderNode );
  31756. this.currentFunctionNode = previous;
  31757. return fn;
  31758. }
  31759. /**
  31760. * Generates a code flow based on a TSL function: Fn().
  31761. *
  31762. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  31763. * @return {Object}
  31764. */
  31765. flowShaderNode( shaderNode ) {
  31766. const layout = shaderNode.layout;
  31767. const inputs = {
  31768. [ Symbol.iterator ]() {
  31769. let index = 0;
  31770. const values = Object.values( this );
  31771. return {
  31772. next: () => ( {
  31773. value: values[ index ],
  31774. done: index ++ >= values.length
  31775. } )
  31776. };
  31777. }
  31778. };
  31779. for ( const input of layout.inputs ) {
  31780. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31781. }
  31782. //
  31783. shaderNode.layout = null;
  31784. const callNode = shaderNode.call( inputs );
  31785. const flowData = this.flowStagesNode( callNode, layout.type );
  31786. shaderNode.layout = layout;
  31787. return flowData;
  31788. }
  31789. /**
  31790. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  31791. *
  31792. * @param {Node} node - The node to execute.
  31793. * @param {?string} output - Expected output type. For example 'vec3'.
  31794. * @return {Object}
  31795. */
  31796. flowStagesNode( node, output = null ) {
  31797. const previousFlow = this.flow;
  31798. const previousVars = this.vars;
  31799. const previousCache = this.cache;
  31800. const previousBuildStage = this.buildStage;
  31801. const previousStack = this.stack;
  31802. const flow = {
  31803. code: ''
  31804. };
  31805. this.flow = flow;
  31806. this.vars = {};
  31807. this.cache = new NodeCache();
  31808. this.stack = stack();
  31809. for ( const buildStage of defaultBuildStages ) {
  31810. this.setBuildStage( buildStage );
  31811. flow.result = node.build( this, output );
  31812. }
  31813. flow.vars = this.getVars( this.shaderStage );
  31814. this.flow = previousFlow;
  31815. this.vars = previousVars;
  31816. this.cache = previousCache;
  31817. this.stack = previousStack;
  31818. this.setBuildStage( previousBuildStage );
  31819. return flow;
  31820. }
  31821. /**
  31822. * Returns the native shader operator name for a given generic name.
  31823. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31824. *
  31825. * @abstract
  31826. * @param {string} op - The operator name to resolve.
  31827. * @return {string} The resolved operator name.
  31828. */
  31829. getFunctionOperator( /* op */ ) {
  31830. return null;
  31831. }
  31832. /**
  31833. * Generates a code flow based on a child Node.
  31834. *
  31835. * @param {Node} node - The node to execute.
  31836. * @param {?string} output - Expected output type. For example 'vec3'.
  31837. * @return {Object} The code flow.
  31838. */
  31839. flowChildNode( node, output = null ) {
  31840. const previousFlow = this.flow;
  31841. const flow = {
  31842. code: ''
  31843. };
  31844. this.flow = flow;
  31845. flow.result = node.build( this, output );
  31846. this.flow = previousFlow;
  31847. return flow;
  31848. }
  31849. /**
  31850. * Executes a flow of code in a different stage.
  31851. *
  31852. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  31853. * return the value in fragment-stage even if it is being executed in an input fragment.
  31854. *
  31855. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31856. * @param {Node} node - The node to execute.
  31857. * @param {?string} output - Expected output type. For example 'vec3'.
  31858. * @param {?string} propertyName - The property name to assign the result.
  31859. * @return {Object}
  31860. */
  31861. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31862. const previousShaderStage = this.shaderStage;
  31863. this.setShaderStage( shaderStage );
  31864. const flowData = this.flowChildNode( node, output );
  31865. if ( propertyName !== null ) {
  31866. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31867. }
  31868. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31869. this.setShaderStage( previousShaderStage );
  31870. return flowData;
  31871. }
  31872. /**
  31873. * Returns an array holding all node attributes of this node builder.
  31874. *
  31875. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31876. */
  31877. getAttributesArray() {
  31878. return this.attributes.concat( this.bufferAttributes );
  31879. }
  31880. /**
  31881. * Returns the attribute definitions as a shader string for the given shader stage.
  31882. *
  31883. * @abstract
  31884. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31885. * @return {string} The attribute code section.
  31886. */
  31887. getAttributes( /*shaderStage*/ ) {
  31888. console.warn( 'Abstract function.' );
  31889. }
  31890. /**
  31891. * Returns the varying definitions as a shader string for the given shader stage.
  31892. *
  31893. * @abstract
  31894. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31895. * @return {string} The varying code section.
  31896. */
  31897. getVaryings( /*shaderStage*/ ) {
  31898. console.warn( 'Abstract function.' );
  31899. }
  31900. /**
  31901. * Returns a single variable definition as a shader string for the given variable type and name.
  31902. *
  31903. * @param {string} type - The variable's type.
  31904. * @param {string} name - The variable's name.
  31905. * @param {?number} [count=null] - The array length.
  31906. * @return {string} The shader string.
  31907. */
  31908. getVar( type, name, count = null ) {
  31909. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  31910. }
  31911. /**
  31912. * Returns the variable definitions as a shader string for the given shader stage.
  31913. *
  31914. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31915. * @return {string} The variable code section.
  31916. */
  31917. getVars( shaderStage ) {
  31918. let snippet = '';
  31919. const vars = this.vars[ shaderStage ];
  31920. if ( vars !== undefined ) {
  31921. for ( const variable of vars ) {
  31922. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31923. }
  31924. }
  31925. return snippet;
  31926. }
  31927. /**
  31928. * Returns the uniform definitions as a shader string for the given shader stage.
  31929. *
  31930. * @abstract
  31931. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31932. * @return {string} The uniform code section.
  31933. */
  31934. getUniforms( /*shaderStage*/ ) {
  31935. console.warn( 'Abstract function.' );
  31936. }
  31937. /**
  31938. * Returns the native code definitions as a shader string for the given shader stage.
  31939. *
  31940. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31941. * @return {string} The native code section.
  31942. */
  31943. getCodes( shaderStage ) {
  31944. const codes = this.codes[ shaderStage ];
  31945. let code = '';
  31946. if ( codes !== undefined ) {
  31947. for ( const nodeCode of codes ) {
  31948. code += nodeCode.code + '\n';
  31949. }
  31950. }
  31951. return code;
  31952. }
  31953. /**
  31954. * Returns the hash of this node builder.
  31955. *
  31956. * @return {string} The hash.
  31957. */
  31958. getHash() {
  31959. return this.vertexShader + this.fragmentShader + this.computeShader;
  31960. }
  31961. /**
  31962. * Sets the current shader stage.
  31963. *
  31964. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  31965. */
  31966. setShaderStage( shaderStage ) {
  31967. this.shaderStage = shaderStage;
  31968. }
  31969. /**
  31970. * Returns the current shader stage.
  31971. *
  31972. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  31973. */
  31974. getShaderStage() {
  31975. return this.shaderStage;
  31976. }
  31977. /**
  31978. * Sets the current build stage.
  31979. *
  31980. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  31981. */
  31982. setBuildStage( buildStage ) {
  31983. this.buildStage = buildStage;
  31984. }
  31985. /**
  31986. * Returns the current build stage.
  31987. *
  31988. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  31989. */
  31990. getBuildStage() {
  31991. return this.buildStage;
  31992. }
  31993. /**
  31994. * Controls the code build of the shader stages.
  31995. *
  31996. * @abstract
  31997. */
  31998. buildCode() {
  31999. console.warn( 'Abstract function.' );
  32000. }
  32001. /**
  32002. * Central build method which controls the build for the given object.
  32003. *
  32004. * @return {NodeBuilder} A reference to this node builder.
  32005. */
  32006. build() {
  32007. const { object, material, renderer } = this;
  32008. if ( material !== null ) {
  32009. let nodeMaterial = renderer.library.fromMaterial( material );
  32010. if ( nodeMaterial === null ) {
  32011. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  32012. nodeMaterial = new NodeMaterial();
  32013. }
  32014. nodeMaterial.build( this );
  32015. } else {
  32016. this.addFlow( 'compute', object );
  32017. }
  32018. // setup() -> stage 1: create possible new nodes and returns an output reference node
  32019. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  32020. // generate() -> stage 3: generate shader
  32021. for ( const buildStage of defaultBuildStages ) {
  32022. this.setBuildStage( buildStage );
  32023. if ( this.context.vertex && this.context.vertex.isNode ) {
  32024. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  32025. }
  32026. for ( const shaderStage of shaderStages ) {
  32027. this.setShaderStage( shaderStage );
  32028. const flowNodes = this.flowNodes[ shaderStage ];
  32029. for ( const node of flowNodes ) {
  32030. if ( buildStage === 'generate' ) {
  32031. this.flowNode( node );
  32032. } else {
  32033. node.build( this );
  32034. }
  32035. }
  32036. }
  32037. }
  32038. this.setBuildStage( null );
  32039. this.setShaderStage( null );
  32040. // stage 4: build code for a specific output
  32041. this.buildCode();
  32042. this.buildUpdateNodes();
  32043. return this;
  32044. }
  32045. /**
  32046. * Returns a uniform representation which is later used for UBO generation and rendering.
  32047. *
  32048. * @param {NodeUniform} uniformNode - The uniform node.
  32049. * @param {string} type - The requested type.
  32050. * @return {Uniform} The uniform.
  32051. */
  32052. getNodeUniform( uniformNode, type ) {
  32053. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  32054. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  32055. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  32056. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  32057. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  32058. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  32059. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  32060. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  32061. throw new Error( `Uniform "${type}" not declared.` );
  32062. }
  32063. /**
  32064. * Formats the given shader snippet from a given type into another one. E.g.
  32065. * this method might be used to convert a simple float string `"1.0"` into a
  32066. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  32067. *
  32068. * @param {string} snippet - The shader snippet.
  32069. * @param {string} fromType - The source type.
  32070. * @param {string} toType - The target type.
  32071. * @return {string} The updated shader string.
  32072. */
  32073. format( snippet, fromType, toType ) {
  32074. fromType = this.getVectorType( fromType );
  32075. toType = this.getVectorType( toType );
  32076. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  32077. return snippet;
  32078. }
  32079. const fromTypeLength = this.getTypeLength( fromType );
  32080. const toTypeLength = this.getTypeLength( toType );
  32081. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  32082. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  32083. }
  32084. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  32085. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  32086. }
  32087. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  32088. // @TODO: ignore for now
  32089. return snippet;
  32090. }
  32091. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  32092. // @TODO: ignore for now
  32093. return snippet;
  32094. }
  32095. if ( fromTypeLength === toTypeLength ) {
  32096. return `${ this.getType( toType ) }( ${ snippet } )`;
  32097. }
  32098. if ( fromTypeLength > toTypeLength ) {
  32099. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32100. }
  32101. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32102. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32103. }
  32104. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32105. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32106. }
  32107. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32108. // convert a number value to vector type, e.g:
  32109. // vec3( 1u ) -> vec3( float( 1u ) )
  32110. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32111. }
  32112. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32113. }
  32114. /**
  32115. * Returns a signature with the engine's current revision.
  32116. *
  32117. * @return {string} The signature.
  32118. */
  32119. getSignature() {
  32120. return `// Three.js r${ REVISION } - Node System\n`;
  32121. }
  32122. // Deprecated
  32123. /**
  32124. * @function
  32125. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  32126. *
  32127. * @param {string} [type='NodeMaterial'] - The node material type.
  32128. * @throws {Error}
  32129. */
  32130. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  32131. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  32132. }
  32133. }
  32134. /**
  32135. * Management class for updating nodes. The module tracks metrics like
  32136. * the elapsed time, delta time, the render and frame ID to correctly
  32137. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  32138. * and {@link Node#updateAfter} depending on the node's configuration.
  32139. */
  32140. class NodeFrame {
  32141. /**
  32142. * Constructs a new node fame.
  32143. */
  32144. constructor() {
  32145. /**
  32146. * The elapsed time in seconds.
  32147. *
  32148. * @type {number}
  32149. * @default 0
  32150. */
  32151. this.time = 0;
  32152. /**
  32153. * The delta time in seconds.
  32154. *
  32155. * @type {number}
  32156. * @default 0
  32157. */
  32158. this.deltaTime = 0;
  32159. /**
  32160. * The frame ID.
  32161. *
  32162. * @type {number}
  32163. * @default 0
  32164. */
  32165. this.frameId = 0;
  32166. /**
  32167. * The render ID.
  32168. *
  32169. * @type {number}
  32170. * @default 0
  32171. */
  32172. this.renderId = 0;
  32173. /**
  32174. * Used to control the {@link Node#update} call.
  32175. *
  32176. * @type {WeakMap<Node, Object>}
  32177. */
  32178. this.updateMap = new WeakMap();
  32179. /**
  32180. * Used to control the {@link Node#updateBefore} call.
  32181. *
  32182. * @type {WeakMap<Node, Object>}
  32183. */
  32184. this.updateBeforeMap = new WeakMap();
  32185. /**
  32186. * Used to control the {@link Node#updateAfter} call.
  32187. *
  32188. * @type {WeakMap<Node, Object>}
  32189. */
  32190. this.updateAfterMap = new WeakMap();
  32191. /**
  32192. * A reference to the current renderer.
  32193. *
  32194. * @type {?Renderer}
  32195. * @default null
  32196. */
  32197. this.renderer = null;
  32198. /**
  32199. * A reference to the current material.
  32200. *
  32201. * @type {?Material}
  32202. * @default null
  32203. */
  32204. this.material = null;
  32205. /**
  32206. * A reference to the current camera.
  32207. *
  32208. * @type {?Camera}
  32209. * @default null
  32210. */
  32211. this.camera = null;
  32212. /**
  32213. * A reference to the current 3D object.
  32214. *
  32215. * @type {?Object3D}
  32216. * @default null
  32217. */
  32218. this.object = null;
  32219. /**
  32220. * A reference to the current scene.
  32221. *
  32222. * @type {?Scene}
  32223. * @default null
  32224. */
  32225. this.scene = null;
  32226. }
  32227. /**
  32228. * Returns a dictionary for a given node and update map which
  32229. * is used to correctly call node update methods per frame or render.
  32230. *
  32231. * @private
  32232. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  32233. * @param {Node} nodeRef - The reference to the current node.
  32234. * @return {Object<string,WeakMap>} The dictionary.
  32235. */
  32236. _getMaps( referenceMap, nodeRef ) {
  32237. let maps = referenceMap.get( nodeRef );
  32238. if ( maps === undefined ) {
  32239. maps = {
  32240. renderMap: new WeakMap(),
  32241. frameMap: new WeakMap()
  32242. };
  32243. referenceMap.set( nodeRef, maps );
  32244. }
  32245. return maps;
  32246. }
  32247. /**
  32248. * This method executes the {@link Node#updateBefore} for the given node.
  32249. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  32250. * is only executed once per frame, render or object depending on the update
  32251. * type.
  32252. *
  32253. * @param {Node} node - The node that should be updated.
  32254. */
  32255. updateBeforeNode( node ) {
  32256. const updateType = node.getUpdateBeforeType();
  32257. const reference = node.updateReference( this );
  32258. if ( updateType === NodeUpdateType.FRAME ) {
  32259. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32260. if ( frameMap.get( reference ) !== this.frameId ) {
  32261. if ( node.updateBefore( this ) !== false ) {
  32262. frameMap.set( reference, this.frameId );
  32263. }
  32264. }
  32265. } else if ( updateType === NodeUpdateType.RENDER ) {
  32266. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32267. if ( renderMap.get( reference ) !== this.renderId ) {
  32268. if ( node.updateBefore( this ) !== false ) {
  32269. renderMap.set( reference, this.renderId );
  32270. }
  32271. }
  32272. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32273. node.updateBefore( this );
  32274. }
  32275. }
  32276. /**
  32277. * This method executes the {@link Node#updateAfter} for the given node.
  32278. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  32279. * is only executed once per frame, render or object depending on the update
  32280. * type.
  32281. *
  32282. * @param {Node} node - The node that should be updated.
  32283. */
  32284. updateAfterNode( node ) {
  32285. const updateType = node.getUpdateAfterType();
  32286. const reference = node.updateReference( this );
  32287. if ( updateType === NodeUpdateType.FRAME ) {
  32288. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32289. if ( frameMap.get( reference ) !== this.frameId ) {
  32290. if ( node.updateAfter( this ) !== false ) {
  32291. frameMap.set( reference, this.frameId );
  32292. }
  32293. }
  32294. } else if ( updateType === NodeUpdateType.RENDER ) {
  32295. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32296. if ( renderMap.get( reference ) !== this.renderId ) {
  32297. if ( node.updateAfter( this ) !== false ) {
  32298. renderMap.set( reference, this.renderId );
  32299. }
  32300. }
  32301. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32302. node.updateAfter( this );
  32303. }
  32304. }
  32305. /**
  32306. * This method executes the {@link Node#update} for the given node.
  32307. * It makes sure {@link Node#updateType} is honored meaning the update
  32308. * is only executed once per frame, render or object depending on the update
  32309. * type.
  32310. *
  32311. * @param {Node} node - The node that should be updated.
  32312. */
  32313. updateNode( node ) {
  32314. const updateType = node.getUpdateType();
  32315. const reference = node.updateReference( this );
  32316. if ( updateType === NodeUpdateType.FRAME ) {
  32317. const { frameMap } = this._getMaps( this.updateMap, reference );
  32318. if ( frameMap.get( reference ) !== this.frameId ) {
  32319. if ( node.update( this ) !== false ) {
  32320. frameMap.set( reference, this.frameId );
  32321. }
  32322. }
  32323. } else if ( updateType === NodeUpdateType.RENDER ) {
  32324. const { renderMap } = this._getMaps( this.updateMap, reference );
  32325. if ( renderMap.get( reference ) !== this.renderId ) {
  32326. if ( node.update( this ) !== false ) {
  32327. renderMap.set( reference, this.renderId );
  32328. }
  32329. }
  32330. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32331. node.update( this );
  32332. }
  32333. }
  32334. /**
  32335. * Updates the internal state of the node frame. This method is
  32336. * called by the renderer in its internal animation loop.
  32337. */
  32338. update() {
  32339. this.frameId ++;
  32340. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32341. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32342. this.lastTime = performance.now();
  32343. this.time += this.deltaTime;
  32344. }
  32345. }
  32346. /**
  32347. * Describes the input of a {@link NodeFunction}.
  32348. */
  32349. class NodeFunctionInput {
  32350. /**
  32351. * Constructs a new node function input.
  32352. *
  32353. * @param {string} type - The input type.
  32354. * @param {string} name - The input name.
  32355. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  32356. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  32357. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  32358. */
  32359. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32360. /**
  32361. * The input type.
  32362. *
  32363. * @type {string}
  32364. */
  32365. this.type = type;
  32366. /**
  32367. * The input name.
  32368. *
  32369. * @type {string}
  32370. */
  32371. this.name = name;
  32372. /**
  32373. * If the input is an Array, count will be the length.
  32374. *
  32375. * @type {?number}
  32376. * @default null
  32377. */
  32378. this.count = count;
  32379. /**
  32380. *The parameter qualifier (only relevant for GLSL).
  32381. *
  32382. * @type {('in'|'out'|'inout')}
  32383. * @default ''
  32384. */
  32385. this.qualifier = qualifier;
  32386. /**
  32387. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  32388. *
  32389. * @type {boolean}
  32390. * @default false
  32391. */
  32392. this.isConst = isConst;
  32393. }
  32394. }
  32395. NodeFunctionInput.isNodeFunctionInput = true;
  32396. /**
  32397. * Module for representing directional lights as nodes.
  32398. *
  32399. * @augments AnalyticLightNode
  32400. */
  32401. class DirectionalLightNode extends AnalyticLightNode {
  32402. static get type() {
  32403. return 'DirectionalLightNode';
  32404. }
  32405. /**
  32406. * Constructs a new directional light node.
  32407. *
  32408. * @param {?DirectionalLight} [light=null] - The directional light source.
  32409. */
  32410. constructor( light = null ) {
  32411. super( light );
  32412. }
  32413. setup( builder ) {
  32414. super.setup( builder );
  32415. const lightingModel = builder.context.lightingModel;
  32416. const lightColor = this.colorNode;
  32417. const lightDirection = lightTargetDirection( this.light );
  32418. const reflectedLight = builder.context.reflectedLight;
  32419. lightingModel.direct( {
  32420. lightDirection,
  32421. lightColor,
  32422. reflectedLight
  32423. }, builder.stack, builder );
  32424. }
  32425. }
  32426. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32427. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32428. let _ltcLib = null;
  32429. /**
  32430. * Module for representing rect area lights as nodes.
  32431. *
  32432. * @augments AnalyticLightNode
  32433. */
  32434. class RectAreaLightNode extends AnalyticLightNode {
  32435. static get type() {
  32436. return 'RectAreaLightNode';
  32437. }
  32438. /**
  32439. * Constructs a new rect area light node.
  32440. *
  32441. * @param {?RectAreaLight} [light=null] - The rect area light source.
  32442. */
  32443. constructor( light = null ) {
  32444. super( light );
  32445. /**
  32446. * Uniform node representing the half height of the are light.
  32447. *
  32448. * @type {UniformNode<vec3>}
  32449. */
  32450. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  32451. /**
  32452. * Uniform node representing the half width of the are light.
  32453. *
  32454. * @type {UniformNode<vec3>}
  32455. */
  32456. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  32457. /**
  32458. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  32459. * relies on `viewMatrix` which might vary per render call.
  32460. *
  32461. * @type {string}
  32462. * @default 'render'
  32463. */
  32464. this.updateType = NodeUpdateType.RENDER;
  32465. }
  32466. /**
  32467. * Overwritten to updated rect area light specific uniforms.
  32468. *
  32469. * @param {NodeFrame} frame - A reference to the current node frame.
  32470. */
  32471. update( frame ) {
  32472. super.update( frame );
  32473. const { light } = this;
  32474. const viewMatrix = frame.camera.matrixWorldInverse;
  32475. _matrix42.identity();
  32476. _matrix41.copy( light.matrixWorld );
  32477. _matrix41.premultiply( viewMatrix );
  32478. _matrix42.extractRotation( _matrix41 );
  32479. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32480. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32481. this.halfWidth.value.applyMatrix4( _matrix42 );
  32482. this.halfHeight.value.applyMatrix4( _matrix42 );
  32483. }
  32484. setup( builder ) {
  32485. super.setup( builder );
  32486. let ltc_1, ltc_2;
  32487. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32488. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  32489. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  32490. } else {
  32491. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  32492. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  32493. }
  32494. const { colorNode, light } = this;
  32495. const lightingModel = builder.context.lightingModel;
  32496. const lightPosition = lightViewPosition( light );
  32497. const reflectedLight = builder.context.reflectedLight;
  32498. lightingModel.directRectArea( {
  32499. lightColor: colorNode,
  32500. lightPosition,
  32501. halfWidth: this.halfWidth,
  32502. halfHeight: this.halfHeight,
  32503. reflectedLight,
  32504. ltc_1,
  32505. ltc_2
  32506. }, builder.stack, builder );
  32507. }
  32508. /**
  32509. * Used to configure the internal BRDF approximation texture data.
  32510. *
  32511. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  32512. */
  32513. static setLTC( ltc ) {
  32514. _ltcLib = ltc;
  32515. }
  32516. }
  32517. /**
  32518. * Module for representing spot lights as nodes.
  32519. *
  32520. * @augments AnalyticLightNode
  32521. */
  32522. class SpotLightNode extends AnalyticLightNode {
  32523. static get type() {
  32524. return 'SpotLightNode';
  32525. }
  32526. /**
  32527. * Constructs a new spot light node.
  32528. *
  32529. * @param {?SpotLight} [light=null] - The spot light source.
  32530. */
  32531. constructor( light = null ) {
  32532. super( light );
  32533. /**
  32534. * Uniform node representing the cone cosine.
  32535. *
  32536. * @type {UniformNode<float>}
  32537. */
  32538. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  32539. /**
  32540. * Uniform node representing the penumbra cosine.
  32541. *
  32542. * @type {UniformNode<float>}
  32543. */
  32544. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  32545. /**
  32546. * Uniform node representing the cutoff distance.
  32547. *
  32548. * @type {UniformNode<float>}
  32549. */
  32550. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32551. /**
  32552. * Uniform node representing the decay exponent.
  32553. *
  32554. * @type {UniformNode<float>}
  32555. */
  32556. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  32557. }
  32558. /**
  32559. * Overwritten to updated spot light specific uniforms.
  32560. *
  32561. * @param {NodeFrame} frame - A reference to the current node frame.
  32562. */
  32563. update( frame ) {
  32564. super.update( frame );
  32565. const { light } = this;
  32566. this.coneCosNode.value = Math.cos( light.angle );
  32567. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32568. this.cutoffDistanceNode.value = light.distance;
  32569. this.decayExponentNode.value = light.decay;
  32570. }
  32571. /**
  32572. * Computes the spot attenuation for the given angle.
  32573. *
  32574. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32575. * @return {Node<float>} The spot attenuation.
  32576. */
  32577. getSpotAttenuation( angleCosine ) {
  32578. const { coneCosNode, penumbraCosNode } = this;
  32579. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32580. }
  32581. setup( builder ) {
  32582. super.setup( builder );
  32583. const lightingModel = builder.context.lightingModel;
  32584. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32585. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32586. const lightDirection = lVector.normalize();
  32587. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32588. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32589. const lightDistance = lVector.length();
  32590. const lightAttenuation = getDistanceAttenuation( {
  32591. lightDistance,
  32592. cutoffDistance: cutoffDistanceNode,
  32593. decayExponent: decayExponentNode
  32594. } );
  32595. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32596. if ( light.map ) {
  32597. const spotLightCoord = lightProjectionUV( light );
  32598. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  32599. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  32600. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  32601. }
  32602. const reflectedLight = builder.context.reflectedLight;
  32603. lightingModel.direct( {
  32604. lightDirection,
  32605. lightColor,
  32606. reflectedLight
  32607. }, builder.stack, builder );
  32608. }
  32609. }
  32610. /**
  32611. * An IES version of the default spot light node.
  32612. *
  32613. * @augments SpotLightNode
  32614. */
  32615. class IESSpotLightNode extends SpotLightNode {
  32616. static get type() {
  32617. return 'IESSpotLightNode';
  32618. }
  32619. /**
  32620. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32621. *
  32622. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32623. * @return {Node<float>} The spot attenuation.
  32624. */
  32625. getSpotAttenuation( angleCosine ) {
  32626. const iesMap = this.light.iesMap;
  32627. let spotAttenuation = null;
  32628. if ( iesMap && iesMap.isTexture === true ) {
  32629. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32630. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32631. } else {
  32632. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32633. }
  32634. return spotAttenuation;
  32635. }
  32636. }
  32637. /**
  32638. * Module for representing ambient lights as nodes.
  32639. *
  32640. * @augments AnalyticLightNode
  32641. */
  32642. class AmbientLightNode extends AnalyticLightNode {
  32643. static get type() {
  32644. return 'AmbientLightNode';
  32645. }
  32646. /**
  32647. * Constructs a new ambient light node.
  32648. *
  32649. * @param {?AmbientLight} [light=null] - The ambient light source.
  32650. */
  32651. constructor( light = null ) {
  32652. super( light );
  32653. }
  32654. setup( { context } ) {
  32655. context.irradiance.addAssign( this.colorNode );
  32656. }
  32657. }
  32658. /**
  32659. * Module for representing hemisphere lights as nodes.
  32660. *
  32661. * @augments AnalyticLightNode
  32662. */
  32663. class HemisphereLightNode extends AnalyticLightNode {
  32664. static get type() {
  32665. return 'HemisphereLightNode';
  32666. }
  32667. /**
  32668. * Constructs a new hemisphere light node.
  32669. *
  32670. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  32671. */
  32672. constructor( light = null ) {
  32673. super( light );
  32674. /**
  32675. * Uniform node representing the light's position.
  32676. *
  32677. * @type {UniformNode<vec3>}
  32678. */
  32679. this.lightPositionNode = lightPosition( light );
  32680. /**
  32681. * A node representing the light's direction.
  32682. *
  32683. * @type {Node<vec3>}
  32684. */
  32685. this.lightDirectionNode = this.lightPositionNode.normalize();
  32686. /**
  32687. * Uniform node representing the light's ground color.
  32688. *
  32689. * @type {UniformNode<vec3>}
  32690. */
  32691. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32692. }
  32693. /**
  32694. * Overwritten to updated hemisphere light specific uniforms.
  32695. *
  32696. * @param {NodeFrame} frame - A reference to the current node frame.
  32697. */
  32698. update( frame ) {
  32699. const { light } = this;
  32700. super.update( frame );
  32701. this.lightPositionNode.object3d = light;
  32702. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32703. }
  32704. setup( builder ) {
  32705. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32706. const dotNL = normalView.dot( lightDirectionNode );
  32707. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32708. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32709. builder.context.irradiance.addAssign( irradiance );
  32710. }
  32711. }
  32712. /**
  32713. * Module for representing light probes as nodes.
  32714. *
  32715. * @augments AnalyticLightNode
  32716. */
  32717. class LightProbeNode extends AnalyticLightNode {
  32718. static get type() {
  32719. return 'LightProbeNode';
  32720. }
  32721. /**
  32722. * Constructs a new light probe node.
  32723. *
  32724. * @param {?LightProbe} [light=null] - The light probe.
  32725. */
  32726. constructor( light = null ) {
  32727. super( light );
  32728. const array = [];
  32729. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  32730. /**
  32731. * Light probe represented as a uniform of spherical harmonics.
  32732. *
  32733. * @type {UniformArrayNode}
  32734. */
  32735. this.lightProbe = uniformArray( array );
  32736. }
  32737. /**
  32738. * Overwritten to updated light probe specific uniforms.
  32739. *
  32740. * @param {NodeFrame} frame - A reference to the current node frame.
  32741. */
  32742. update( frame ) {
  32743. const { light } = this;
  32744. super.update( frame );
  32745. //
  32746. for ( let i = 0; i < 9; i ++ ) {
  32747. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  32748. }
  32749. }
  32750. setup( builder ) {
  32751. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  32752. builder.context.irradiance.addAssign( irradiance );
  32753. }
  32754. }
  32755. /**
  32756. * Base class for node parsers. A derived parser must be implemented
  32757. * for each supported native shader language.
  32758. */
  32759. class NodeParser {
  32760. /**
  32761. * The method parses the given native code an returns a node function.
  32762. *
  32763. * @abstract
  32764. * @param {string} source - The native shader code.
  32765. * @return {NodeFunction} A node function.
  32766. */
  32767. parseFunction( /*source*/ ) {
  32768. console.warn( 'Abstract function.' );
  32769. }
  32770. }
  32771. /**
  32772. * Base class for node functions. A derived module must be implemented
  32773. * for each supported native shader language. Similar to other `Node*` modules,
  32774. * this class is only relevant during the building process and not used
  32775. * in user-level code.
  32776. */
  32777. class NodeFunction {
  32778. /**
  32779. * Constructs a new node function.
  32780. *
  32781. * @param {string} type - The node type. This type is the return type of the node function.
  32782. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  32783. * @param {string} [name=''] - The function's name.
  32784. * @param {string} [precision=''] - The precision qualifier.
  32785. */
  32786. constructor( type, inputs, name = '', precision = '' ) {
  32787. /**
  32788. * The node type. This type is the return type of the node function.
  32789. *
  32790. * @type {string}
  32791. */
  32792. this.type = type;
  32793. /**
  32794. * The function's inputs.
  32795. *
  32796. * @type {Array<NodeFunctionInput>}
  32797. */
  32798. this.inputs = inputs;
  32799. /**
  32800. * The name of the uniform.
  32801. *
  32802. * @type {string}
  32803. * @default ''
  32804. */
  32805. this.name = name;
  32806. /**
  32807. * The precision qualifier.
  32808. *
  32809. * @type {string}
  32810. * @default ''
  32811. */
  32812. this.precision = precision;
  32813. }
  32814. /**
  32815. * This method returns the native code of the node function.
  32816. *
  32817. * @abstract
  32818. * @param {string} name - The function's name.
  32819. * @return {string} A shader code.
  32820. */
  32821. getCode( /*name = this.name*/ ) {
  32822. console.warn( 'Abstract function.' );
  32823. }
  32824. }
  32825. NodeFunction.isNodeFunction = true;
  32826. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  32827. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  32828. const pragmaMain = '#pragma main';
  32829. const parse$1 = ( source ) => {
  32830. source = source.trim();
  32831. const pragmaMainIndex = source.indexOf( pragmaMain );
  32832. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  32833. const declaration = mainCode.match( declarationRegexp$1 );
  32834. if ( declaration !== null && declaration.length === 5 ) {
  32835. // tokenizer
  32836. const inputsCode = declaration[ 4 ];
  32837. const propsMatches = [];
  32838. let nameMatch = null;
  32839. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  32840. propsMatches.push( nameMatch );
  32841. }
  32842. // parser
  32843. const inputs = [];
  32844. let i = 0;
  32845. while ( i < propsMatches.length ) {
  32846. const isConst = propsMatches[ i ][ 0 ] === 'const';
  32847. if ( isConst === true ) {
  32848. i ++;
  32849. }
  32850. let qualifier = propsMatches[ i ][ 0 ];
  32851. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  32852. i ++;
  32853. } else {
  32854. qualifier = '';
  32855. }
  32856. const type = propsMatches[ i ++ ][ 0 ];
  32857. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  32858. if ( Number.isNaN( count ) === false ) i ++;
  32859. else count = null;
  32860. const name = propsMatches[ i ++ ][ 0 ];
  32861. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  32862. }
  32863. //
  32864. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32865. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32866. const type = declaration[ 2 ];
  32867. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32868. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  32869. return {
  32870. type,
  32871. inputs,
  32872. name,
  32873. precision,
  32874. inputsCode,
  32875. blockCode,
  32876. headerCode
  32877. };
  32878. } else {
  32879. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32880. }
  32881. };
  32882. /**
  32883. * This class represents a GLSL node function.
  32884. *
  32885. * @augments NodeFunction
  32886. */
  32887. class GLSLNodeFunction extends NodeFunction {
  32888. /**
  32889. * Constructs a new GLSL node function.
  32890. *
  32891. * @param {string} source - The GLSL source.
  32892. */
  32893. constructor( source ) {
  32894. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32895. super( type, inputs, name, precision );
  32896. this.inputsCode = inputsCode;
  32897. this.blockCode = blockCode;
  32898. this.headerCode = headerCode;
  32899. }
  32900. /**
  32901. * This method returns the GLSL code of the node function.
  32902. *
  32903. * @param {string} [name=this.name] - The function's name.
  32904. * @return {string} The shader code.
  32905. */
  32906. getCode( name = this.name ) {
  32907. let code;
  32908. const blockCode = this.blockCode;
  32909. if ( blockCode !== '' ) {
  32910. const { type, inputsCode, headerCode, precision } = this;
  32911. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32912. if ( precision !== '' ) {
  32913. declarationCode = `${ precision } ${ declarationCode }`;
  32914. }
  32915. code = headerCode + declarationCode + blockCode;
  32916. } else {
  32917. // interface function
  32918. code = '';
  32919. }
  32920. return code;
  32921. }
  32922. }
  32923. /**
  32924. * A GLSL node parser.
  32925. *
  32926. * @augments NodeParser
  32927. */
  32928. class GLSLNodeParser extends NodeParser {
  32929. /**
  32930. * The method parses the given GLSL code an returns a node function.
  32931. *
  32932. * @param {string} source - The GLSL code.
  32933. * @return {GLSLNodeFunction} A node function.
  32934. */
  32935. parseFunction( source ) {
  32936. return new GLSLNodeFunction( source );
  32937. }
  32938. }
  32939. const _outputNodeMap = new WeakMap();
  32940. const _chainKeys$2 = [];
  32941. const _cacheKeyValues = [];
  32942. /**
  32943. * This renderer module manages node-related objects and is the
  32944. * primary interface between the renderer and the node system.
  32945. *
  32946. * @private
  32947. * @augments DataMap
  32948. */
  32949. class Nodes extends DataMap {
  32950. /**
  32951. * Constructs a new nodes management component.
  32952. *
  32953. * @param {Renderer} renderer - The renderer.
  32954. * @param {Backend} backend - The renderer's backend.
  32955. */
  32956. constructor( renderer, backend ) {
  32957. super();
  32958. /**
  32959. * The renderer.
  32960. *
  32961. * @type {Renderer}
  32962. */
  32963. this.renderer = renderer;
  32964. /**
  32965. * The renderer's backend.
  32966. *
  32967. * @type {Backend}
  32968. */
  32969. this.backend = backend;
  32970. /**
  32971. * The node frame.
  32972. *
  32973. * @type {Renderer}
  32974. */
  32975. this.nodeFrame = new NodeFrame();
  32976. /**
  32977. * A cache for managing node builder states.
  32978. *
  32979. * @type {Map<number,NodeBuilderState>}
  32980. */
  32981. this.nodeBuilderCache = new Map();
  32982. /**
  32983. * A cache for managing data cache key data.
  32984. *
  32985. * @type {ChainMap}
  32986. */
  32987. this.callHashCache = new ChainMap();
  32988. /**
  32989. * A cache for managing node uniforms group data.
  32990. *
  32991. * @type {ChainMap}
  32992. */
  32993. this.groupsData = new ChainMap();
  32994. /**
  32995. * A cache for managing node objects of
  32996. * scene properties like fog or environments.
  32997. *
  32998. * @type {Object<string,WeakMap>}
  32999. */
  33000. this.cacheLib = {};
  33001. }
  33002. /**
  33003. * Returns `true` if the given node uniforms group must be updated or not.
  33004. *
  33005. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  33006. * @return {boolean} Whether the node uniforms group requires an update or not.
  33007. */
  33008. updateGroup( nodeUniformsGroup ) {
  33009. const groupNode = nodeUniformsGroup.groupNode;
  33010. const name = groupNode.name;
  33011. // objectGroup is always updated
  33012. if ( name === objectGroup.name ) return true;
  33013. // renderGroup is updated once per render/compute call
  33014. if ( name === renderGroup.name ) {
  33015. const uniformsGroupData = this.get( nodeUniformsGroup );
  33016. const renderId = this.nodeFrame.renderId;
  33017. if ( uniformsGroupData.renderId !== renderId ) {
  33018. uniformsGroupData.renderId = renderId;
  33019. return true;
  33020. }
  33021. return false;
  33022. }
  33023. // frameGroup is updated once per frame
  33024. if ( name === frameGroup.name ) {
  33025. const uniformsGroupData = this.get( nodeUniformsGroup );
  33026. const frameId = this.nodeFrame.frameId;
  33027. if ( uniformsGroupData.frameId !== frameId ) {
  33028. uniformsGroupData.frameId = frameId;
  33029. return true;
  33030. }
  33031. return false;
  33032. }
  33033. // other groups are updated just when groupNode.needsUpdate is true
  33034. _chainKeys$2[ 0 ] = groupNode;
  33035. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  33036. let groupData = this.groupsData.get( _chainKeys$2 );
  33037. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  33038. _chainKeys$2.length = 0;
  33039. if ( groupData.version !== groupNode.version ) {
  33040. groupData.version = groupNode.version;
  33041. return true;
  33042. }
  33043. return false;
  33044. }
  33045. /**
  33046. * Returns the cache key for the given render object.
  33047. *
  33048. * @param {RenderObject} renderObject - The render object.
  33049. * @return {number} The cache key.
  33050. */
  33051. getForRenderCacheKey( renderObject ) {
  33052. return renderObject.initialCacheKey;
  33053. }
  33054. /**
  33055. * Returns a node builder state for the given render object.
  33056. *
  33057. * @param {RenderObject} renderObject - The render object.
  33058. * @return {NodeBuilderState} The node builder state.
  33059. */
  33060. getForRender( renderObject ) {
  33061. const renderObjectData = this.get( renderObject );
  33062. let nodeBuilderState = renderObjectData.nodeBuilderState;
  33063. if ( nodeBuilderState === undefined ) {
  33064. const { nodeBuilderCache } = this;
  33065. const cacheKey = this.getForRenderCacheKey( renderObject );
  33066. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  33067. if ( nodeBuilderState === undefined ) {
  33068. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  33069. nodeBuilder.scene = renderObject.scene;
  33070. nodeBuilder.material = renderObject.material;
  33071. nodeBuilder.camera = renderObject.camera;
  33072. nodeBuilder.context.material = renderObject.material;
  33073. nodeBuilder.lightsNode = renderObject.lightsNode;
  33074. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  33075. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  33076. nodeBuilder.clippingContext = renderObject.clippingContext;
  33077. nodeBuilder.build();
  33078. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33079. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  33080. }
  33081. nodeBuilderState.usedTimes ++;
  33082. renderObjectData.nodeBuilderState = nodeBuilderState;
  33083. }
  33084. return nodeBuilderState;
  33085. }
  33086. /**
  33087. * Deletes the given object from the internal data map
  33088. *
  33089. * @param {any} object - The object to delete.
  33090. * @return {?Object} The deleted dictionary.
  33091. */
  33092. delete( object ) {
  33093. if ( object.isRenderObject ) {
  33094. const nodeBuilderState = this.get( object ).nodeBuilderState;
  33095. nodeBuilderState.usedTimes --;
  33096. if ( nodeBuilderState.usedTimes === 0 ) {
  33097. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  33098. }
  33099. }
  33100. return super.delete( object );
  33101. }
  33102. /**
  33103. * Returns a node builder state for the given compute node.
  33104. *
  33105. * @param {Node} computeNode - The compute node.
  33106. * @return {NodeBuilderState} The node builder state.
  33107. */
  33108. getForCompute( computeNode ) {
  33109. const computeData = this.get( computeNode );
  33110. let nodeBuilderState = computeData.nodeBuilderState;
  33111. if ( nodeBuilderState === undefined ) {
  33112. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  33113. nodeBuilder.build();
  33114. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33115. computeData.nodeBuilderState = nodeBuilderState;
  33116. }
  33117. return nodeBuilderState;
  33118. }
  33119. /**
  33120. * Creates a node builder state for the given node builder.
  33121. *
  33122. * @private
  33123. * @param {NodeBuilder} nodeBuilder - The node builder.
  33124. * @return {NodeBuilderState} The node builder state.
  33125. */
  33126. _createNodeBuilderState( nodeBuilder ) {
  33127. return new NodeBuilderState(
  33128. nodeBuilder.vertexShader,
  33129. nodeBuilder.fragmentShader,
  33130. nodeBuilder.computeShader,
  33131. nodeBuilder.getAttributesArray(),
  33132. nodeBuilder.getBindings(),
  33133. nodeBuilder.updateNodes,
  33134. nodeBuilder.updateBeforeNodes,
  33135. nodeBuilder.updateAfterNodes,
  33136. nodeBuilder.observer,
  33137. nodeBuilder.transforms
  33138. );
  33139. }
  33140. /**
  33141. * Returns an environment node for the current configured
  33142. * scene environment.
  33143. *
  33144. * @param {Scene} scene - The scene.
  33145. * @return {Node} A node representing the current scene environment.
  33146. */
  33147. getEnvironmentNode( scene ) {
  33148. this.updateEnvironment( scene );
  33149. let environmentNode = null;
  33150. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  33151. environmentNode = scene.environmentNode;
  33152. } else {
  33153. const sceneData = this.get( scene );
  33154. if ( sceneData.environmentNode ) {
  33155. environmentNode = sceneData.environmentNode;
  33156. }
  33157. }
  33158. return environmentNode;
  33159. }
  33160. /**
  33161. * Returns a background node for the current configured
  33162. * scene background.
  33163. *
  33164. * @param {Scene} scene - The scene.
  33165. * @return {Node} A node representing the current scene background.
  33166. */
  33167. getBackgroundNode( scene ) {
  33168. this.updateBackground( scene );
  33169. let backgroundNode = null;
  33170. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  33171. backgroundNode = scene.backgroundNode;
  33172. } else {
  33173. const sceneData = this.get( scene );
  33174. if ( sceneData.backgroundNode ) {
  33175. backgroundNode = sceneData.backgroundNode;
  33176. }
  33177. }
  33178. return backgroundNode;
  33179. }
  33180. /**
  33181. * Returns a fog node for the current configured scene fog.
  33182. *
  33183. * @param {Scene} scene - The scene.
  33184. * @return {Node} A node representing the current scene fog.
  33185. */
  33186. getFogNode( scene ) {
  33187. this.updateFog( scene );
  33188. return scene.fogNode || this.get( scene ).fogNode || null;
  33189. }
  33190. /**
  33191. * Returns a cache key for the given scene and lights node.
  33192. * This key is used by `RenderObject` as a part of the dynamic
  33193. * cache key (a key that must be checked every time the render
  33194. * objects is drawn).
  33195. *
  33196. * @param {Scene} scene - The scene.
  33197. * @param {LightsNode} lightsNode - The lights node.
  33198. * @return {number} The cache key.
  33199. */
  33200. getCacheKey( scene, lightsNode ) {
  33201. _chainKeys$2[ 0 ] = scene;
  33202. _chainKeys$2[ 1 ] = lightsNode;
  33203. const callId = this.renderer.info.calls;
  33204. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  33205. if ( cacheKeyData.callId !== callId ) {
  33206. const environmentNode = this.getEnvironmentNode( scene );
  33207. const fogNode = this.getFogNode( scene );
  33208. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  33209. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  33210. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  33211. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  33212. cacheKeyData.callId = callId;
  33213. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  33214. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  33215. _cacheKeyValues.length = 0;
  33216. }
  33217. _chainKeys$2.length = 0;
  33218. return cacheKeyData.cacheKey;
  33219. }
  33220. /**
  33221. * A boolean that indicates whether tone mapping should be enabled
  33222. * or not.
  33223. *
  33224. * @type {boolean}
  33225. */
  33226. get isToneMappingState() {
  33227. return this.renderer.getRenderTarget() ? false : true;
  33228. }
  33229. /**
  33230. * If a scene background is configured, this method makes sure to
  33231. * represent the background with a corresponding node-based implementation.
  33232. *
  33233. * @param {Scene} scene - The scene.
  33234. */
  33235. updateBackground( scene ) {
  33236. const sceneData = this.get( scene );
  33237. const background = scene.background;
  33238. if ( background ) {
  33239. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  33240. if ( sceneData.background !== background || forceUpdate ) {
  33241. const backgroundNode = this.getCacheNode( 'background', background, () => {
  33242. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  33243. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  33244. return pmremTexture( background );
  33245. } else {
  33246. let envMap;
  33247. if ( background.isCubeTexture === true ) {
  33248. envMap = cubeTexture( background );
  33249. } else {
  33250. envMap = texture( background );
  33251. }
  33252. return cubeMapNode( envMap );
  33253. }
  33254. } else if ( background.isTexture === true ) {
  33255. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  33256. } else if ( background.isColor !== true ) {
  33257. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  33258. }
  33259. }, forceUpdate );
  33260. sceneData.backgroundNode = backgroundNode;
  33261. sceneData.background = background;
  33262. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  33263. }
  33264. } else if ( sceneData.backgroundNode ) {
  33265. delete sceneData.backgroundNode;
  33266. delete sceneData.background;
  33267. }
  33268. }
  33269. /**
  33270. * This method is part of the caching of nodes which are used to represents the
  33271. * scene's background, fog or environment.
  33272. *
  33273. * @param {string} type - The type of object to cache.
  33274. * @param {Object} object - The object.
  33275. * @param {Function} callback - A callback that produces a node representation for the given object.
  33276. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  33277. * @return {Node} The node representation.
  33278. */
  33279. getCacheNode( type, object, callback, forceUpdate = false ) {
  33280. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  33281. let node = nodeCache.get( object );
  33282. if ( node === undefined || forceUpdate ) {
  33283. node = callback();
  33284. nodeCache.set( object, node );
  33285. }
  33286. return node;
  33287. }
  33288. /**
  33289. * If a scene fog is configured, this method makes sure to
  33290. * represent the fog with a corresponding node-based implementation.
  33291. *
  33292. * @param {Scene} scene - The scene.
  33293. */
  33294. updateFog( scene ) {
  33295. const sceneData = this.get( scene );
  33296. const sceneFog = scene.fog;
  33297. if ( sceneFog ) {
  33298. if ( sceneData.fog !== sceneFog ) {
  33299. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  33300. if ( sceneFog.isFogExp2 ) {
  33301. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33302. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  33303. return fog( color, densityFogFactor( density ) );
  33304. } else if ( sceneFog.isFog ) {
  33305. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33306. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  33307. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  33308. return fog( color, rangeFogFactor( near, far ) );
  33309. } else {
  33310. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  33311. }
  33312. } );
  33313. sceneData.fogNode = fogNode;
  33314. sceneData.fog = sceneFog;
  33315. }
  33316. } else {
  33317. delete sceneData.fogNode;
  33318. delete sceneData.fog;
  33319. }
  33320. }
  33321. /**
  33322. * If a scene environment is configured, this method makes sure to
  33323. * represent the environment with a corresponding node-based implementation.
  33324. *
  33325. * @param {Scene} scene - The scene.
  33326. */
  33327. updateEnvironment( scene ) {
  33328. const sceneData = this.get( scene );
  33329. const environment = scene.environment;
  33330. if ( environment ) {
  33331. if ( sceneData.environment !== environment ) {
  33332. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  33333. if ( environment.isCubeTexture === true ) {
  33334. return cubeTexture( environment );
  33335. } else if ( environment.isTexture === true ) {
  33336. return texture( environment );
  33337. } else {
  33338. console.error( 'Nodes: Unsupported environment configuration.', environment );
  33339. }
  33340. } );
  33341. sceneData.environmentNode = environmentNode;
  33342. sceneData.environment = environment;
  33343. }
  33344. } else if ( sceneData.environmentNode ) {
  33345. delete sceneData.environmentNode;
  33346. delete sceneData.environment;
  33347. }
  33348. }
  33349. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  33350. const nodeFrame = this.nodeFrame;
  33351. nodeFrame.renderer = renderer;
  33352. nodeFrame.scene = scene;
  33353. nodeFrame.object = object;
  33354. nodeFrame.camera = camera;
  33355. nodeFrame.material = material;
  33356. return nodeFrame;
  33357. }
  33358. getNodeFrameForRender( renderObject ) {
  33359. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  33360. }
  33361. /**
  33362. * Returns the current output cache key.
  33363. *
  33364. * @return {string} The output cache key.
  33365. */
  33366. getOutputCacheKey() {
  33367. const renderer = this.renderer;
  33368. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  33369. }
  33370. /**
  33371. * Checks if the output configuration (tone mapping and color space) for
  33372. * the given target has changed.
  33373. *
  33374. * @param {Texture} outputTarget - The output target.
  33375. * @return {boolean} Whether the output configuration has changed or not.
  33376. */
  33377. hasOutputChange( outputTarget ) {
  33378. const cacheKey = _outputNodeMap.get( outputTarget );
  33379. return cacheKey !== this.getOutputCacheKey();
  33380. }
  33381. /**
  33382. * Returns a node that represents the output configuration (tone mapping and
  33383. * color space) for the current target.
  33384. *
  33385. * @param {Texture} outputTarget - The output target.
  33386. * @return {Node} The output node.
  33387. */
  33388. getOutputNode( outputTarget ) {
  33389. const renderer = this.renderer;
  33390. const cacheKey = this.getOutputCacheKey();
  33391. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  33392. _outputNodeMap.set( outputTarget, cacheKey );
  33393. return output;
  33394. }
  33395. /**
  33396. * Triggers the call of `updateBefore()` methods
  33397. * for all nodes of the given render object.
  33398. *
  33399. * @param {RenderObject} renderObject - The render object.
  33400. */
  33401. updateBefore( renderObject ) {
  33402. const nodeBuilder = renderObject.getNodeBuilderState();
  33403. for ( const node of nodeBuilder.updateBeforeNodes ) {
  33404. // update frame state for each node
  33405. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  33406. }
  33407. }
  33408. /**
  33409. * Triggers the call of `updateAfter()` methods
  33410. * for all nodes of the given render object.
  33411. *
  33412. * @param {RenderObject} renderObject - The render object.
  33413. */
  33414. updateAfter( renderObject ) {
  33415. const nodeBuilder = renderObject.getNodeBuilderState();
  33416. for ( const node of nodeBuilder.updateAfterNodes ) {
  33417. // update frame state for each node
  33418. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  33419. }
  33420. }
  33421. /**
  33422. * Triggers the call of `update()` methods
  33423. * for all nodes of the given compute node.
  33424. *
  33425. * @param {Node} computeNode - The compute node.
  33426. */
  33427. updateForCompute( computeNode ) {
  33428. const nodeFrame = this.getNodeFrame();
  33429. const nodeBuilder = this.getForCompute( computeNode );
  33430. for ( const node of nodeBuilder.updateNodes ) {
  33431. nodeFrame.updateNode( node );
  33432. }
  33433. }
  33434. /**
  33435. * Triggers the call of `update()` methods
  33436. * for all nodes of the given compute node.
  33437. *
  33438. * @param {RenderObject} renderObject - The render object.
  33439. */
  33440. updateForRender( renderObject ) {
  33441. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33442. const nodeBuilder = renderObject.getNodeBuilderState();
  33443. for ( const node of nodeBuilder.updateNodes ) {
  33444. nodeFrame.updateNode( node );
  33445. }
  33446. }
  33447. /**
  33448. * Returns `true` if the given render object requires a refresh.
  33449. *
  33450. * @param {RenderObject} renderObject - The render object.
  33451. * @return {boolean} Whether the given render object requires a refresh or not.
  33452. */
  33453. needsRefresh( renderObject ) {
  33454. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33455. const monitor = renderObject.getMonitor();
  33456. return monitor.needsRefresh( renderObject, nodeFrame );
  33457. }
  33458. /**
  33459. * Frees the internal resources.
  33460. */
  33461. dispose() {
  33462. super.dispose();
  33463. this.nodeFrame = new NodeFrame();
  33464. this.nodeBuilderCache = new Map();
  33465. this.cacheLib = {};
  33466. }
  33467. }
  33468. const _plane = /*@__PURE__*/ new Plane();
  33469. /**
  33470. * Represents the state that is used to perform clipping via clipping planes.
  33471. * There is a default clipping context for each render context. When the
  33472. * scene holds instances of `ClippingGroup`, there will be a context for each
  33473. * group.
  33474. *
  33475. * @private
  33476. */
  33477. class ClippingContext {
  33478. /**
  33479. * Constructs a new clipping context.
  33480. *
  33481. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  33482. */
  33483. constructor( parentContext = null ) {
  33484. /**
  33485. * The clipping context's version.
  33486. *
  33487. * @type {number}
  33488. * @readonly
  33489. */
  33490. this.version = 0;
  33491. /**
  33492. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  33493. *
  33494. * @type {?boolean}
  33495. * @default null
  33496. */
  33497. this.clipIntersection = null;
  33498. /**
  33499. * The clipping context's cache key.
  33500. *
  33501. * @type {string}
  33502. */
  33503. this.cacheKey = '';
  33504. /**
  33505. * Whether the shadow pass is active or not.
  33506. *
  33507. * @type {boolean}
  33508. * @default false
  33509. */
  33510. this.shadowPass = false;
  33511. /**
  33512. * The view normal matrix.
  33513. *
  33514. * @type {Matrix3}
  33515. */
  33516. this.viewNormalMatrix = new Matrix3();
  33517. /**
  33518. * Internal cache for maintaining clipping contexts.
  33519. *
  33520. * @type {WeakMap<ClippingGroup,ClippingContext>}
  33521. */
  33522. this.clippingGroupContexts = new WeakMap();
  33523. /**
  33524. * The intersection planes.
  33525. *
  33526. * @type {Array<Vector4>}
  33527. */
  33528. this.intersectionPlanes = [];
  33529. /**
  33530. * The intersection planes.
  33531. *
  33532. * @type {Array<Vector4>}
  33533. */
  33534. this.unionPlanes = [];
  33535. /**
  33536. * The version of the clipping context's parent context.
  33537. *
  33538. * @type {?number}
  33539. * @readonly
  33540. */
  33541. this.parentVersion = null;
  33542. if ( parentContext !== null ) {
  33543. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  33544. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  33545. this.shadowPass = parentContext.shadowPass;
  33546. this.viewMatrix = parentContext.viewMatrix;
  33547. }
  33548. }
  33549. /**
  33550. * Projects the given source clipping planes and writes the result into the
  33551. * destination array.
  33552. *
  33553. * @param {Array<Plane>} source - The source clipping planes.
  33554. * @param {Array<Vector4>} destination - The destination.
  33555. * @param {number} offset - The offset.
  33556. */
  33557. projectPlanes( source, destination, offset ) {
  33558. const l = source.length;
  33559. for ( let i = 0; i < l; i ++ ) {
  33560. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  33561. const v = destination[ offset + i ];
  33562. const normal = _plane.normal;
  33563. v.x = - normal.x;
  33564. v.y = - normal.y;
  33565. v.z = - normal.z;
  33566. v.w = _plane.constant;
  33567. }
  33568. }
  33569. /**
  33570. * Updates the root clipping context of a scene.
  33571. *
  33572. * @param {Scene} scene - The scene.
  33573. * @param {Camera} camera - The camera that is used to render the scene.
  33574. */
  33575. updateGlobal( scene, camera ) {
  33576. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  33577. this.viewMatrix = camera.matrixWorldInverse;
  33578. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  33579. }
  33580. /**
  33581. * Updates the clipping context.
  33582. *
  33583. * @param {ClippingContext} parentContext - The parent context.
  33584. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  33585. */
  33586. update( parentContext, clippingGroup ) {
  33587. let update = false;
  33588. if ( parentContext.version !== this.parentVersion ) {
  33589. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  33590. this.unionPlanes = Array.from( parentContext.unionPlanes );
  33591. this.parentVersion = parentContext.version;
  33592. }
  33593. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  33594. this.clipIntersection = clippingGroup.clipIntersection;
  33595. if ( this.clipIntersection ) {
  33596. this.unionPlanes.length = parentContext.unionPlanes.length;
  33597. } else {
  33598. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  33599. }
  33600. }
  33601. const srcClippingPlanes = clippingGroup.clippingPlanes;
  33602. const l = srcClippingPlanes.length;
  33603. let dstClippingPlanes;
  33604. let offset;
  33605. if ( this.clipIntersection ) {
  33606. dstClippingPlanes = this.intersectionPlanes;
  33607. offset = parentContext.intersectionPlanes.length;
  33608. } else {
  33609. dstClippingPlanes = this.unionPlanes;
  33610. offset = parentContext.unionPlanes.length;
  33611. }
  33612. if ( dstClippingPlanes.length !== offset + l ) {
  33613. dstClippingPlanes.length = offset + l;
  33614. for ( let i = 0; i < l; i ++ ) {
  33615. dstClippingPlanes[ offset + i ] = new Vector4();
  33616. }
  33617. update = true;
  33618. }
  33619. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33620. if ( update ) {
  33621. this.version ++;
  33622. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33623. }
  33624. }
  33625. /**
  33626. * Returns a clipping context for the given clipping group.
  33627. *
  33628. * @param {ClippingGroup} clippingGroup - The clipping group.
  33629. * @return {ClippingContext} The clipping context.
  33630. */
  33631. getGroupContext( clippingGroup ) {
  33632. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33633. let context = this.clippingGroupContexts.get( clippingGroup );
  33634. if ( context === undefined ) {
  33635. context = new ClippingContext( this );
  33636. this.clippingGroupContexts.set( clippingGroup, context );
  33637. }
  33638. context.update( this, clippingGroup );
  33639. return context;
  33640. }
  33641. /**
  33642. * The count of union clipping planes.
  33643. *
  33644. * @type {number}
  33645. * @readonly
  33646. */
  33647. get unionClippingCount() {
  33648. return this.unionPlanes.length;
  33649. }
  33650. }
  33651. /**
  33652. * This module is used to represent render bundles inside the renderer
  33653. * for further processing.
  33654. *
  33655. * @private
  33656. */
  33657. class RenderBundle {
  33658. /**
  33659. * Constructs a new bundle group.
  33660. *
  33661. * @param {BundleGroup} bundleGroup - The bundle group.
  33662. * @param {Camera} camera - The camera the bundle group is rendered with.
  33663. */
  33664. constructor( bundleGroup, camera ) {
  33665. this.bundleGroup = bundleGroup;
  33666. this.camera = camera;
  33667. }
  33668. }
  33669. const _chainKeys$1 = [];
  33670. /**
  33671. * This renderer module manages render bundles.
  33672. *
  33673. * @private
  33674. */
  33675. class RenderBundles {
  33676. /**
  33677. * Constructs a new render bundle management component.
  33678. */
  33679. constructor() {
  33680. /**
  33681. * A chain map for maintaining the render bundles.
  33682. *
  33683. * @type {ChainMap}
  33684. */
  33685. this.bundles = new ChainMap();
  33686. }
  33687. /**
  33688. * Returns a render bundle for the given bundle group and camera.
  33689. *
  33690. * @param {BundleGroup} bundleGroup - The bundle group.
  33691. * @param {Camera} camera - The camera the bundle group is rendered with.
  33692. * @return {RenderBundle} The render bundle.
  33693. */
  33694. get( bundleGroup, camera ) {
  33695. const bundles = this.bundles;
  33696. _chainKeys$1[ 0 ] = bundleGroup;
  33697. _chainKeys$1[ 1 ] = camera;
  33698. let bundle = bundles.get( _chainKeys$1 );
  33699. if ( bundle === undefined ) {
  33700. bundle = new RenderBundle( bundleGroup, camera );
  33701. bundles.set( _chainKeys$1, bundle );
  33702. }
  33703. _chainKeys$1.length = 0;
  33704. return bundle;
  33705. }
  33706. /**
  33707. * Frees all internal resources.
  33708. */
  33709. dispose() {
  33710. this.bundles = new ChainMap();
  33711. }
  33712. }
  33713. /**
  33714. * The purpose of a node library is to assign node implementations
  33715. * to existing library features. In `WebGPURenderer` lights, materials
  33716. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33717. * are implemented with node-based modules.
  33718. *
  33719. * @private
  33720. */
  33721. class NodeLibrary {
  33722. /**
  33723. * Constructs a new node library.
  33724. */
  33725. constructor() {
  33726. /**
  33727. * A weak map that maps lights to light nodes.
  33728. *
  33729. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  33730. */
  33731. this.lightNodes = new WeakMap();
  33732. /**
  33733. * A map that maps materials to node materials.
  33734. *
  33735. * @type {Map<string,NodeMaterial.constructor>}
  33736. */
  33737. this.materialNodes = new Map();
  33738. /**
  33739. * A map that maps tone mapping techniques (constants)
  33740. * to tone mapping node functions.
  33741. *
  33742. * @type {Map<number,Function>}
  33743. */
  33744. this.toneMappingNodes = new Map();
  33745. }
  33746. /**
  33747. * Returns a matching node material instance for the given material object.
  33748. *
  33749. * This method also assigns/copies the properties of the given material object
  33750. * to the node material. This is done to make sure the current material
  33751. * configuration carries over to the node version.
  33752. *
  33753. * @param {Material} material - A material.
  33754. * @return {NodeMaterial} The corresponding node material.
  33755. */
  33756. fromMaterial( material ) {
  33757. if ( material.isNodeMaterial ) return material;
  33758. let nodeMaterial = null;
  33759. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  33760. if ( nodeMaterialClass !== null ) {
  33761. nodeMaterial = new nodeMaterialClass();
  33762. for ( const key in material ) {
  33763. nodeMaterial[ key ] = material[ key ];
  33764. }
  33765. }
  33766. return nodeMaterial;
  33767. }
  33768. /**
  33769. * Adds a tone mapping node function for a tone mapping technique (constant).
  33770. *
  33771. * @param {Function} toneMappingNode - The tone mapping node function.
  33772. * @param {number} toneMapping - The tone mapping.
  33773. */
  33774. addToneMapping( toneMappingNode, toneMapping ) {
  33775. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  33776. }
  33777. /**
  33778. * Returns a tone mapping node function for a tone mapping technique (constant).
  33779. *
  33780. * @param {number} toneMapping - The tone mapping.
  33781. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  33782. */
  33783. getToneMappingFunction( toneMapping ) {
  33784. return this.toneMappingNodes.get( toneMapping ) || null;
  33785. }
  33786. /**
  33787. * Returns a node material class definition for a material type.
  33788. *
  33789. * @param {string} materialType - The material type.
  33790. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  33791. */
  33792. getMaterialNodeClass( materialType ) {
  33793. return this.materialNodes.get( materialType ) || null;
  33794. }
  33795. /**
  33796. * Adds a node material class definition for a given material type.
  33797. *
  33798. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  33799. * @param {string} materialClassType - The material type.
  33800. */
  33801. addMaterial( materialNodeClass, materialClassType ) {
  33802. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  33803. }
  33804. /**
  33805. * Returns a light node class definition for a light class definition.
  33806. *
  33807. * @param {Light.constructor} light - The light class definition.
  33808. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  33809. */
  33810. getLightNodeClass( light ) {
  33811. return this.lightNodes.get( light ) || null;
  33812. }
  33813. /**
  33814. * Adds a light node class definition for a given light class definition.
  33815. *
  33816. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  33817. * @param {Light.constructor} lightClass - The light class definition.
  33818. */
  33819. addLight( lightNodeClass, lightClass ) {
  33820. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  33821. }
  33822. /**
  33823. * Adds a node class definition for the given type to the provided type library.
  33824. *
  33825. * @param {any} nodeClass - The node class definition.
  33826. * @param {number|string} type - The object type.
  33827. * @param {Map} library - The type library.
  33828. */
  33829. addType( nodeClass, type, library ) {
  33830. if ( library.has( type ) ) {
  33831. console.warn( `Redefinition of node ${ type }` );
  33832. return;
  33833. }
  33834. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33835. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  33836. library.set( type, nodeClass );
  33837. }
  33838. /**
  33839. * Adds a node class definition for the given class definition to the provided type library.
  33840. *
  33841. * @param {any} nodeClass - The node class definition.
  33842. * @param {any} baseClass - The class definition.
  33843. * @param {WeakMap} library - The type library.
  33844. */
  33845. addClass( nodeClass, baseClass, library ) {
  33846. if ( library.has( baseClass ) ) {
  33847. console.warn( `Redefinition of node ${ baseClass.name }` );
  33848. return;
  33849. }
  33850. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33851. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  33852. library.set( baseClass, nodeClass );
  33853. }
  33854. }
  33855. const _defaultLights = /*@__PURE__*/ new LightsNode();
  33856. const _chainKeys = [];
  33857. /**
  33858. * This renderer module manages the lights nodes which are unique
  33859. * per scene and camera combination.
  33860. *
  33861. * The lights node itself is later configured in the render list
  33862. * with the actual lights from the scene.
  33863. *
  33864. * @private
  33865. * @augments ChainMap
  33866. */
  33867. class Lighting extends ChainMap {
  33868. /**
  33869. * Constructs a lighting management component.
  33870. */
  33871. constructor() {
  33872. super();
  33873. }
  33874. /**
  33875. * Creates a new lights node for the given array of lights.
  33876. *
  33877. * @param {Array<Light>} lights - The render object.
  33878. * @return {LightsNode} The lights node.
  33879. */
  33880. createNode( lights = [] ) {
  33881. return new LightsNode().setLights( lights );
  33882. }
  33883. /**
  33884. * Returns a lights node for the given scene and camera.
  33885. *
  33886. * @param {Scene} scene - The scene.
  33887. * @param {Camera} camera - The camera.
  33888. * @return {LightsNode} The lights node.
  33889. */
  33890. getNode( scene, camera ) {
  33891. // ignore post-processing
  33892. if ( scene.isQuadMesh ) return _defaultLights;
  33893. _chainKeys[ 0 ] = scene;
  33894. _chainKeys[ 1 ] = camera;
  33895. let node = this.get( _chainKeys );
  33896. if ( node === undefined ) {
  33897. node = this.createNode();
  33898. this.set( _chainKeys, node );
  33899. }
  33900. _chainKeys.length = 0;
  33901. return node;
  33902. }
  33903. }
  33904. /**
  33905. * A special type of render target that is used when rendering
  33906. * with the WebXR Device API.
  33907. *
  33908. * @private
  33909. * @augments RenderTarget
  33910. */
  33911. class XRRenderTarget extends RenderTarget {
  33912. /**
  33913. * Constructs a new XR render target.
  33914. *
  33915. * @param {number} [width=1] - The width of the render target.
  33916. * @param {number} [height=1] - The height of the render target.
  33917. * @param {Object} [options={}] - The configuration options.
  33918. */
  33919. constructor( width = 1, height = 1, options = {} ) {
  33920. super( width, height, options );
  33921. /**
  33922. * This flag can be used for type testing.
  33923. *
  33924. * @type {boolean}
  33925. * @readonly
  33926. * @default true
  33927. */
  33928. this.isXRRenderTarget = true;
  33929. /**
  33930. * Whether the attachments of the render target
  33931. * are defined by external textures. This flag is
  33932. * set to `true` when using the WebXR Layers API.
  33933. *
  33934. * @type {boolean}
  33935. * @default false
  33936. */
  33937. this.hasExternalTextures = false;
  33938. /**
  33939. * Whether a depth buffer should automatically be allocated
  33940. * for this XR render target or not.
  33941. *
  33942. * Allocating a depth buffer is the default behavior of XR render
  33943. * targets. However, when using the WebXR Layers API, this flag
  33944. * must be set to `false` when the `ignoreDepthValues` property of
  33945. * the projection layers evaluates to `false`.
  33946. *
  33947. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  33948. *
  33949. * @type {boolean}
  33950. * @default true
  33951. */
  33952. this.autoAllocateDepthBuffer = true;
  33953. }
  33954. copy( source ) {
  33955. super.copy( source );
  33956. this.hasExternalTextures = source.hasExternalTextures;
  33957. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  33958. return this;
  33959. }
  33960. }
  33961. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33962. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33963. /**
  33964. * The XR manager is built on top of the WebXR Device API to
  33965. * manage XR sessions with `WebGPURenderer`.
  33966. *
  33967. * XR is currently only supported with a WebGL 2 backend.
  33968. *
  33969. * @augments EventDispatcher
  33970. */
  33971. class XRManager extends EventDispatcher {
  33972. /**
  33973. * Constructs a new XR manager.
  33974. *
  33975. * @param {Renderer} renderer - The renderer.
  33976. */
  33977. constructor( renderer ) {
  33978. super();
  33979. /**
  33980. * This flag globally enables XR rendering.
  33981. *
  33982. * @type {boolean}
  33983. * @default false
  33984. */
  33985. this.enabled = false;
  33986. /**
  33987. * Whether the XR device is currently presenting or not.
  33988. *
  33989. * @type {boolean}
  33990. * @default false
  33991. * @readonly
  33992. */
  33993. this.isPresenting = false;
  33994. /**
  33995. * Whether the XR camera should automatically be updated or not.
  33996. *
  33997. * @type {boolean}
  33998. * @default true
  33999. */
  34000. this.cameraAutoUpdate = true;
  34001. /**
  34002. * The renderer.
  34003. *
  34004. * @private
  34005. * @type {Renderer}
  34006. */
  34007. this._renderer = renderer;
  34008. // camera
  34009. /**
  34010. * Represents the camera for the left eye.
  34011. *
  34012. * @private
  34013. * @type {PerspectiveCamera}
  34014. */
  34015. this._cameraL = new PerspectiveCamera();
  34016. this._cameraL.viewport = new Vector4();
  34017. /**
  34018. * Represents the camera for the right eye.
  34019. *
  34020. * @private
  34021. * @type {PerspectiveCamera}
  34022. */
  34023. this._cameraR = new PerspectiveCamera();
  34024. this._cameraR.viewport = new Vector4();
  34025. /**
  34026. * A list of cameras used for rendering the XR views.
  34027. *
  34028. * @private
  34029. * @type {Array<Camera>}
  34030. */
  34031. this._cameras = [ this._cameraL, this._cameraR ];
  34032. /**
  34033. * The main XR camera.
  34034. *
  34035. * @private
  34036. * @type {ArrayCamera}
  34037. */
  34038. this._cameraXR = new ArrayCamera();
  34039. /**
  34040. * The current near value of the XR camera.
  34041. *
  34042. * @private
  34043. * @type {?number}
  34044. * @default null
  34045. */
  34046. this._currentDepthNear = null;
  34047. /**
  34048. * The current far value of the XR camera.
  34049. *
  34050. * @private
  34051. * @type {?number}
  34052. * @default null
  34053. */
  34054. this._currentDepthFar = null;
  34055. /**
  34056. * A list of WebXR controllers requested by the application.
  34057. *
  34058. * @private
  34059. * @type {Array<WebXRController>}
  34060. */
  34061. this._controllers = [];
  34062. /**
  34063. * A list of XR input source. Each input source belongs to
  34064. * an instance of WebXRController.
  34065. *
  34066. * @private
  34067. * @type {Array<XRInputSource?>}
  34068. */
  34069. this._controllerInputSources = [];
  34070. /**
  34071. * The XR render target that represents the rendering destination
  34072. * during an active XR session.
  34073. *
  34074. * @private
  34075. * @type {?RenderTarget}
  34076. * @default null
  34077. */
  34078. this._xrRenderTarget = null;
  34079. /**
  34080. * The current animation context.
  34081. *
  34082. * @private
  34083. * @type {?Window}
  34084. * @default null
  34085. */
  34086. this._currentAnimationContext = null;
  34087. /**
  34088. * The current animation loop.
  34089. *
  34090. * @private
  34091. * @type {?Function}
  34092. * @default null
  34093. */
  34094. this._currentAnimationLoop = null;
  34095. /**
  34096. * The current pixel ratio.
  34097. *
  34098. * @private
  34099. * @type {?number}
  34100. * @default null
  34101. */
  34102. this._currentPixelRatio = null;
  34103. /**
  34104. * The current size of the renderer's canvas
  34105. * in logical pixel unit.
  34106. *
  34107. * @private
  34108. * @type {Vector2}
  34109. */
  34110. this._currentSize = new Vector2();
  34111. /**
  34112. * The default event listener for handling events inside a XR session.
  34113. *
  34114. * @private
  34115. * @type {Function}
  34116. */
  34117. this._onSessionEvent = onSessionEvent.bind( this );
  34118. /**
  34119. * The event listener for handling the end of a XR session.
  34120. *
  34121. * @private
  34122. * @type {Function}
  34123. */
  34124. this._onSessionEnd = onSessionEnd.bind( this );
  34125. /**
  34126. * The event listener for handling the `inputsourceschange` event.
  34127. *
  34128. * @private
  34129. * @type {Function}
  34130. */
  34131. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  34132. /**
  34133. * The animation loop which is used as a replacement for the default
  34134. * animation loop of the applicatio. It is only used when a XR session
  34135. * is active.
  34136. *
  34137. * @private
  34138. * @type {Function}
  34139. */
  34140. this._onAnimationFrame = onAnimationFrame.bind( this );
  34141. /**
  34142. * The current XR reference space.
  34143. *
  34144. * @private
  34145. * @type {?XRReferenceSpace}
  34146. * @default null
  34147. */
  34148. this._referenceSpace = null;
  34149. /**
  34150. * The current XR reference space type.
  34151. *
  34152. * @private
  34153. * @type {string}
  34154. * @default 'local-floor'
  34155. */
  34156. this._referenceSpaceType = 'local-floor';
  34157. /**
  34158. * A custom reference space defined by the application.
  34159. *
  34160. * @private
  34161. * @type {?XRReferenceSpace}
  34162. * @default null
  34163. */
  34164. this._customReferenceSpace = null;
  34165. /**
  34166. * The framebuffer scale factor.
  34167. *
  34168. * @private
  34169. * @type {number}
  34170. * @default 1
  34171. */
  34172. this._framebufferScaleFactor = 1;
  34173. /**
  34174. * The foveation factor.
  34175. *
  34176. * @private
  34177. * @type {number}
  34178. * @default 1
  34179. */
  34180. this._foveation = 1.0;
  34181. /**
  34182. * A reference to the current XR session.
  34183. *
  34184. * @private
  34185. * @type {?XRSession}
  34186. * @default null
  34187. */
  34188. this._session = null;
  34189. /**
  34190. * A reference to the current XR base layer.
  34191. *
  34192. * @private
  34193. * @type {?XRWebGLLayer}
  34194. * @default null
  34195. */
  34196. this._glBaseLayer = null;
  34197. /**
  34198. * A reference to the current XR binding.
  34199. *
  34200. * @private
  34201. * @type {?XRWebGLBinding}
  34202. * @default null
  34203. */
  34204. this._glBinding = null;
  34205. /**
  34206. * A reference to the current XR projection layer.
  34207. *
  34208. * @private
  34209. * @type {?XRProjectionLayer}
  34210. * @default null
  34211. */
  34212. this._glProjLayer = null;
  34213. /**
  34214. * A reference to the current XR frame.
  34215. *
  34216. * @private
  34217. * @type {?XRFrame}
  34218. * @default null
  34219. */
  34220. this._xrFrame = null;
  34221. /**
  34222. * Whether to use the WebXR Layers API or not.
  34223. *
  34224. * @private
  34225. * @type {boolean}
  34226. * @readonly
  34227. */
  34228. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  34229. }
  34230. /**
  34231. * Returns an instance of `THREE.Group` that represents the transformation
  34232. * of a XR controller in target ray space. The requested controller is defined
  34233. * by the given index.
  34234. *
  34235. * @param {number} index - The index of the XR controller.
  34236. * @return {Group} A group that represents the controller's transformation.
  34237. */
  34238. getController( index ) {
  34239. const controller = this._getController( index );
  34240. return controller.getTargetRaySpace();
  34241. }
  34242. /**
  34243. * Returns an instance of `THREE.Group` that represents the transformation
  34244. * of a XR controller in grip space. The requested controller is defined
  34245. * by the given index.
  34246. *
  34247. * @param {number} index - The index of the XR controller.
  34248. * @return {Group} A group that represents the controller's transformation.
  34249. */
  34250. getControllerGrip( index ) {
  34251. const controller = this._getController( index );
  34252. return controller.getGripSpace();
  34253. }
  34254. /**
  34255. * Returns an instance of `THREE.Group` that represents the transformation
  34256. * of a XR controller in hand space. The requested controller is defined
  34257. * by the given index.
  34258. *
  34259. * @param {number} index - The index of the XR controller.
  34260. * @return {Group} A group that represents the controller's transformation.
  34261. */
  34262. getHand( index ) {
  34263. const controller = this._getController( index );
  34264. return controller.getHandSpace();
  34265. }
  34266. /**
  34267. * Returns the foveation value.
  34268. *
  34269. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  34270. */
  34271. getFoveation() {
  34272. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  34273. return undefined;
  34274. }
  34275. return this._foveation;
  34276. }
  34277. /**
  34278. * Sets the foveation value.
  34279. *
  34280. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  34281. * and `1` means maximum foveation (the edges render at lower resolution).
  34282. */
  34283. setFoveation( foveation ) {
  34284. this._foveation = foveation;
  34285. if ( this._glProjLayer !== null ) {
  34286. this._glProjLayer.fixedFoveation = foveation;
  34287. }
  34288. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  34289. this._glBaseLayer.fixedFoveation = foveation;
  34290. }
  34291. }
  34292. /**
  34293. * Returns the framebuffer scale factor.
  34294. *
  34295. * @return {number} The framebuffer scale factor.
  34296. */
  34297. getFramebufferScaleFactor() {
  34298. return this._framebufferScaleFactor;
  34299. }
  34300. /**
  34301. * Sets the framebuffer scale factor.
  34302. *
  34303. * This method can not be used during a XR session.
  34304. *
  34305. * @param {number} factor - The framebuffer scale factor.
  34306. */
  34307. setFramebufferScaleFactor( factor ) {
  34308. this._framebufferScaleFactor = factor;
  34309. if ( this.isPresenting === true ) {
  34310. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  34311. }
  34312. }
  34313. /**
  34314. * Returns the reference space type.
  34315. *
  34316. * @return {string} The reference space type.
  34317. */
  34318. getReferenceSpaceType() {
  34319. return this._referenceSpaceType;
  34320. }
  34321. /**
  34322. * Sets the reference space type.
  34323. *
  34324. * This method can not be used during a XR session.
  34325. *
  34326. * @param {string} type - The reference space type.
  34327. */
  34328. setReferenceSpaceType( type ) {
  34329. this._referenceSpaceType = type;
  34330. if ( this.isPresenting === true ) {
  34331. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  34332. }
  34333. }
  34334. /**
  34335. * Returns the XR reference space.
  34336. *
  34337. * @return {XRReferenceSpace} The XR reference space.
  34338. */
  34339. getReferenceSpace() {
  34340. return this._customReferenceSpace || this._referenceSpace;
  34341. }
  34342. /**
  34343. * Sets a custom XR reference space.
  34344. *
  34345. * @param {XRReferenceSpace} space - The XR reference space.
  34346. */
  34347. setReferenceSpace( space ) {
  34348. this._customReferenceSpace = space;
  34349. }
  34350. /**
  34351. * Returns the XR camera.
  34352. *
  34353. * @return {ArrayCamera} The XR camera.
  34354. */
  34355. getCamera() {
  34356. return this._cameraXR;
  34357. }
  34358. /**
  34359. * Returns the environment blend mode from the current XR session.
  34360. *
  34361. * @return {?('opaque'|'additive'|'alpha-blend')} The environment blend mode. Returns `null` when used outside of a XR session.
  34362. */
  34363. getEnvironmentBlendMode() {
  34364. if ( this._session !== null ) {
  34365. return this._session.environmentBlendMode;
  34366. }
  34367. }
  34368. /**
  34369. * Returns the current XR frame.
  34370. *
  34371. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  34372. */
  34373. getFrame() {
  34374. return this._xrFrame;
  34375. }
  34376. /**
  34377. * Returns the current XR session.
  34378. *
  34379. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  34380. */
  34381. getSession() {
  34382. return this._session;
  34383. }
  34384. /**
  34385. * After a XR session has been requested usually with one of the `*Button` modules, it
  34386. * is injected into the renderer with this method. This method triggers the start of
  34387. * the actual XR rendering.
  34388. *
  34389. * @async
  34390. * @param {XRSession} session - The XR session to set.
  34391. * @return {Promise} A Promise that resolves when the session has been set.
  34392. */
  34393. async setSession( session ) {
  34394. const renderer = this._renderer;
  34395. const backend = renderer.backend;
  34396. const gl = renderer.getContext();
  34397. this._session = session;
  34398. if ( session !== null ) {
  34399. 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.' );
  34400. session.addEventListener( 'select', this._onSessionEvent );
  34401. session.addEventListener( 'selectstart', this._onSessionEvent );
  34402. session.addEventListener( 'selectend', this._onSessionEvent );
  34403. session.addEventListener( 'squeeze', this._onSessionEvent );
  34404. session.addEventListener( 'squeezestart', this._onSessionEvent );
  34405. session.addEventListener( 'squeezeend', this._onSessionEvent );
  34406. session.addEventListener( 'end', this._onSessionEnd );
  34407. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34408. await backend.makeXRCompatible();
  34409. this._currentPixelRatio = renderer.getPixelRatio();
  34410. renderer.getSize( this._currentSize );
  34411. this._currentAnimationContext = renderer._animation.getContext();
  34412. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  34413. renderer._animation.stop();
  34414. //
  34415. if ( this._useLayers === true ) {
  34416. // default path using XRWebGLBinding/XRProjectionLayer
  34417. let depthFormat = null;
  34418. let depthType = null;
  34419. let glDepthFormat = null;
  34420. if ( renderer.depth ) {
  34421. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  34422. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  34423. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  34424. }
  34425. const projectionlayerInit = {
  34426. colorFormat: gl.RGBA8,
  34427. depthFormat: glDepthFormat,
  34428. scaleFactor: this._framebufferScaleFactor
  34429. };
  34430. const glBinding = new XRWebGLBinding( session, gl );
  34431. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  34432. this._glBinding = glBinding;
  34433. this._glProjLayer = glProjLayer;
  34434. session.updateRenderState( { layers: [ glProjLayer ] } );
  34435. renderer.setPixelRatio( 1 );
  34436. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  34437. this._xrRenderTarget = new XRRenderTarget(
  34438. glProjLayer.textureWidth,
  34439. glProjLayer.textureHeight,
  34440. {
  34441. format: RGBAFormat,
  34442. type: UnsignedByteType,
  34443. colorSpace: renderer.outputColorSpace,
  34444. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  34445. stencilBuffer: renderer.stencil,
  34446. samples: renderer.samples
  34447. } );
  34448. this._xrRenderTarget.hasExternalTextures = true;
  34449. } else {
  34450. // fallback to XRWebGLLayer
  34451. const layerInit = {
  34452. antialias: renderer.samples > 0,
  34453. alpha: true,
  34454. depth: renderer.depth,
  34455. stencil: renderer.stencil,
  34456. framebufferScaleFactor: this.getFramebufferScaleFactor()
  34457. };
  34458. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  34459. this._glBaseLayer = glBaseLayer;
  34460. session.updateRenderState( { baseLayer: glBaseLayer } );
  34461. renderer.setPixelRatio( 1 );
  34462. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  34463. this._xrRenderTarget = new XRRenderTarget(
  34464. glBaseLayer.framebufferWidth,
  34465. glBaseLayer.framebufferHeight,
  34466. {
  34467. format: RGBAFormat,
  34468. type: UnsignedByteType,
  34469. colorSpace: renderer.outputColorSpace,
  34470. stencilBuffer: renderer.stencil
  34471. }
  34472. );
  34473. }
  34474. //
  34475. this.setFoveation( this.getFoveation() );
  34476. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  34477. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  34478. renderer._animation.setContext( session );
  34479. renderer._animation.start();
  34480. this.isPresenting = true;
  34481. this.dispatchEvent( { type: 'sessionstart' } );
  34482. }
  34483. }
  34484. /**
  34485. * This method is called by the renderer per frame and updates the XR camera
  34486. * and it sub cameras based on the given camera. The given camera is the "user"
  34487. * camera created on application level and used for non-XR rendering.
  34488. *
  34489. * @param {PerspectiveCamera} camera - The camera.
  34490. */
  34491. updateCamera( camera ) {
  34492. const session = this._session;
  34493. if ( session === null ) return;
  34494. const depthNear = camera.near;
  34495. const depthFar = camera.far;
  34496. const cameraXR = this._cameraXR;
  34497. const cameraL = this._cameraL;
  34498. const cameraR = this._cameraR;
  34499. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  34500. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  34501. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  34502. // Note that the new renderState won't apply until the next frame. See #18320
  34503. session.updateRenderState( {
  34504. depthNear: cameraXR.near,
  34505. depthFar: cameraXR.far
  34506. } );
  34507. this._currentDepthNear = cameraXR.near;
  34508. this._currentDepthFar = cameraXR.far;
  34509. }
  34510. cameraL.layers.mask = camera.layers.mask | 0b010;
  34511. cameraR.layers.mask = camera.layers.mask | 0b100;
  34512. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  34513. const parent = camera.parent;
  34514. const cameras = cameraXR.cameras;
  34515. updateCamera( cameraXR, parent );
  34516. for ( let i = 0; i < cameras.length; i ++ ) {
  34517. updateCamera( cameras[ i ], parent );
  34518. }
  34519. // update projection matrix for proper view frustum culling
  34520. if ( cameras.length === 2 ) {
  34521. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  34522. } else {
  34523. // assume single camera setup (AR)
  34524. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  34525. }
  34526. // update user camera and its children
  34527. updateUserCamera( camera, cameraXR, parent );
  34528. }
  34529. /**
  34530. * Returns a WebXR controller for the given controller index.
  34531. *
  34532. * @private
  34533. * @param {number} index - The controller index.
  34534. * @return {WebXRController} The XR controller.
  34535. */
  34536. _getController( index ) {
  34537. let controller = this._controllers[ index ];
  34538. if ( controller === undefined ) {
  34539. controller = new WebXRController();
  34540. this._controllers[ index ] = controller;
  34541. }
  34542. return controller;
  34543. }
  34544. }
  34545. /**
  34546. * Assumes 2 cameras that are parallel and share an X-axis, and that
  34547. * the cameras' projection and world matrices have already been set.
  34548. * And that near and far planes are identical for both cameras.
  34549. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  34550. *
  34551. * @param {ArrayCamera} camera - The camera to update.
  34552. * @param {PerspectiveCamera} cameraL - The left camera.
  34553. * @param {PerspectiveCamera} cameraR - The right camera.
  34554. */
  34555. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  34556. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  34557. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  34558. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  34559. const projL = cameraL.projectionMatrix.elements;
  34560. const projR = cameraR.projectionMatrix.elements;
  34561. // VR systems will have identical far and near planes, and
  34562. // most likely identical top and bottom frustum extents.
  34563. // Use the left camera for these values.
  34564. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  34565. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  34566. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  34567. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  34568. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  34569. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  34570. const left = near * leftFov;
  34571. const right = near * rightFov;
  34572. // Calculate the new camera's position offset from the
  34573. // left camera. xOffset should be roughly half `ipd`.
  34574. const zOffset = ipd / ( - leftFov + rightFov );
  34575. const xOffset = zOffset * - leftFov;
  34576. // TODO: Better way to apply this offset?
  34577. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  34578. camera.translateX( xOffset );
  34579. camera.translateZ( zOffset );
  34580. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  34581. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34582. // Check if the projection uses an infinite far plane.
  34583. if ( projL[ 10 ] === -1 ) {
  34584. // Use the projection matrix from the left eye.
  34585. // The camera offset is sufficient to include the view volumes
  34586. // of both eyes (assuming symmetric projections).
  34587. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  34588. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  34589. } else {
  34590. // Find the union of the frustum values of the cameras and scale
  34591. // the values so that the near plane's position does not change in world space,
  34592. // although must now be relative to the new union camera.
  34593. const near2 = near + zOffset;
  34594. const far2 = far + zOffset;
  34595. const left2 = left - xOffset;
  34596. const right2 = right + ( ipd - xOffset );
  34597. const top2 = topFov * far / far2 * near2;
  34598. const bottom2 = bottomFov * far / far2 * near2;
  34599. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  34600. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34601. }
  34602. }
  34603. /**
  34604. * Updates the world matrices for the given camera based on the parent 3D object.
  34605. *
  34606. * @inner
  34607. * @param {Camera} camera - The camera to update.
  34608. * @param {Object3D} parent - The parent 3D object.
  34609. */
  34610. function updateCamera( camera, parent ) {
  34611. if ( parent === null ) {
  34612. camera.matrixWorld.copy( camera.matrix );
  34613. } else {
  34614. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  34615. }
  34616. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34617. }
  34618. /**
  34619. * Updates the given camera with the transfomration of the XR camera and parent object.
  34620. *
  34621. * @inner
  34622. * @param {Camera} camera - The camera to update.
  34623. * @param {ArrayCamera} cameraXR - The XR camera.
  34624. * @param {Object3D} parent - The parent 3D object.
  34625. */
  34626. function updateUserCamera( camera, cameraXR, parent ) {
  34627. if ( parent === null ) {
  34628. camera.matrix.copy( cameraXR.matrixWorld );
  34629. } else {
  34630. camera.matrix.copy( parent.matrixWorld );
  34631. camera.matrix.invert();
  34632. camera.matrix.multiply( cameraXR.matrixWorld );
  34633. }
  34634. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34635. camera.updateMatrixWorld( true );
  34636. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  34637. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  34638. if ( camera.isPerspectiveCamera ) {
  34639. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  34640. camera.zoom = 1;
  34641. }
  34642. }
  34643. function onSessionEvent( event ) {
  34644. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  34645. if ( controllerIndex === -1 ) {
  34646. return;
  34647. }
  34648. const controller = this._controllers[ controllerIndex ];
  34649. if ( controller !== undefined ) {
  34650. const referenceSpace = this.getReferenceSpace();
  34651. controller.update( event.inputSource, event.frame, referenceSpace );
  34652. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  34653. }
  34654. }
  34655. function onSessionEnd() {
  34656. const session = this._session;
  34657. const renderer = this._renderer;
  34658. session.removeEventListener( 'select', this._onSessionEvent );
  34659. session.removeEventListener( 'selectstart', this._onSessionEvent );
  34660. session.removeEventListener( 'selectend', this._onSessionEvent );
  34661. session.removeEventListener( 'squeeze', this._onSessionEvent );
  34662. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  34663. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  34664. session.removeEventListener( 'end', this._onSessionEnd );
  34665. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34666. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34667. const inputSource = this._controllerInputSources[ i ];
  34668. if ( inputSource === null ) continue;
  34669. this._controllerInputSources[ i ] = null;
  34670. this._controllers[ i ].disconnect( inputSource );
  34671. }
  34672. this._currentDepthNear = null;
  34673. this._currentDepthFar = null;
  34674. // restore framebuffer/rendering state
  34675. renderer.backend.setXRTarget( null );
  34676. renderer.setOutputRenderTarget( null );
  34677. this._session = null;
  34678. this._xrRenderTarget = null;
  34679. //
  34680. this.isPresenting = false;
  34681. renderer._animation.stop();
  34682. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  34683. renderer._animation.setContext( this._currentAnimationContext );
  34684. renderer._animation.start();
  34685. renderer.setPixelRatio( this._currentPixelRatio );
  34686. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  34687. this.dispatchEvent( { type: 'sessionend' } );
  34688. }
  34689. function onInputSourcesChange( event ) {
  34690. const controllers = this._controllers;
  34691. const controllerInputSources = this._controllerInputSources;
  34692. // Notify disconnected
  34693. for ( let i = 0; i < event.removed.length; i ++ ) {
  34694. const inputSource = event.removed[ i ];
  34695. const index = controllerInputSources.indexOf( inputSource );
  34696. if ( index >= 0 ) {
  34697. controllerInputSources[ index ] = null;
  34698. controllers[ index ].disconnect( inputSource );
  34699. }
  34700. }
  34701. // Notify connected
  34702. for ( let i = 0; i < event.added.length; i ++ ) {
  34703. const inputSource = event.added[ i ];
  34704. let controllerIndex = controllerInputSources.indexOf( inputSource );
  34705. if ( controllerIndex === -1 ) {
  34706. // Assign input source a controller that currently has no input source
  34707. for ( let i = 0; i < controllers.length; i ++ ) {
  34708. if ( i >= controllerInputSources.length ) {
  34709. controllerInputSources.push( inputSource );
  34710. controllerIndex = i;
  34711. break;
  34712. } else if ( controllerInputSources[ i ] === null ) {
  34713. controllerInputSources[ i ] = inputSource;
  34714. controllerIndex = i;
  34715. break;
  34716. }
  34717. }
  34718. // If all controllers do currently receive input we ignore new ones
  34719. if ( controllerIndex === -1 ) break;
  34720. }
  34721. const controller = controllers[ controllerIndex ];
  34722. if ( controller ) {
  34723. controller.connect( inputSource );
  34724. }
  34725. }
  34726. }
  34727. function onAnimationFrame( time, frame ) {
  34728. if ( frame === undefined ) return;
  34729. const cameraXR = this._cameraXR;
  34730. const renderer = this._renderer;
  34731. const backend = renderer.backend;
  34732. const glBaseLayer = this._glBaseLayer;
  34733. const referenceSpace = this.getReferenceSpace();
  34734. const pose = frame.getViewerPose( referenceSpace );
  34735. this._xrFrame = frame;
  34736. if ( pose !== null ) {
  34737. const views = pose.views;
  34738. if ( this._glBaseLayer !== null ) {
  34739. backend.setXRTarget( glBaseLayer.framebuffer );
  34740. }
  34741. let cameraXRNeedsUpdate = false;
  34742. // check if it's necessary to rebuild cameraXR's camera list
  34743. if ( views.length !== cameraXR.cameras.length ) {
  34744. cameraXR.cameras.length = 0;
  34745. cameraXRNeedsUpdate = true;
  34746. }
  34747. for ( let i = 0; i < views.length; i ++ ) {
  34748. const view = views[ i ];
  34749. let viewport;
  34750. if ( this._useLayers === true ) {
  34751. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  34752. viewport = glSubImage.viewport;
  34753. // For side-by-side projection, we only produce a single texture for both eyes.
  34754. if ( i === 0 ) {
  34755. backend.setXRRenderTargetTextures(
  34756. this._xrRenderTarget,
  34757. glSubImage.colorTexture,
  34758. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  34759. );
  34760. }
  34761. } else {
  34762. viewport = glBaseLayer.getViewport( view );
  34763. }
  34764. let camera = this._cameras[ i ];
  34765. if ( camera === undefined ) {
  34766. camera = new PerspectiveCamera();
  34767. camera.layers.enable( i );
  34768. camera.viewport = new Vector4();
  34769. this._cameras[ i ] = camera;
  34770. }
  34771. camera.matrix.fromArray( view.transform.matrix );
  34772. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34773. camera.projectionMatrix.fromArray( view.projectionMatrix );
  34774. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34775. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  34776. if ( i === 0 ) {
  34777. cameraXR.matrix.copy( camera.matrix );
  34778. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  34779. }
  34780. if ( cameraXRNeedsUpdate === true ) {
  34781. cameraXR.cameras.push( camera );
  34782. }
  34783. }
  34784. renderer.setOutputRenderTarget( this._xrRenderTarget );
  34785. }
  34786. //
  34787. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34788. const inputSource = this._controllerInputSources[ i ];
  34789. const controller = this._controllers[ i ];
  34790. if ( inputSource !== null && controller !== undefined ) {
  34791. controller.update( inputSource, frame, referenceSpace );
  34792. }
  34793. }
  34794. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  34795. if ( frame.detectedPlanes ) {
  34796. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  34797. }
  34798. this._xrFrame = null;
  34799. }
  34800. const _scene = /*@__PURE__*/ new Scene();
  34801. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  34802. const _screen = /*@__PURE__*/ new Vector4();
  34803. const _frustum = /*@__PURE__*/ new Frustum();
  34804. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  34805. const _vector4 = /*@__PURE__*/ new Vector4();
  34806. /**
  34807. * Base class for renderers.
  34808. */
  34809. class Renderer {
  34810. /**
  34811. * Constructs a new renderer.
  34812. *
  34813. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  34814. * @param {Object} parameters - The configuration parameter.
  34815. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  34816. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  34817. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  34818. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  34819. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  34820. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  34821. * to overwrite the default.
  34822. * @param {?Function} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34823. * @param {number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  34824. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  34825. */
  34826. constructor( backend, parameters = {} ) {
  34827. /**
  34828. * This flag can be used for type testing.
  34829. *
  34830. * @type {boolean}
  34831. * @readonly
  34832. * @default true
  34833. */
  34834. this.isRenderer = true;
  34835. //
  34836. const {
  34837. logarithmicDepthBuffer = false,
  34838. alpha = true,
  34839. depth = true,
  34840. stencil = false,
  34841. antialias = false,
  34842. samples = 0,
  34843. getFallback = null,
  34844. colorBufferType = HalfFloatType
  34845. } = parameters;
  34846. /**
  34847. * A reference to the canvas element the renderer is drawing to.
  34848. * This value of this property will automatically be created by
  34849. * the renderer.
  34850. *
  34851. * @type {HTMLCanvasElement|OffscreenCanvas}
  34852. */
  34853. this.domElement = backend.getDomElement();
  34854. /**
  34855. * A reference to the current backend.
  34856. *
  34857. * @type {Backend}
  34858. */
  34859. this.backend = backend;
  34860. /**
  34861. * The number of MSAA samples.
  34862. *
  34863. * @type {number}
  34864. * @default 0
  34865. */
  34866. this.samples = samples || ( antialias === true ) ? 4 : 0;
  34867. /**
  34868. * Whether the renderer should automatically clear the current rendering target
  34869. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  34870. * or the current bound render target (custom framebuffer).
  34871. *
  34872. * @type {boolean}
  34873. * @default true
  34874. */
  34875. this.autoClear = true;
  34876. /**
  34877. * When `autoClear` is set to `true`, this property defines whether the renderer
  34878. * should clear the color buffer.
  34879. *
  34880. * @type {boolean}
  34881. * @default true
  34882. */
  34883. this.autoClearColor = true;
  34884. /**
  34885. * When `autoClear` is set to `true`, this property defines whether the renderer
  34886. * should clear the depth buffer.
  34887. *
  34888. * @type {boolean}
  34889. * @default true
  34890. */
  34891. this.autoClearDepth = true;
  34892. /**
  34893. * When `autoClear` is set to `true`, this property defines whether the renderer
  34894. * should clear the stencil buffer.
  34895. *
  34896. * @type {boolean}
  34897. * @default true
  34898. */
  34899. this.autoClearStencil = true;
  34900. /**
  34901. * Whether the default framebuffer should be transparent or opaque.
  34902. *
  34903. * @type {boolean}
  34904. * @default true
  34905. */
  34906. this.alpha = alpha;
  34907. /**
  34908. * Whether logarithmic depth buffer is enabled or not.
  34909. *
  34910. * @type {boolean}
  34911. * @default false
  34912. */
  34913. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34914. /**
  34915. * Defines the output color space of the renderer.
  34916. *
  34917. * @type {string}
  34918. * @default SRGBColorSpace
  34919. */
  34920. this.outputColorSpace = SRGBColorSpace;
  34921. /**
  34922. * Defines the tone mapping of the renderer.
  34923. *
  34924. * @type {number}
  34925. * @default NoToneMapping
  34926. */
  34927. this.toneMapping = NoToneMapping;
  34928. /**
  34929. * Defines the tone mapping exposure.
  34930. *
  34931. * @type {number}
  34932. * @default 1
  34933. */
  34934. this.toneMappingExposure = 1.0;
  34935. /**
  34936. * Whether the renderer should sort its render lists or not.
  34937. *
  34938. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34939. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34940. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34941. * e.g. manually determining each object's rendering order.
  34942. *
  34943. * @type {boolean}
  34944. * @default true
  34945. */
  34946. this.sortObjects = true;
  34947. /**
  34948. * Whether the default framebuffer should have a depth buffer or not.
  34949. *
  34950. * @type {boolean}
  34951. * @default true
  34952. */
  34953. this.depth = depth;
  34954. /**
  34955. * Whether the default framebuffer should have a stencil buffer or not.
  34956. *
  34957. * @type {boolean}
  34958. * @default false
  34959. */
  34960. this.stencil = stencil;
  34961. /**
  34962. * Holds a series of statistical information about the GPU memory
  34963. * and the rendering process. Useful for debugging and monitoring.
  34964. *
  34965. * @type {Info}
  34966. */
  34967. this.info = new Info();
  34968. this.nodes = {
  34969. modelViewMatrix: null,
  34970. modelNormalViewMatrix: null
  34971. };
  34972. /**
  34973. * The node library defines how certain library objects like materials, lights
  34974. * or tone mapping functions are mapped to node types. This is required since
  34975. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34976. * be part of the scene graph, they are internally represented as nodes for
  34977. * further processing.
  34978. *
  34979. * @type {NodeLibrary}
  34980. */
  34981. this.library = new NodeLibrary();
  34982. /**
  34983. * A map-like data structure for managing lights.
  34984. *
  34985. * @type {Lighting}
  34986. */
  34987. this.lighting = new Lighting();
  34988. // internals
  34989. /**
  34990. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34991. *
  34992. * @private
  34993. * @type {Function}
  34994. */
  34995. this._getFallback = getFallback;
  34996. /**
  34997. * The renderer's pixel ration.
  34998. *
  34999. * @private
  35000. * @type {number}
  35001. * @default 1
  35002. */
  35003. this._pixelRatio = 1;
  35004. /**
  35005. * The width of the renderer's default framebuffer in logical pixel unit.
  35006. *
  35007. * @private
  35008. * @type {number}
  35009. */
  35010. this._width = this.domElement.width;
  35011. /**
  35012. * The height of the renderer's default framebuffer in logical pixel unit.
  35013. *
  35014. * @private
  35015. * @type {number}
  35016. */
  35017. this._height = this.domElement.height;
  35018. /**
  35019. * The viewport of the renderer in logical pixel unit.
  35020. *
  35021. * @private
  35022. * @type {Vector4}
  35023. */
  35024. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35025. /**
  35026. * The scissor rectangle of the renderer in logical pixel unit.
  35027. *
  35028. * @private
  35029. * @type {Vector4}
  35030. */
  35031. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35032. /**
  35033. * Whether the scissor test should be enabled or not.
  35034. *
  35035. * @private
  35036. * @type {boolean}
  35037. */
  35038. this._scissorTest = false;
  35039. /**
  35040. * A reference to a renderer module for managing shader attributes.
  35041. *
  35042. * @private
  35043. * @type {?Attributes}
  35044. * @default null
  35045. */
  35046. this._attributes = null;
  35047. /**
  35048. * A reference to a renderer module for managing geometries.
  35049. *
  35050. * @private
  35051. * @type {?Geometries}
  35052. * @default null
  35053. */
  35054. this._geometries = null;
  35055. /**
  35056. * A reference to a renderer module for managing node related logic.
  35057. *
  35058. * @private
  35059. * @type {?Nodes}
  35060. * @default null
  35061. */
  35062. this._nodes = null;
  35063. /**
  35064. * A reference to a renderer module for managing the internal animation loop.
  35065. *
  35066. * @private
  35067. * @type {?Animation}
  35068. * @default null
  35069. */
  35070. this._animation = null;
  35071. /**
  35072. * A reference to a renderer module for managing shader program bindings.
  35073. *
  35074. * @private
  35075. * @type {?Bindings}
  35076. * @default null
  35077. */
  35078. this._bindings = null;
  35079. /**
  35080. * A reference to a renderer module for managing render objects.
  35081. *
  35082. * @private
  35083. * @type {?RenderObjects}
  35084. * @default null
  35085. */
  35086. this._objects = null;
  35087. /**
  35088. * A reference to a renderer module for managing render and compute pipelines.
  35089. *
  35090. * @private
  35091. * @type {?Pipelines}
  35092. * @default null
  35093. */
  35094. this._pipelines = null;
  35095. /**
  35096. * A reference to a renderer module for managing render bundles.
  35097. *
  35098. * @private
  35099. * @type {?RenderBundles}
  35100. * @default null
  35101. */
  35102. this._bundles = null;
  35103. /**
  35104. * A reference to a renderer module for managing render lists.
  35105. *
  35106. * @private
  35107. * @type {?RenderLists}
  35108. * @default null
  35109. */
  35110. this._renderLists = null;
  35111. /**
  35112. * A reference to a renderer module for managing render contexts.
  35113. *
  35114. * @private
  35115. * @type {?RenderContexts}
  35116. * @default null
  35117. */
  35118. this._renderContexts = null;
  35119. /**
  35120. * A reference to a renderer module for managing textures.
  35121. *
  35122. * @private
  35123. * @type {?Textures}
  35124. * @default null
  35125. */
  35126. this._textures = null;
  35127. /**
  35128. * A reference to a renderer module for backgrounds.
  35129. *
  35130. * @private
  35131. * @type {?Background}
  35132. * @default null
  35133. */
  35134. this._background = null;
  35135. /**
  35136. * This fullscreen quad is used for internal render passes
  35137. * like the tone mapping and color space output pass.
  35138. *
  35139. * @private
  35140. * @type {QuadMesh}
  35141. */
  35142. this._quad = new QuadMesh( new NodeMaterial() );
  35143. this._quad.material.name = 'Renderer_output';
  35144. /**
  35145. * A reference to the current render context.
  35146. *
  35147. * @private
  35148. * @type {?RenderContext}
  35149. * @default null
  35150. */
  35151. this._currentRenderContext = null;
  35152. /**
  35153. * A custom sort function for the opaque render list.
  35154. *
  35155. * @private
  35156. * @type {?Function}
  35157. * @default null
  35158. */
  35159. this._opaqueSort = null;
  35160. /**
  35161. * A custom sort function for the transparent render list.
  35162. *
  35163. * @private
  35164. * @type {?Function}
  35165. * @default null
  35166. */
  35167. this._transparentSort = null;
  35168. /**
  35169. * The framebuffer target.
  35170. *
  35171. * @private
  35172. * @type {?RenderTarget}
  35173. * @default null
  35174. */
  35175. this._frameBufferTarget = null;
  35176. const alphaClear = this.alpha === true ? 0 : 1;
  35177. /**
  35178. * The clear color value.
  35179. *
  35180. * @private
  35181. * @type {Color4}
  35182. */
  35183. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35184. /**
  35185. * The clear depth value.
  35186. *
  35187. * @private
  35188. * @type {number}
  35189. * @default 1
  35190. */
  35191. this._clearDepth = 1;
  35192. /**
  35193. * The clear stencil value.
  35194. *
  35195. * @private
  35196. * @type {number}
  35197. * @default 0
  35198. */
  35199. this._clearStencil = 0;
  35200. /**
  35201. * The current render target.
  35202. *
  35203. * @private
  35204. * @type {?RenderTarget}
  35205. * @default null
  35206. */
  35207. this._renderTarget = null;
  35208. /**
  35209. * The active cube face.
  35210. *
  35211. * @private
  35212. * @type {number}
  35213. * @default 0
  35214. */
  35215. this._activeCubeFace = 0;
  35216. /**
  35217. * The active mipmap level.
  35218. *
  35219. * @private
  35220. * @type {number}
  35221. * @default 0
  35222. */
  35223. this._activeMipmapLevel = 0;
  35224. /**
  35225. * The current output render target.
  35226. *
  35227. * @private
  35228. * @type {?RenderTarget}
  35229. * @default null
  35230. */
  35231. this._outputRenderTarget = null;
  35232. /**
  35233. * The MRT setting.
  35234. *
  35235. * @private
  35236. * @type {?MRTNode}
  35237. * @default null
  35238. */
  35239. this._mrt = null;
  35240. /**
  35241. * This function defines how a render object is going
  35242. * to be rendered.
  35243. *
  35244. * @private
  35245. * @type {?Function}
  35246. * @default null
  35247. */
  35248. this._renderObjectFunction = null;
  35249. /**
  35250. * Used to keep track of the current render object function.
  35251. *
  35252. * @private
  35253. * @type {?Function}
  35254. * @default null
  35255. */
  35256. this._currentRenderObjectFunction = null;
  35257. /**
  35258. * Used to keep track of the current render bundle.
  35259. *
  35260. * @private
  35261. * @type {?RenderBundle}
  35262. * @default null
  35263. */
  35264. this._currentRenderBundle = null;
  35265. /**
  35266. * Next to `_renderObjectFunction()`, this function provides another hook
  35267. * for influencing the render process of a render object. It is meant for internal
  35268. * use and only relevant for `compileAsync()` right now. Instead of using
  35269. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  35270. * a different function might be used which performs no draw but just the node
  35271. * and pipeline updates.
  35272. *
  35273. * @private
  35274. * @type {?Function}
  35275. * @default null
  35276. */
  35277. this._handleObjectFunction = this._renderObjectDirect;
  35278. /**
  35279. * Indicates whether the device has been lost or not. In WebGL terms, the device
  35280. * lost is considered as a context lost. When this is set to `true`, rendering
  35281. * isn't possible anymore.
  35282. *
  35283. * @private
  35284. * @type {boolean}
  35285. * @default false
  35286. */
  35287. this._isDeviceLost = false;
  35288. /**
  35289. * A callback function that defines what should happen when a device/context lost occurs.
  35290. *
  35291. * @type {Function}
  35292. */
  35293. this.onDeviceLost = this._onDeviceLost;
  35294. /**
  35295. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  35296. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  35297. * This will reduce rendering quality though.
  35298. *
  35299. * @private
  35300. * @type {number}
  35301. * @default HalfFloatType
  35302. */
  35303. this._colorBufferType = colorBufferType;
  35304. /**
  35305. * Whether the renderer has been initialized or not.
  35306. *
  35307. * @private
  35308. * @type {boolean}
  35309. * @default false
  35310. */
  35311. this._initialized = false;
  35312. /**
  35313. * A reference to the promise which initializes the renderer.
  35314. *
  35315. * @private
  35316. * @type {?Promise}
  35317. * @default null
  35318. */
  35319. this._initPromise = null;
  35320. /**
  35321. * An array of compilation promises which are used in `compileAsync()`.
  35322. *
  35323. * @private
  35324. * @type {?Array<Promise>}
  35325. * @default null
  35326. */
  35327. this._compilationPromises = null;
  35328. /**
  35329. * Whether the renderer should render transparent render objects or not.
  35330. *
  35331. * @type {boolean}
  35332. * @default true
  35333. */
  35334. this.transparent = true;
  35335. /**
  35336. * Whether the renderer should render opaque render objects or not.
  35337. *
  35338. * @type {boolean}
  35339. * @default true
  35340. */
  35341. this.opaque = true;
  35342. /**
  35343. * Shadow map configuration
  35344. * @typedef {Object} ShadowMapConfig
  35345. * @property {boolean} enabled - Whether to globally enable shadows or not.
  35346. * @property {number} type - The shadow map type.
  35347. */
  35348. /**
  35349. * The renderer's shadow configuration.
  35350. *
  35351. * @type {ShadowMapConfig}
  35352. */
  35353. this.shadowMap = {
  35354. enabled: false,
  35355. type: PCFShadowMap
  35356. };
  35357. /**
  35358. * XR configuration.
  35359. * @typedef {Object} XRConfig
  35360. * @property {boolean} enabled - Whether to globally enable XR or not.
  35361. */
  35362. /**
  35363. * The renderer's XR manager.
  35364. *
  35365. * @type {XRManager}
  35366. */
  35367. this.xr = new XRManager( this );
  35368. /**
  35369. * Debug configuration.
  35370. * @typedef {Object} DebugConfig
  35371. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  35372. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  35373. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  35374. */
  35375. /**
  35376. * The renderer's debug configuration.
  35377. *
  35378. * @type {DebugConfig}
  35379. */
  35380. this.debug = {
  35381. checkShaderErrors: true,
  35382. onShaderError: null,
  35383. getShaderAsync: async ( scene, camera, object ) => {
  35384. await this.compileAsync( scene, camera );
  35385. const renderList = this._renderLists.get( scene, camera );
  35386. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  35387. const material = scene.overrideMaterial || object.material;
  35388. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  35389. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  35390. return { fragmentShader, vertexShader };
  35391. }
  35392. };
  35393. }
  35394. /**
  35395. * Initializes the renderer so it is ready for usage.
  35396. *
  35397. * @async
  35398. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  35399. */
  35400. async init() {
  35401. if ( this._initialized ) {
  35402. throw new Error( 'Renderer: Backend has already been initialized.' );
  35403. }
  35404. if ( this._initPromise !== null ) {
  35405. return this._initPromise;
  35406. }
  35407. this._initPromise = new Promise( async ( resolve, reject ) => {
  35408. let backend = this.backend;
  35409. try {
  35410. await backend.init( this );
  35411. } catch ( error ) {
  35412. if ( this._getFallback !== null ) {
  35413. // try the fallback
  35414. try {
  35415. this.backend = backend = this._getFallback( error );
  35416. await backend.init( this );
  35417. } catch ( error ) {
  35418. reject( error );
  35419. return;
  35420. }
  35421. } else {
  35422. reject( error );
  35423. return;
  35424. }
  35425. }
  35426. this._nodes = new Nodes( this, backend );
  35427. this._animation = new Animation( this._nodes, this.info );
  35428. this._attributes = new Attributes( backend );
  35429. this._background = new Background( this, this._nodes );
  35430. this._geometries = new Geometries( this._attributes, this.info );
  35431. this._textures = new Textures( this, backend, this.info );
  35432. this._pipelines = new Pipelines( backend, this._nodes );
  35433. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35434. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35435. this._renderLists = new RenderLists( this.lighting );
  35436. this._bundles = new RenderBundles();
  35437. this._renderContexts = new RenderContexts();
  35438. //
  35439. this._animation.start();
  35440. this._initialized = true;
  35441. resolve();
  35442. } );
  35443. return this._initPromise;
  35444. }
  35445. /**
  35446. * The coordinate system of the renderer. The value of this property
  35447. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  35448. * `THREE.WebGPUCoordinateSystem`.
  35449. *
  35450. * @readonly
  35451. * @type {number}
  35452. */
  35453. get coordinateSystem() {
  35454. return this.backend.coordinateSystem;
  35455. }
  35456. /**
  35457. * Compiles all materials in the given scene. This can be useful to avoid a
  35458. * phenomenon which is called "shader compilation stutter", which occurs when
  35459. * rendering an object with a new shader for the first time.
  35460. *
  35461. * If you want to add a 3D object to an existing scene, use the third optional
  35462. * parameter for applying the target scene. Note that the (target) scene's lighting
  35463. * and environment must be configured before calling this method.
  35464. *
  35465. * @async
  35466. * @param {Object3D} scene - The scene or 3D object to precompile.
  35467. * @param {Camera} camera - The camera that is used to render the scene.
  35468. * @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.
  35469. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  35470. */
  35471. async compileAsync( scene, camera, targetScene = null ) {
  35472. if ( this._isDeviceLost === true ) return;
  35473. if ( this._initialized === false ) await this.init();
  35474. // preserve render tree
  35475. const nodeFrame = this._nodes.nodeFrame;
  35476. const previousRenderId = nodeFrame.renderId;
  35477. const previousRenderContext = this._currentRenderContext;
  35478. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35479. const previousCompilationPromises = this._compilationPromises;
  35480. //
  35481. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35482. if ( targetScene === null ) targetScene = scene;
  35483. const renderTarget = this._renderTarget;
  35484. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35485. const activeMipmapLevel = this._activeMipmapLevel;
  35486. const compilationPromises = [];
  35487. this._currentRenderContext = renderContext;
  35488. this._currentRenderObjectFunction = this.renderObject;
  35489. this._handleObjectFunction = this._createObjectPipeline;
  35490. this._compilationPromises = compilationPromises;
  35491. nodeFrame.renderId ++;
  35492. //
  35493. nodeFrame.update();
  35494. //
  35495. renderContext.depth = this.depth;
  35496. renderContext.stencil = this.stencil;
  35497. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35498. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35499. //
  35500. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35501. //
  35502. const renderList = this._renderLists.get( scene, camera );
  35503. renderList.begin();
  35504. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35505. // include lights from target scene
  35506. if ( targetScene !== scene ) {
  35507. targetScene.traverseVisible( function ( object ) {
  35508. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35509. renderList.pushLight( object );
  35510. }
  35511. } );
  35512. }
  35513. renderList.finish();
  35514. //
  35515. if ( renderTarget !== null ) {
  35516. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35517. const renderTargetData = this._textures.get( renderTarget );
  35518. renderContext.textures = renderTargetData.textures;
  35519. renderContext.depthTexture = renderTargetData.depthTexture;
  35520. } else {
  35521. renderContext.textures = null;
  35522. renderContext.depthTexture = null;
  35523. }
  35524. //
  35525. this._background.update( sceneRef, renderList, renderContext );
  35526. // process render lists
  35527. const opaqueObjects = renderList.opaque;
  35528. const transparentObjects = renderList.transparent;
  35529. const transparentDoublePassObjects = renderList.transparentDoublePass;
  35530. const lightsNode = renderList.lightsNode;
  35531. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35532. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35533. // restore render tree
  35534. nodeFrame.renderId = previousRenderId;
  35535. this._currentRenderContext = previousRenderContext;
  35536. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35537. this._compilationPromises = previousCompilationPromises;
  35538. this._handleObjectFunction = this._renderObjectDirect;
  35539. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35540. await Promise.all( compilationPromises );
  35541. }
  35542. /**
  35543. * Renders the scene in an async fashion.
  35544. *
  35545. * @async
  35546. * @param {Object3D} scene - The scene or 3D object to render.
  35547. * @param {Camera} camera - The camera.
  35548. * @return {Promise} A Promise that resolves when the render has been finished.
  35549. */
  35550. async renderAsync( scene, camera ) {
  35551. if ( this._initialized === false ) await this.init();
  35552. this._renderScene( scene, camera );
  35553. }
  35554. /**
  35555. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  35556. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  35557. *
  35558. * @async
  35559. * @return {Promise} A Promise that resolves when synchronization has been finished.
  35560. */
  35561. async waitForGPU() {
  35562. await this.backend.waitForGPU();
  35563. }
  35564. /**
  35565. * Sets the given MRT configuration.
  35566. *
  35567. * @param {MRTNode} mrt - The MRT node to set.
  35568. * @return {Renderer} A reference to this renderer.
  35569. */
  35570. setMRT( mrt ) {
  35571. this._mrt = mrt;
  35572. return this;
  35573. }
  35574. /**
  35575. * Returns the MRT configuration.
  35576. *
  35577. * @return {MRTNode} The MRT configuration.
  35578. */
  35579. getMRT() {
  35580. return this._mrt;
  35581. }
  35582. /**
  35583. * Returns the color buffer type.
  35584. *
  35585. * @return {number} The color buffer type.
  35586. */
  35587. getColorBufferType() {
  35588. return this._colorBufferType;
  35589. }
  35590. /**
  35591. * Default implementation of the device lost callback.
  35592. *
  35593. * @private
  35594. * @param {Object} info - Information about the context lost.
  35595. */
  35596. _onDeviceLost( info ) {
  35597. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  35598. if ( info.reason ) {
  35599. errorMessage += `\nReason: ${info.reason}`;
  35600. }
  35601. console.error( errorMessage );
  35602. this._isDeviceLost = true;
  35603. }
  35604. /**
  35605. * Renders the given render bundle.
  35606. *
  35607. * @private
  35608. * @param {Object} bundle - Render bundle data.
  35609. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  35610. * @param {LightsNode} lightsNode - The current lights node.
  35611. */
  35612. _renderBundle( bundle, sceneRef, lightsNode ) {
  35613. const { bundleGroup, camera, renderList } = bundle;
  35614. const renderContext = this._currentRenderContext;
  35615. //
  35616. const renderBundle = this._bundles.get( bundleGroup, camera );
  35617. const renderBundleData = this.backend.get( renderBundle );
  35618. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35619. //
  35620. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  35621. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  35622. renderBundleData.renderContexts.add( renderContext );
  35623. if ( renderBundleNeedsUpdate ) {
  35624. this.backend.beginBundle( renderContext );
  35625. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  35626. renderBundleData.renderObjects = [];
  35627. }
  35628. this._currentRenderBundle = renderBundle;
  35629. const opaqueObjects = renderList.opaque;
  35630. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35631. this._currentRenderBundle = null;
  35632. //
  35633. this.backend.finishBundle( renderContext, renderBundle );
  35634. renderBundleData.version = bundleGroup.version;
  35635. } else {
  35636. const { renderObjects } = renderBundleData;
  35637. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  35638. const renderObject = renderObjects[ i ];
  35639. if ( this._nodes.needsRefresh( renderObject ) ) {
  35640. this._nodes.updateBefore( renderObject );
  35641. this._nodes.updateForRender( renderObject );
  35642. this._bindings.updateForRender( renderObject );
  35643. this._nodes.updateAfter( renderObject );
  35644. }
  35645. }
  35646. }
  35647. this.backend.addBundle( renderContext, renderBundle );
  35648. }
  35649. /**
  35650. * Renders the scene or 3D object with the given camera. This method can only be called
  35651. * if the renderer has been initialized.
  35652. *
  35653. * The target of the method is the default framebuffer (meaning the canvas)
  35654. * or alternatively a render target when specified via `setRenderTarget()`.
  35655. *
  35656. * @param {Object3D} scene - The scene or 3D object to render.
  35657. * @param {Camera} camera - The camera to render the scene with.
  35658. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  35659. * Only returned when the renderer has not been initialized.
  35660. */
  35661. render( scene, camera ) {
  35662. if ( this._initialized === false ) {
  35663. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35664. return this.renderAsync( scene, camera );
  35665. }
  35666. this._renderScene( scene, camera );
  35667. }
  35668. /**
  35669. * Returns an internal render target which is used when computing the output tone mapping
  35670. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  35671. * pass and not inline to achieve more correct results.
  35672. *
  35673. * @private
  35674. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  35675. */
  35676. _getFrameBufferTarget() {
  35677. const { currentToneMapping, currentColorSpace } = this;
  35678. const useToneMapping = currentToneMapping !== NoToneMapping;
  35679. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  35680. if ( useToneMapping === false && useColorSpace === false ) return null;
  35681. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35682. const { depth, stencil } = this;
  35683. let frameBufferTarget = this._frameBufferTarget;
  35684. if ( frameBufferTarget === null ) {
  35685. frameBufferTarget = new RenderTarget( width, height, {
  35686. depthBuffer: depth,
  35687. stencilBuffer: stencil,
  35688. type: this._colorBufferType,
  35689. format: RGBAFormat,
  35690. colorSpace: LinearSRGBColorSpace,
  35691. generateMipmaps: false,
  35692. minFilter: LinearFilter,
  35693. magFilter: LinearFilter,
  35694. samples: this.samples
  35695. } );
  35696. frameBufferTarget.isPostProcessingRenderTarget = true;
  35697. this._frameBufferTarget = frameBufferTarget;
  35698. }
  35699. frameBufferTarget.depthBuffer = depth;
  35700. frameBufferTarget.stencilBuffer = stencil;
  35701. frameBufferTarget.setSize( width, height );
  35702. frameBufferTarget.viewport.copy( this._viewport );
  35703. frameBufferTarget.scissor.copy( this._scissor );
  35704. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35705. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35706. frameBufferTarget.scissorTest = this._scissorTest;
  35707. return frameBufferTarget;
  35708. }
  35709. /**
  35710. * Renders the scene or 3D object with the given camera.
  35711. *
  35712. * @private
  35713. * @param {Object3D} scene - The scene or 3D object to render.
  35714. * @param {Camera} camera - The camera to render the scene with.
  35715. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  35716. * @return {RenderContext} The current render context.
  35717. */
  35718. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35719. if ( this._isDeviceLost === true ) return;
  35720. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35721. // preserve render tree
  35722. const nodeFrame = this._nodes.nodeFrame;
  35723. const previousRenderId = nodeFrame.renderId;
  35724. const previousRenderContext = this._currentRenderContext;
  35725. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35726. //
  35727. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35728. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  35729. const activeCubeFace = this._activeCubeFace;
  35730. const activeMipmapLevel = this._activeMipmapLevel;
  35731. //
  35732. let renderTarget;
  35733. if ( frameBufferTarget !== null ) {
  35734. renderTarget = frameBufferTarget;
  35735. this.setRenderTarget( renderTarget );
  35736. } else {
  35737. renderTarget = outputRenderTarget;
  35738. }
  35739. //
  35740. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35741. this._currentRenderContext = renderContext;
  35742. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35743. //
  35744. this.info.calls ++;
  35745. this.info.render.calls ++;
  35746. this.info.render.frameCalls ++;
  35747. nodeFrame.renderId = this.info.calls;
  35748. //
  35749. const coordinateSystem = this.coordinateSystem;
  35750. const xr = this.xr;
  35751. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  35752. camera.coordinateSystem = coordinateSystem;
  35753. camera.updateProjectionMatrix();
  35754. if ( camera.isArrayCamera ) {
  35755. for ( const subCamera of camera.cameras ) {
  35756. subCamera.coordinateSystem = coordinateSystem;
  35757. subCamera.updateProjectionMatrix();
  35758. }
  35759. }
  35760. }
  35761. //
  35762. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35763. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35764. if ( xr.enabled === true && xr.isPresenting === true ) {
  35765. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  35766. camera = xr.getCamera(); // use XR camera for rendering
  35767. }
  35768. //
  35769. let viewport = this._viewport;
  35770. let scissor = this._scissor;
  35771. let pixelRatio = this._pixelRatio;
  35772. if ( renderTarget !== null ) {
  35773. viewport = renderTarget.viewport;
  35774. scissor = renderTarget.scissor;
  35775. pixelRatio = 1;
  35776. }
  35777. this.getDrawingBufferSize( _drawingBufferSize );
  35778. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35779. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35780. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35781. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35782. renderContext.viewportValue.width >>= activeMipmapLevel;
  35783. renderContext.viewportValue.height >>= activeMipmapLevel;
  35784. renderContext.viewportValue.minDepth = minDepth;
  35785. renderContext.viewportValue.maxDepth = maxDepth;
  35786. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35787. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35788. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35789. renderContext.scissorValue.width >>= activeMipmapLevel;
  35790. renderContext.scissorValue.height >>= activeMipmapLevel;
  35791. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35792. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35793. //
  35794. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35795. //
  35796. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35797. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35798. const renderList = this._renderLists.get( scene, camera );
  35799. renderList.begin();
  35800. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35801. renderList.finish();
  35802. if ( this.sortObjects === true ) {
  35803. renderList.sort( this._opaqueSort, this._transparentSort );
  35804. }
  35805. //
  35806. if ( renderTarget !== null ) {
  35807. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35808. const renderTargetData = this._textures.get( renderTarget );
  35809. renderContext.textures = renderTargetData.textures;
  35810. renderContext.depthTexture = renderTargetData.depthTexture;
  35811. renderContext.width = renderTargetData.width;
  35812. renderContext.height = renderTargetData.height;
  35813. renderContext.renderTarget = renderTarget;
  35814. renderContext.depth = renderTarget.depthBuffer;
  35815. renderContext.stencil = renderTarget.stencilBuffer;
  35816. } else {
  35817. renderContext.textures = null;
  35818. renderContext.depthTexture = null;
  35819. renderContext.width = this.domElement.width;
  35820. renderContext.height = this.domElement.height;
  35821. renderContext.depth = this.depth;
  35822. renderContext.stencil = this.stencil;
  35823. }
  35824. renderContext.width >>= activeMipmapLevel;
  35825. renderContext.height >>= activeMipmapLevel;
  35826. renderContext.activeCubeFace = activeCubeFace;
  35827. renderContext.activeMipmapLevel = activeMipmapLevel;
  35828. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35829. //
  35830. this._background.update( sceneRef, renderList, renderContext );
  35831. //
  35832. this.backend.beginRender( renderContext );
  35833. // process render lists
  35834. const {
  35835. bundles,
  35836. lightsNode,
  35837. transparentDoublePass: transparentDoublePassObjects,
  35838. transparent: transparentObjects,
  35839. opaque: opaqueObjects
  35840. } = renderList;
  35841. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35842. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35843. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35844. // finish render pass
  35845. this.backend.finishRender( renderContext );
  35846. // restore render tree
  35847. nodeFrame.renderId = previousRenderId;
  35848. this._currentRenderContext = previousRenderContext;
  35849. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35850. //
  35851. if ( frameBufferTarget !== null ) {
  35852. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35853. this._renderOutput( renderTarget );
  35854. }
  35855. //
  35856. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35857. //
  35858. return renderContext;
  35859. }
  35860. /**
  35861. * The output pass performs tone mapping and color space conversion.
  35862. *
  35863. * @private
  35864. * @param {RenderTarget} renderTarget - The current render target.
  35865. */
  35866. _renderOutput( renderTarget ) {
  35867. const quad = this._quad;
  35868. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35869. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35870. quad.material.needsUpdate = true;
  35871. }
  35872. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  35873. const currentAutoClear = this.autoClear;
  35874. const currentXR = this.xr.enabled;
  35875. this.autoClear = false;
  35876. this.xr.enabled = false;
  35877. this._renderScene( quad, quad.camera, false );
  35878. this.autoClear = currentAutoClear;
  35879. this.xr.enabled = currentXR;
  35880. }
  35881. /**
  35882. * Returns the maximum available anisotropy for texture filtering.
  35883. *
  35884. * @return {number} The maximum available anisotropy.
  35885. */
  35886. getMaxAnisotropy() {
  35887. return this.backend.getMaxAnisotropy();
  35888. }
  35889. /**
  35890. * Returns the active cube face.
  35891. *
  35892. * @return {number} The active cube face.
  35893. */
  35894. getActiveCubeFace() {
  35895. return this._activeCubeFace;
  35896. }
  35897. /**
  35898. * Returns the active mipmap level.
  35899. *
  35900. * @return {number} The active mipmap level.
  35901. */
  35902. getActiveMipmapLevel() {
  35903. return this._activeMipmapLevel;
  35904. }
  35905. /**
  35906. * Applications are advised to always define the animation loop
  35907. * with this method and not manually with `requestAnimationFrame()`
  35908. * for best compatibility.
  35909. *
  35910. * @async
  35911. * @param {Function} callback - The application's animation loop.
  35912. * @return {Promise} A Promise that resolves when the set has been executed.
  35913. */
  35914. async setAnimationLoop( callback ) {
  35915. if ( this._initialized === false ) await this.init();
  35916. this._animation.setAnimationLoop( callback );
  35917. }
  35918. /**
  35919. * Can be used to transfer buffer data from a storage buffer attribute
  35920. * from the GPU to the CPU in context of compute shaders.
  35921. *
  35922. * @async
  35923. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  35924. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  35925. */
  35926. async getArrayBufferAsync( attribute ) {
  35927. return await this.backend.getArrayBufferAsync( attribute );
  35928. }
  35929. /**
  35930. * Returns the rendering context.
  35931. *
  35932. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  35933. */
  35934. getContext() {
  35935. return this.backend.getContext();
  35936. }
  35937. /**
  35938. * Returns the pixel ratio.
  35939. *
  35940. * @return {number} The pixel ratio.
  35941. */
  35942. getPixelRatio() {
  35943. return this._pixelRatio;
  35944. }
  35945. /**
  35946. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  35947. *
  35948. * @param {Vector2} target - The method writes the result in this target object.
  35949. * @return {Vector2} The drawing buffer size.
  35950. */
  35951. getDrawingBufferSize( target ) {
  35952. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35953. }
  35954. /**
  35955. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35956. *
  35957. * @param {Vector2} target - The method writes the result in this target object.
  35958. * @return {Vector2} The drawing buffer size.
  35959. */
  35960. getSize( target ) {
  35961. return target.set( this._width, this._height );
  35962. }
  35963. /**
  35964. * Sets the given pixel ration and resizes the canvas if necessary.
  35965. *
  35966. * @param {number} [value=1] - The pixel ratio.
  35967. */
  35968. setPixelRatio( value = 1 ) {
  35969. if ( this._pixelRatio === value ) return;
  35970. this._pixelRatio = value;
  35971. this.setSize( this._width, this._height, false );
  35972. }
  35973. /**
  35974. * This method allows to define the drawing buffer size by specifying
  35975. * width, height and pixel ratio all at once. The size of the drawing
  35976. * buffer is computed with this formula:
  35977. * ````
  35978. * size.x = width * pixelRatio;
  35979. * size.y = height * pixelRatio;
  35980. *```
  35981. *
  35982. * @param {number} width - The width in logical pixels.
  35983. * @param {number} height - The height in logical pixels.
  35984. * @param {number} pixelRatio - The pixel ratio.
  35985. */
  35986. setDrawingBufferSize( width, height, pixelRatio ) {
  35987. this._width = width;
  35988. this._height = height;
  35989. this._pixelRatio = pixelRatio;
  35990. this.domElement.width = Math.floor( width * pixelRatio );
  35991. this.domElement.height = Math.floor( height * pixelRatio );
  35992. this.setViewport( 0, 0, width, height );
  35993. if ( this._initialized ) this.backend.updateSize();
  35994. }
  35995. /**
  35996. * Sets the size of the renderer.
  35997. *
  35998. * @param {number} width - The width in logical pixels.
  35999. * @param {number} height - The height in logical pixels.
  36000. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  36001. */
  36002. setSize( width, height, updateStyle = true ) {
  36003. this._width = width;
  36004. this._height = height;
  36005. this.domElement.width = Math.floor( width * this._pixelRatio );
  36006. this.domElement.height = Math.floor( height * this._pixelRatio );
  36007. if ( updateStyle === true ) {
  36008. this.domElement.style.width = width + 'px';
  36009. this.domElement.style.height = height + 'px';
  36010. }
  36011. this.setViewport( 0, 0, width, height );
  36012. if ( this._initialized ) this.backend.updateSize();
  36013. }
  36014. /**
  36015. * Defines a manual sort function for the opaque render list.
  36016. * Pass `null` to use the default sort.
  36017. *
  36018. * @param {Function} method - The sort function.
  36019. */
  36020. setOpaqueSort( method ) {
  36021. this._opaqueSort = method;
  36022. }
  36023. /**
  36024. * Defines a manual sort function for the transparent render list.
  36025. * Pass `null` to use the default sort.
  36026. *
  36027. * @param {Function} method - The sort function.
  36028. */
  36029. setTransparentSort( method ) {
  36030. this._transparentSort = method;
  36031. }
  36032. /**
  36033. * Returns the scissor rectangle.
  36034. *
  36035. * @param {Vector4} target - The method writes the result in this target object.
  36036. * @return {Vector4} The scissor rectangle.
  36037. */
  36038. getScissor( target ) {
  36039. const scissor = this._scissor;
  36040. target.x = scissor.x;
  36041. target.y = scissor.y;
  36042. target.width = scissor.width;
  36043. target.height = scissor.height;
  36044. return target;
  36045. }
  36046. /**
  36047. * Defines the scissor rectangle.
  36048. *
  36049. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  36050. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  36051. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  36052. * @param {number} width - The width of the scissor box in logical pixel unit.
  36053. * @param {number} height - The height of the scissor box in logical pixel unit.
  36054. */
  36055. setScissor( x, y, width, height ) {
  36056. const scissor = this._scissor;
  36057. if ( x.isVector4 ) {
  36058. scissor.copy( x );
  36059. } else {
  36060. scissor.set( x, y, width, height );
  36061. }
  36062. }
  36063. /**
  36064. * Returns the scissor test value.
  36065. *
  36066. * @return {boolean} Whether the scissor test should be enabled or not.
  36067. */
  36068. getScissorTest() {
  36069. return this._scissorTest;
  36070. }
  36071. /**
  36072. * Defines the scissor test.
  36073. *
  36074. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  36075. */
  36076. setScissorTest( boolean ) {
  36077. this._scissorTest = boolean;
  36078. this.backend.setScissorTest( boolean );
  36079. }
  36080. /**
  36081. * Returns the viewport definition.
  36082. *
  36083. * @param {Vector4} target - The method writes the result in this target object.
  36084. * @return {Vector4} The viewport definition.
  36085. */
  36086. getViewport( target ) {
  36087. return target.copy( this._viewport );
  36088. }
  36089. /**
  36090. * Defines the viewport.
  36091. *
  36092. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36093. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36094. * @param {number} width - The width of the viewport in logical pixel unit.
  36095. * @param {number} height - The height of the viewport in logical pixel unit.
  36096. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  36097. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  36098. */
  36099. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36100. const viewport = this._viewport;
  36101. if ( x.isVector4 ) {
  36102. viewport.copy( x );
  36103. } else {
  36104. viewport.set( x, y, width, height );
  36105. }
  36106. viewport.minDepth = minDepth;
  36107. viewport.maxDepth = maxDepth;
  36108. }
  36109. /**
  36110. * Returns the clear color.
  36111. *
  36112. * @param {Color} target - The method writes the result in this target object.
  36113. * @return {Color} The clear color.
  36114. */
  36115. getClearColor( target ) {
  36116. return target.copy( this._clearColor );
  36117. }
  36118. /**
  36119. * Defines the clear color and optionally the clear alpha.
  36120. *
  36121. * @param {Color} color - The clear color.
  36122. * @param {number} [alpha=1] - The clear alpha.
  36123. */
  36124. setClearColor( color, alpha = 1 ) {
  36125. this._clearColor.set( color );
  36126. this._clearColor.a = alpha;
  36127. }
  36128. /**
  36129. * Returns the clear alpha.
  36130. *
  36131. * @return {number} The clear alpha.
  36132. */
  36133. getClearAlpha() {
  36134. return this._clearColor.a;
  36135. }
  36136. /**
  36137. * Defines the clear alpha.
  36138. *
  36139. * @param {number} alpha - The clear alpha.
  36140. */
  36141. setClearAlpha( alpha ) {
  36142. this._clearColor.a = alpha;
  36143. }
  36144. /**
  36145. * Returns the clear depth.
  36146. *
  36147. * @return {number} The clear depth.
  36148. */
  36149. getClearDepth() {
  36150. return this._clearDepth;
  36151. }
  36152. /**
  36153. * Defines the clear depth.
  36154. *
  36155. * @param {number} depth - The clear depth.
  36156. */
  36157. setClearDepth( depth ) {
  36158. this._clearDepth = depth;
  36159. }
  36160. /**
  36161. * Returns the clear stencil.
  36162. *
  36163. * @return {number} The clear stencil.
  36164. */
  36165. getClearStencil() {
  36166. return this._clearStencil;
  36167. }
  36168. /**
  36169. * Defines the clear stencil.
  36170. *
  36171. * @param {number} stencil - The clear stencil.
  36172. */
  36173. setClearStencil( stencil ) {
  36174. this._clearStencil = stencil;
  36175. }
  36176. /**
  36177. * This method performs an occlusion query for the given 3D object.
  36178. * It returns `true` if the given 3D object is fully occluded by other
  36179. * 3D objects in the scene.
  36180. *
  36181. * @param {Object3D} object - The 3D object to test.
  36182. * @return {boolean} Whether the 3D object is fully occluded or not.
  36183. */
  36184. isOccluded( object ) {
  36185. const renderContext = this._currentRenderContext;
  36186. return renderContext && this.backend.isOccluded( renderContext, object );
  36187. }
  36188. /**
  36189. * Performs a manual clear operation. This method ignores `autoClear` properties.
  36190. *
  36191. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36192. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36193. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36194. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36195. * Only returned when the renderer has not been initialized.
  36196. */
  36197. clear( color = true, depth = true, stencil = true ) {
  36198. if ( this._initialized === false ) {
  36199. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36200. return this.clearAsync( color, depth, stencil );
  36201. }
  36202. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36203. let renderContext = null;
  36204. if ( renderTarget !== null ) {
  36205. this._textures.updateRenderTarget( renderTarget );
  36206. const renderTargetData = this._textures.get( renderTarget );
  36207. renderContext = this._renderContexts.getForClear( renderTarget );
  36208. renderContext.textures = renderTargetData.textures;
  36209. renderContext.depthTexture = renderTargetData.depthTexture;
  36210. renderContext.width = renderTargetData.width;
  36211. renderContext.height = renderTargetData.height;
  36212. renderContext.renderTarget = renderTarget;
  36213. renderContext.depth = renderTarget.depthBuffer;
  36214. renderContext.stencil = renderTarget.stencilBuffer;
  36215. // #30329
  36216. renderContext.clearColorValue = this.backend.getClearColor();
  36217. }
  36218. this.backend.clear( color, depth, stencil, renderContext );
  36219. if ( renderTarget !== null && this._renderTarget === null ) {
  36220. this._renderOutput( renderTarget );
  36221. }
  36222. }
  36223. /**
  36224. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  36225. *
  36226. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36227. * Only returned when the renderer has not been initialized.
  36228. */
  36229. clearColor() {
  36230. return this.clear( true, false, false );
  36231. }
  36232. /**
  36233. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  36234. *
  36235. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36236. * Only returned when the renderer has not been initialized.
  36237. */
  36238. clearDepth() {
  36239. return this.clear( false, true, false );
  36240. }
  36241. /**
  36242. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  36243. *
  36244. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36245. * Only returned when the renderer has not been initialized.
  36246. */
  36247. clearStencil() {
  36248. return this.clear( false, false, true );
  36249. }
  36250. /**
  36251. * Async version of {@link Renderer#clear}.
  36252. *
  36253. * @async
  36254. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36255. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36256. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36257. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36258. */
  36259. async clearAsync( color = true, depth = true, stencil = true ) {
  36260. if ( this._initialized === false ) await this.init();
  36261. this.clear( color, depth, stencil );
  36262. }
  36263. /**
  36264. * Async version of {@link Renderer#clearColor}.
  36265. *
  36266. * @async
  36267. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36268. */
  36269. async clearColorAsync() {
  36270. this.clearAsync( true, false, false );
  36271. }
  36272. /**
  36273. * Async version of {@link Renderer#clearDepth}.
  36274. *
  36275. * @async
  36276. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36277. */
  36278. async clearDepthAsync() {
  36279. this.clearAsync( false, true, false );
  36280. }
  36281. /**
  36282. * Async version of {@link Renderer#clearStencil}.
  36283. *
  36284. * @async
  36285. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36286. */
  36287. async clearStencilAsync() {
  36288. this.clearAsync( false, false, true );
  36289. }
  36290. /**
  36291. * The current output tone mapping of the renderer. When a render target is set,
  36292. * the output tone mapping is always `NoToneMapping`.
  36293. *
  36294. * @type {number}
  36295. */
  36296. get currentToneMapping() {
  36297. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  36298. }
  36299. /**
  36300. * The current output color space of the renderer. When a render target is set,
  36301. * the output color space is always `LinearSRGBColorSpace`.
  36302. *
  36303. * @type {string}
  36304. */
  36305. get currentColorSpace() {
  36306. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  36307. }
  36308. /**
  36309. * Returns `true` if the rendering settings are set to screen output.
  36310. *
  36311. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  36312. */
  36313. get isOutputTarget() {
  36314. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  36315. }
  36316. /**
  36317. * Frees all internal resources of the renderer. Call this method if the renderer
  36318. * is no longer in use by your app.
  36319. */
  36320. dispose() {
  36321. this.info.dispose();
  36322. this.backend.dispose();
  36323. this._animation.dispose();
  36324. this._objects.dispose();
  36325. this._pipelines.dispose();
  36326. this._nodes.dispose();
  36327. this._bindings.dispose();
  36328. this._renderLists.dispose();
  36329. this._renderContexts.dispose();
  36330. this._textures.dispose();
  36331. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  36332. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  36333. if ( queryPool !== null ) queryPool.dispose();
  36334. } );
  36335. this.setRenderTarget( null );
  36336. this.setAnimationLoop( null );
  36337. }
  36338. /**
  36339. * Sets the given render target. Calling this method means the renderer does not
  36340. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  36341. * Use `null` as the first argument to reset the state.
  36342. *
  36343. * @param {?RenderTarget} renderTarget - The render target to set.
  36344. * @param {number} [activeCubeFace=0] - The active cube face.
  36345. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  36346. */
  36347. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36348. this._renderTarget = renderTarget;
  36349. this._activeCubeFace = activeCubeFace;
  36350. this._activeMipmapLevel = activeMipmapLevel;
  36351. }
  36352. /**
  36353. * Returns the current render target.
  36354. *
  36355. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  36356. */
  36357. getRenderTarget() {
  36358. return this._renderTarget;
  36359. }
  36360. /**
  36361. * Sets the output render target for the renderer.
  36362. *
  36363. * @param {Object} renderTarget - The render target to set as the output target.
  36364. */
  36365. setOutputRenderTarget( renderTarget ) {
  36366. this._outputRenderTarget = renderTarget;
  36367. }
  36368. /**
  36369. * Returns the current output target.
  36370. *
  36371. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  36372. */
  36373. getOutputRenderTarget() {
  36374. return this._outputRenderTarget;
  36375. }
  36376. /**
  36377. * Callback for {@link Renderer#setRenderObjectFunction}.
  36378. *
  36379. * @callback renderObjectFunction
  36380. * @param {Object3D} object - The 3D object.
  36381. * @param {Scene} scene - The scene the 3D object belongs to.
  36382. * @param {Camera} camera - The camera the object should be rendered with.
  36383. * @param {BufferGeometry} geometry - The object's geometry.
  36384. * @param {Material} material - The object's material.
  36385. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36386. * @param {LightsNode} lightsNode - The current lights node.
  36387. * @param {ClippingContext} clippingContext - The clipping context.
  36388. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36389. */
  36390. /**
  36391. * Sets the given render object function. Calling this method overwrites the default implementation
  36392. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  36393. * if you want to modify the way objects are rendered. For example you can define things like "every
  36394. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  36395. * The custom function must always call `renderObject()` in its implementation.
  36396. *
  36397. * Use `null` as the first argument to reset the state.
  36398. *
  36399. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  36400. */
  36401. setRenderObjectFunction( renderObjectFunction ) {
  36402. this._renderObjectFunction = renderObjectFunction;
  36403. }
  36404. /**
  36405. * Returns the current render object function.
  36406. *
  36407. * @return {?Function} The current render object function. Returns `null` if no function is set.
  36408. */
  36409. getRenderObjectFunction() {
  36410. return this._renderObjectFunction;
  36411. }
  36412. /**
  36413. * Execute a single or an array of compute nodes. This method can only be called
  36414. * if the renderer has been initialized.
  36415. *
  36416. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36417. * @return {?Promise} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  36418. */
  36419. compute( computeNodes ) {
  36420. if ( this._isDeviceLost === true ) return;
  36421. if ( this._initialized === false ) {
  36422. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  36423. return this.computeAsync( computeNodes );
  36424. }
  36425. //
  36426. const nodeFrame = this._nodes.nodeFrame;
  36427. const previousRenderId = nodeFrame.renderId;
  36428. //
  36429. this.info.calls ++;
  36430. this.info.compute.calls ++;
  36431. this.info.compute.frameCalls ++;
  36432. nodeFrame.renderId = this.info.calls;
  36433. //
  36434. const backend = this.backend;
  36435. const pipelines = this._pipelines;
  36436. const bindings = this._bindings;
  36437. const nodes = this._nodes;
  36438. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36439. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36440. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36441. }
  36442. backend.beginCompute( computeNodes );
  36443. for ( const computeNode of computeList ) {
  36444. // onInit
  36445. if ( pipelines.has( computeNode ) === false ) {
  36446. const dispose = () => {
  36447. computeNode.removeEventListener( 'dispose', dispose );
  36448. pipelines.delete( computeNode );
  36449. bindings.delete( computeNode );
  36450. nodes.delete( computeNode );
  36451. };
  36452. computeNode.addEventListener( 'dispose', dispose );
  36453. //
  36454. const onInitFn = computeNode.onInitFunction;
  36455. if ( onInitFn !== null ) {
  36456. onInitFn.call( computeNode, { renderer: this } );
  36457. }
  36458. }
  36459. nodes.updateForCompute( computeNode );
  36460. bindings.updateForCompute( computeNode );
  36461. const computeBindings = bindings.getForCompute( computeNode );
  36462. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36463. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36464. }
  36465. backend.finishCompute( computeNodes );
  36466. //
  36467. nodeFrame.renderId = previousRenderId;
  36468. }
  36469. /**
  36470. * Execute a single or an array of compute nodes.
  36471. *
  36472. * @async
  36473. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36474. * @return {Promise} A Promise that resolve when the compute has finished.
  36475. */
  36476. async computeAsync( computeNodes ) {
  36477. if ( this._initialized === false ) await this.init();
  36478. this.compute( computeNodes );
  36479. }
  36480. /**
  36481. * Checks if the given feature is supported by the selected backend.
  36482. *
  36483. * @async
  36484. * @param {string} name - The feature's name.
  36485. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36486. */
  36487. async hasFeatureAsync( name ) {
  36488. if ( this._initialized === false ) await this.init();
  36489. return this.backend.hasFeature( name );
  36490. }
  36491. async resolveTimestampsAsync( type = 'render' ) {
  36492. if ( this._initialized === false ) await this.init();
  36493. return this.backend.resolveTimestampsAsync( type );
  36494. }
  36495. /**
  36496. * Checks if the given feature is supported by the selected backend. If the
  36497. * renderer has not been initialized, this method always returns `false`.
  36498. *
  36499. * @param {string} name - The feature's name.
  36500. * @return {boolean} Whether the feature is supported or not.
  36501. */
  36502. hasFeature( name ) {
  36503. if ( this._initialized === false ) {
  36504. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36505. return false;
  36506. }
  36507. return this.backend.hasFeature( name );
  36508. }
  36509. /**
  36510. * Returns `true` when the renderer has been initialized.
  36511. *
  36512. * @return {boolean} Whether the renderer has been initialized or not.
  36513. */
  36514. hasInitialized() {
  36515. return this._initialized;
  36516. }
  36517. /**
  36518. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36519. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36520. *
  36521. * @async
  36522. * @param {Texture} texture - The texture.
  36523. * @return {Promise} A Promise that resolves when the texture has been initialized.
  36524. */
  36525. async initTextureAsync( texture ) {
  36526. if ( this._initialized === false ) await this.init();
  36527. this._textures.updateTexture( texture );
  36528. }
  36529. /**
  36530. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36531. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36532. *
  36533. * This method can only be used if the renderer has been initialized.
  36534. *
  36535. * @param {Texture} texture - The texture.
  36536. */
  36537. initTexture( texture ) {
  36538. if ( this._initialized === false ) {
  36539. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  36540. }
  36541. this._textures.updateTexture( texture );
  36542. }
  36543. /**
  36544. * Copies the current bound framebuffer into the given texture.
  36545. *
  36546. * @param {FramebufferTexture} framebufferTexture - The texture.
  36547. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  36548. */
  36549. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  36550. if ( rectangle !== null ) {
  36551. if ( rectangle.isVector2 ) {
  36552. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  36553. } else if ( rectangle.isVector4 ) {
  36554. rectangle = _vector4.copy( rectangle ).floor();
  36555. } else {
  36556. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  36557. return;
  36558. }
  36559. } else {
  36560. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  36561. }
  36562. //
  36563. let renderContext = this._currentRenderContext;
  36564. let renderTarget;
  36565. if ( renderContext !== null ) {
  36566. renderTarget = renderContext.renderTarget;
  36567. } else {
  36568. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36569. if ( renderTarget !== null ) {
  36570. this._textures.updateRenderTarget( renderTarget );
  36571. renderContext = this._textures.get( renderTarget );
  36572. }
  36573. }
  36574. //
  36575. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  36576. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  36577. }
  36578. /**
  36579. * Copies data of source texture into a destination texture.
  36580. *
  36581. * @param {Texture} srcTexture - The source texture.
  36582. * @param {Texture} dstTexture - The destination texture.
  36583. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  36584. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  36585. * @param {number} level - The mipmap level to copy.
  36586. */
  36587. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36588. this._textures.updateTexture( srcTexture );
  36589. this._textures.updateTexture( dstTexture );
  36590. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36591. }
  36592. /**
  36593. * Reads pixel data from the given render target.
  36594. *
  36595. * @async
  36596. * @param {RenderTarget} renderTarget - The render target to read from.
  36597. * @param {number} x - The `x` coordinate of the copy region's origin.
  36598. * @param {number} y - The `y` coordinate of the copy region's origin.
  36599. * @param {number} width - The width of the copy region.
  36600. * @param {number} height - The height of the copy region.
  36601. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  36602. * @param {number} [faceIndex=0] - The active cube face index.
  36603. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  36604. */
  36605. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  36606. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  36607. }
  36608. /**
  36609. * Analyzes the given 3D object's hierarchy and builds render lists from the
  36610. * processed hierarchy.
  36611. *
  36612. * @param {Object3D} object - The 3D object to process (usually a scene).
  36613. * @param {Camera} camera - The camera the object is rendered with.
  36614. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  36615. * @param {RenderList} renderList - The current render list.
  36616. * @param {ClippingContext} clippingContext - The current clipping context.
  36617. */
  36618. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  36619. if ( object.visible === false ) return;
  36620. const visible = object.layers.test( camera.layers );
  36621. if ( visible ) {
  36622. if ( object.isGroup ) {
  36623. groupOrder = object.renderOrder;
  36624. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  36625. } else if ( object.isLOD ) {
  36626. if ( object.autoUpdate === true ) object.update( camera );
  36627. } else if ( object.isLight ) {
  36628. renderList.pushLight( object );
  36629. } else if ( object.isSprite ) {
  36630. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36631. if ( this.sortObjects === true ) {
  36632. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36633. }
  36634. const { geometry, material } = object;
  36635. if ( material.visible ) {
  36636. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36637. }
  36638. }
  36639. } else if ( object.isLineLoop ) {
  36640. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36641. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36642. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36643. const { geometry, material } = object;
  36644. if ( this.sortObjects === true ) {
  36645. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36646. _vector4
  36647. .copy( geometry.boundingSphere.center )
  36648. .applyMatrix4( object.matrixWorld )
  36649. .applyMatrix4( _projScreenMatrix );
  36650. }
  36651. if ( Array.isArray( material ) ) {
  36652. const groups = geometry.groups;
  36653. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36654. const group = groups[ i ];
  36655. const groupMaterial = material[ group.materialIndex ];
  36656. if ( groupMaterial && groupMaterial.visible ) {
  36657. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  36658. }
  36659. }
  36660. } else if ( material.visible ) {
  36661. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36662. }
  36663. }
  36664. }
  36665. }
  36666. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  36667. const baseRenderList = renderList;
  36668. // replace render list
  36669. renderList = this._renderLists.get( object, camera );
  36670. renderList.begin();
  36671. baseRenderList.pushBundle( {
  36672. bundleGroup: object,
  36673. camera,
  36674. renderList,
  36675. } );
  36676. renderList.finish();
  36677. }
  36678. const children = object.children;
  36679. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36680. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  36681. }
  36682. }
  36683. /**
  36684. * Renders the given render bundles.
  36685. *
  36686. * @private
  36687. * @param {Array<Object>} bundles - Array with render bundle data.
  36688. * @param {Scene} sceneRef - The scene the render bundles belong to.
  36689. * @param {LightsNode} lightsNode - The current lights node.
  36690. */
  36691. _renderBundles( bundles, sceneRef, lightsNode ) {
  36692. for ( const bundle of bundles ) {
  36693. this._renderBundle( bundle, sceneRef, lightsNode );
  36694. }
  36695. }
  36696. /**
  36697. * Renders the transparent objects from the given render lists.
  36698. *
  36699. * @private
  36700. * @param {Array<Object>} renderList - The transparent render list.
  36701. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  36702. * @param {Camera} camera - The camera the render list should be rendered with.
  36703. * @param {Scene} scene - The scene the render list belongs to.
  36704. * @param {LightsNode} lightsNode - The current lights node.
  36705. */
  36706. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  36707. if ( doublePassList.length > 0 ) {
  36708. // render back side
  36709. for ( const { material } of doublePassList ) {
  36710. material.side = BackSide;
  36711. }
  36712. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  36713. // render front side
  36714. for ( const { material } of doublePassList ) {
  36715. material.side = FrontSide;
  36716. }
  36717. this._renderObjects( renderList, camera, scene, lightsNode );
  36718. // restore
  36719. for ( const { material } of doublePassList ) {
  36720. material.side = DoubleSide;
  36721. }
  36722. } else {
  36723. this._renderObjects( renderList, camera, scene, lightsNode );
  36724. }
  36725. }
  36726. /**
  36727. * Renders the objects from the given render list.
  36728. *
  36729. * @private
  36730. * @param {Array<Object>} renderList - The render list.
  36731. * @param {Camera} camera - The camera the render list should be rendered with.
  36732. * @param {Scene} scene - The scene the render list belongs to.
  36733. * @param {LightsNode} lightsNode - The current lights node.
  36734. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36735. */
  36736. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  36737. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36738. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  36739. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  36740. }
  36741. }
  36742. /**
  36743. * This method represents the default render object function that manages the render lifecycle
  36744. * of the object.
  36745. *
  36746. * @param {Object3D} object - The 3D object.
  36747. * @param {Scene} scene - The scene the 3D object belongs to.
  36748. * @param {Camera} camera - The camera the object should be rendered with.
  36749. * @param {BufferGeometry} geometry - The object's geometry.
  36750. * @param {Material} material - The object's material.
  36751. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36752. * @param {LightsNode} lightsNode - The current lights node.
  36753. * @param {ClippingContext} clippingContext - The clipping context.
  36754. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36755. */
  36756. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  36757. let overridePositionNode;
  36758. let overrideColorNode;
  36759. let overrideDepthNode;
  36760. //
  36761. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36762. //
  36763. if ( scene.overrideMaterial !== null ) {
  36764. const overrideMaterial = scene.overrideMaterial;
  36765. if ( material.positionNode && material.positionNode.isNode ) {
  36766. overridePositionNode = overrideMaterial.positionNode;
  36767. overrideMaterial.positionNode = material.positionNode;
  36768. }
  36769. overrideMaterial.alphaTest = material.alphaTest;
  36770. overrideMaterial.alphaMap = material.alphaMap;
  36771. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  36772. if ( overrideMaterial.isShadowPassMaterial ) {
  36773. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36774. if ( material.depthNode && material.depthNode.isNode ) {
  36775. overrideDepthNode = overrideMaterial.depthNode;
  36776. overrideMaterial.depthNode = material.depthNode;
  36777. }
  36778. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  36779. overrideColorNode = overrideMaterial.colorNode;
  36780. overrideMaterial.colorNode = material.castShadowNode;
  36781. }
  36782. }
  36783. material = overrideMaterial;
  36784. }
  36785. //
  36786. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36787. material.side = BackSide;
  36788. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  36789. material.side = FrontSide;
  36790. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  36791. material.side = DoubleSide;
  36792. } else {
  36793. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  36794. }
  36795. //
  36796. if ( overridePositionNode !== undefined ) {
  36797. scene.overrideMaterial.positionNode = overridePositionNode;
  36798. }
  36799. if ( overrideDepthNode !== undefined ) {
  36800. scene.overrideMaterial.depthNode = overrideDepthNode;
  36801. }
  36802. if ( overrideColorNode !== undefined ) {
  36803. scene.overrideMaterial.colorNode = overrideColorNode;
  36804. }
  36805. //
  36806. object.onAfterRender( this, scene, camera, geometry, material, group );
  36807. }
  36808. /**
  36809. * This method represents the default `_handleObjectFunction` implementation which creates
  36810. * a render object from the given data and performs the draw command with the selected backend.
  36811. *
  36812. * @private
  36813. * @param {Object3D} object - The 3D object.
  36814. * @param {Material} material - The object's material.
  36815. * @param {Scene} scene - The scene the 3D object belongs to.
  36816. * @param {Camera} camera - The camera the object should be rendered with.
  36817. * @param {LightsNode} lightsNode - The current lights node.
  36818. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36819. * @param {ClippingContext} clippingContext - The clipping context.
  36820. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36821. */
  36822. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36823. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36824. renderObject.drawRange = object.geometry.drawRange;
  36825. renderObject.group = group;
  36826. //
  36827. const needsRefresh = this._nodes.needsRefresh( renderObject );
  36828. if ( needsRefresh ) {
  36829. this._nodes.updateBefore( renderObject );
  36830. this._geometries.updateForRender( renderObject );
  36831. this._nodes.updateForRender( renderObject );
  36832. this._bindings.updateForRender( renderObject );
  36833. }
  36834. this._pipelines.updateForRender( renderObject );
  36835. //
  36836. if ( this._currentRenderBundle !== null ) {
  36837. const renderBundleData = this.backend.get( this._currentRenderBundle );
  36838. renderBundleData.renderObjects.push( renderObject );
  36839. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  36840. }
  36841. this.backend.draw( renderObject, this.info );
  36842. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  36843. }
  36844. /**
  36845. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  36846. * Used in `compileAsync()`.
  36847. *
  36848. * @private
  36849. * @param {Object3D} object - The 3D object.
  36850. * @param {Material} material - The object's material.
  36851. * @param {Scene} scene - The scene the 3D object belongs to.
  36852. * @param {Camera} camera - The camera the object should be rendered with.
  36853. * @param {LightsNode} lightsNode - The current lights node.
  36854. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36855. * @param {ClippingContext} clippingContext - The clipping context.
  36856. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36857. */
  36858. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36859. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36860. renderObject.drawRange = object.geometry.drawRange;
  36861. renderObject.group = group;
  36862. //
  36863. this._nodes.updateBefore( renderObject );
  36864. this._geometries.updateForRender( renderObject );
  36865. this._nodes.updateForRender( renderObject );
  36866. this._bindings.updateForRender( renderObject );
  36867. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36868. this._nodes.updateAfter( renderObject );
  36869. }
  36870. /**
  36871. * Alias for `compileAsync()`.
  36872. *
  36873. * @method
  36874. * @param {Object3D} scene - The scene or 3D object to precompile.
  36875. * @param {Camera} camera - The camera that is used to render the scene.
  36876. * @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.
  36877. * @return {Promise} A Promise that resolves when the compile has been finished.
  36878. */
  36879. get compile() {
  36880. return this.compileAsync;
  36881. }
  36882. }
  36883. /**
  36884. * A binding represents the connection between a resource (like a texture, sampler
  36885. * or uniform buffer) and the resource definition in a shader stage.
  36886. *
  36887. * This module is an abstract base class for all concrete bindings types.
  36888. *
  36889. * @abstract
  36890. * @private
  36891. */
  36892. class Binding {
  36893. /**
  36894. * Constructs a new binding.
  36895. *
  36896. * @param {string} [name=''] - The binding's name.
  36897. */
  36898. constructor( name = '' ) {
  36899. /**
  36900. * The binding's name.
  36901. *
  36902. * @type {string}
  36903. */
  36904. this.name = name;
  36905. /**
  36906. * A bitmask that defines in what shader stages the
  36907. * binding's resource is accessible.
  36908. *
  36909. * @type {number}
  36910. */
  36911. this.visibility = 0;
  36912. }
  36913. /**
  36914. * Makes sure binding's resource is visible for the given shader stage.
  36915. *
  36916. * @param {number} visibility - The shader stage.
  36917. */
  36918. setVisibility( visibility ) {
  36919. this.visibility |= visibility;
  36920. }
  36921. /**
  36922. * Clones the binding.
  36923. *
  36924. * @return {Binding} The cloned binding.
  36925. */
  36926. clone() {
  36927. return Object.assign( new this.constructor(), this );
  36928. }
  36929. }
  36930. /**
  36931. * This function is usually called with the length in bytes of an array buffer.
  36932. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  36933. *
  36934. * @function
  36935. * @param {number} floatLength - The buffer length.
  36936. * @return {number} The padded length.
  36937. */
  36938. function getFloatLength( floatLength ) {
  36939. // ensure chunk size alignment (STD140 layout)
  36940. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36941. }
  36942. /**
  36943. * Represents a buffer binding type.
  36944. *
  36945. * @private
  36946. * @abstract
  36947. * @augments Binding
  36948. */
  36949. class Buffer extends Binding {
  36950. /**
  36951. * Constructs a new buffer.
  36952. *
  36953. * @param {string} name - The buffer's name.
  36954. * @param {TypedArray} [buffer=null] - The buffer.
  36955. */
  36956. constructor( name, buffer = null ) {
  36957. super( name );
  36958. /**
  36959. * This flag can be used for type testing.
  36960. *
  36961. * @type {boolean}
  36962. * @readonly
  36963. * @default true
  36964. */
  36965. this.isBuffer = true;
  36966. /**
  36967. * The bytes per element.
  36968. *
  36969. * @type {number}
  36970. */
  36971. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36972. /**
  36973. * A reference to the internal buffer.
  36974. *
  36975. * @private
  36976. * @type {TypedArray}
  36977. */
  36978. this._buffer = buffer;
  36979. }
  36980. /**
  36981. * The buffer's byte length.
  36982. *
  36983. * @type {number}
  36984. * @readonly
  36985. */
  36986. get byteLength() {
  36987. return getFloatLength( this._buffer.byteLength );
  36988. }
  36989. /**
  36990. * A reference to the internal buffer.
  36991. *
  36992. * @type {Float32Array}
  36993. * @readonly
  36994. */
  36995. get buffer() {
  36996. return this._buffer;
  36997. }
  36998. /**
  36999. * Updates the binding.
  37000. *
  37001. * @return {boolean} Whether the buffer has been updated and must be
  37002. * uploaded to the GPU.
  37003. */
  37004. update() {
  37005. return true;
  37006. }
  37007. }
  37008. /**
  37009. * Represents a uniform buffer binding type.
  37010. *
  37011. * @private
  37012. * @augments Buffer
  37013. */
  37014. class UniformBuffer extends Buffer {
  37015. /**
  37016. * Constructs a new uniform buffer.
  37017. *
  37018. * @param {string} name - The buffer's name.
  37019. * @param {TypedArray} [buffer=null] - The buffer.
  37020. */
  37021. constructor( name, buffer = null ) {
  37022. super( name, buffer );
  37023. /**
  37024. * This flag can be used for type testing.
  37025. *
  37026. * @type {boolean}
  37027. * @readonly
  37028. * @default true
  37029. */
  37030. this.isUniformBuffer = true;
  37031. }
  37032. }
  37033. let _id$4 = 0;
  37034. /**
  37035. * A special form of uniform buffer binding type.
  37036. * It's buffer value is managed by a node object.
  37037. *
  37038. * @private
  37039. * @augments UniformBuffer
  37040. */
  37041. class NodeUniformBuffer extends UniformBuffer {
  37042. /**
  37043. * Constructs a new node-based uniform buffer.
  37044. *
  37045. * @param {BufferNode} nodeUniform - The uniform buffer node.
  37046. * @param {UniformGroupNode} groupNode - The uniform group node.
  37047. */
  37048. constructor( nodeUniform, groupNode ) {
  37049. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37050. /**
  37051. * The uniform buffer node.
  37052. *
  37053. * @type {BufferNode}
  37054. */
  37055. this.nodeUniform = nodeUniform;
  37056. /**
  37057. * The uniform group node.
  37058. *
  37059. * @type {UniformGroupNode}
  37060. */
  37061. this.groupNode = groupNode;
  37062. }
  37063. /**
  37064. * The uniform buffer.
  37065. *
  37066. * @type {Float32Array}
  37067. */
  37068. get buffer() {
  37069. return this.nodeUniform.value;
  37070. }
  37071. }
  37072. /**
  37073. * This class represents a uniform buffer binding but with
  37074. * an API that allows to maintain individual uniform objects.
  37075. *
  37076. * @private
  37077. * @augments UniformBuffer
  37078. */
  37079. class UniformsGroup extends UniformBuffer {
  37080. /**
  37081. * Constructs a new uniforms group.
  37082. *
  37083. * @param {string} name - The group's name.
  37084. */
  37085. constructor( name ) {
  37086. super( name );
  37087. /**
  37088. * This flag can be used for type testing.
  37089. *
  37090. * @type {boolean}
  37091. * @readonly
  37092. * @default true
  37093. */
  37094. this.isUniformsGroup = true;
  37095. /**
  37096. * An array with the raw uniform values.
  37097. *
  37098. * @private
  37099. * @type {?Array<number>}
  37100. * @default null
  37101. */
  37102. this._values = null;
  37103. /**
  37104. * An array of uniform objects.
  37105. *
  37106. * The order of uniforms in this array must match the order of uniforms in the shader.
  37107. *
  37108. * @type {Array<Uniform>}
  37109. */
  37110. this.uniforms = [];
  37111. }
  37112. /**
  37113. * Adds a uniform to this group.
  37114. *
  37115. * @param {Uniform} uniform - The uniform to add.
  37116. * @return {UniformsGroup} A reference to this group.
  37117. */
  37118. addUniform( uniform ) {
  37119. this.uniforms.push( uniform );
  37120. return this;
  37121. }
  37122. /**
  37123. * Removes a uniform from this group.
  37124. *
  37125. * @param {Uniform} uniform - The uniform to remove.
  37126. * @return {UniformsGroup} A reference to this group.
  37127. */
  37128. removeUniform( uniform ) {
  37129. const index = this.uniforms.indexOf( uniform );
  37130. if ( index !== -1 ) {
  37131. this.uniforms.splice( index, 1 );
  37132. }
  37133. return this;
  37134. }
  37135. /**
  37136. * An array with the raw uniform values.
  37137. *
  37138. * @type {Array<number>}
  37139. */
  37140. get values() {
  37141. if ( this._values === null ) {
  37142. this._values = Array.from( this.buffer );
  37143. }
  37144. return this._values;
  37145. }
  37146. /**
  37147. * A Float32 array buffer with the uniform values.
  37148. *
  37149. * @type {Float32Array}
  37150. */
  37151. get buffer() {
  37152. let buffer = this._buffer;
  37153. if ( buffer === null ) {
  37154. const byteLength = this.byteLength;
  37155. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37156. this._buffer = buffer;
  37157. }
  37158. return buffer;
  37159. }
  37160. /**
  37161. * The byte length of the buffer with correct buffer alignment.
  37162. *
  37163. * @type {number}
  37164. */
  37165. get byteLength() {
  37166. let offset = 0; // global buffer offset in bytes
  37167. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37168. const uniform = this.uniforms[ i ];
  37169. const { boundary, itemSize } = uniform;
  37170. // offset within a single chunk in bytes
  37171. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37172. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37173. // conformance tests
  37174. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37175. // check for chunk overflow
  37176. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37177. } else if ( chunkOffset % boundary !== 0 ) {
  37178. // check for correct alignment
  37179. offset += ( chunkOffset % boundary );
  37180. }
  37181. uniform.offset = ( offset / this.bytesPerElement );
  37182. offset += ( itemSize * this.bytesPerElement );
  37183. }
  37184. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37185. }
  37186. /**
  37187. * Updates this group by updating each uniform object of
  37188. * the internal uniform list. The uniform objects check if their
  37189. * values has actually changed so this method only returns
  37190. * `true` if there is a real value change.
  37191. *
  37192. * @return {boolean} Whether the uniforms have been updated and
  37193. * must be uploaded to the GPU.
  37194. */
  37195. update() {
  37196. let updated = false;
  37197. for ( const uniform of this.uniforms ) {
  37198. if ( this.updateByType( uniform ) === true ) {
  37199. updated = true;
  37200. }
  37201. }
  37202. return updated;
  37203. }
  37204. /**
  37205. * Updates a given uniform by calling an update method matching
  37206. * the uniforms type.
  37207. *
  37208. * @param {Uniform} uniform - The uniform to update.
  37209. * @return {boolean} Whether the uniform has been updated or not.
  37210. */
  37211. updateByType( uniform ) {
  37212. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37213. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37214. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37215. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37216. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37217. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37218. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37219. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37220. }
  37221. /**
  37222. * Updates a given Number uniform.
  37223. *
  37224. * @param {NumberUniform} uniform - The Number uniform.
  37225. * @return {boolean} Whether the uniform has been updated or not.
  37226. */
  37227. updateNumber( uniform ) {
  37228. let updated = false;
  37229. const a = this.values;
  37230. const v = uniform.getValue();
  37231. const offset = uniform.offset;
  37232. const type = uniform.getType();
  37233. if ( a[ offset ] !== v ) {
  37234. const b = this._getBufferForType( type );
  37235. b[ offset ] = a[ offset ] = v;
  37236. updated = true;
  37237. }
  37238. return updated;
  37239. }
  37240. /**
  37241. * Updates a given Vector2 uniform.
  37242. *
  37243. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  37244. * @return {boolean} Whether the uniform has been updated or not.
  37245. */
  37246. updateVector2( uniform ) {
  37247. let updated = false;
  37248. const a = this.values;
  37249. const v = uniform.getValue();
  37250. const offset = uniform.offset;
  37251. const type = uniform.getType();
  37252. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37253. const b = this._getBufferForType( type );
  37254. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37255. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37256. updated = true;
  37257. }
  37258. return updated;
  37259. }
  37260. /**
  37261. * Updates a given Vector3 uniform.
  37262. *
  37263. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  37264. * @return {boolean} Whether the uniform has been updated or not.
  37265. */
  37266. updateVector3( uniform ) {
  37267. let updated = false;
  37268. const a = this.values;
  37269. const v = uniform.getValue();
  37270. const offset = uniform.offset;
  37271. const type = uniform.getType();
  37272. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  37273. const b = this._getBufferForType( type );
  37274. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37275. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37276. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37277. updated = true;
  37278. }
  37279. return updated;
  37280. }
  37281. /**
  37282. * Updates a given Vector4 uniform.
  37283. *
  37284. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  37285. * @return {boolean} Whether the uniform has been updated or not.
  37286. */
  37287. updateVector4( uniform ) {
  37288. let updated = false;
  37289. const a = this.values;
  37290. const v = uniform.getValue();
  37291. const offset = uniform.offset;
  37292. const type = uniform.getType();
  37293. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  37294. const b = this._getBufferForType( type );
  37295. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37296. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37297. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37298. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  37299. updated = true;
  37300. }
  37301. return updated;
  37302. }
  37303. /**
  37304. * Updates a given Color uniform.
  37305. *
  37306. * @param {ColorUniform} uniform - The Color uniform.
  37307. * @return {boolean} Whether the uniform has been updated or not.
  37308. */
  37309. updateColor( uniform ) {
  37310. let updated = false;
  37311. const a = this.values;
  37312. const c = uniform.getValue();
  37313. const offset = uniform.offset;
  37314. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  37315. const b = this.buffer;
  37316. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  37317. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  37318. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  37319. updated = true;
  37320. }
  37321. return updated;
  37322. }
  37323. /**
  37324. * Updates a given Matrix3 uniform.
  37325. *
  37326. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  37327. * @return {boolean} Whether the uniform has been updated or not.
  37328. */
  37329. updateMatrix3( uniform ) {
  37330. let updated = false;
  37331. const a = this.values;
  37332. const e = uniform.getValue().elements;
  37333. const offset = uniform.offset;
  37334. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  37335. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  37336. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  37337. const b = this.buffer;
  37338. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  37339. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  37340. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  37341. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  37342. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  37343. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  37344. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  37345. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  37346. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  37347. updated = true;
  37348. }
  37349. return updated;
  37350. }
  37351. /**
  37352. * Updates a given Matrix4 uniform.
  37353. *
  37354. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  37355. * @return {boolean} Whether the uniform has been updated or not.
  37356. */
  37357. updateMatrix4( uniform ) {
  37358. let updated = false;
  37359. const a = this.values;
  37360. const e = uniform.getValue().elements;
  37361. const offset = uniform.offset;
  37362. if ( arraysEqual( a, e, offset ) === false ) {
  37363. const b = this.buffer;
  37364. b.set( e, offset );
  37365. setArray( a, e, offset );
  37366. updated = true;
  37367. }
  37368. return updated;
  37369. }
  37370. /**
  37371. * Returns a typed array that matches the given data type.
  37372. *
  37373. * @param {string} type - The data type.
  37374. * @return {TypedArray} The typed array.
  37375. */
  37376. _getBufferForType( type ) {
  37377. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  37378. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  37379. return this.buffer;
  37380. }
  37381. }
  37382. /**
  37383. * Sets the values of the second array to the first array.
  37384. *
  37385. * @private
  37386. * @param {TypedArray} a - The first array.
  37387. * @param {TypedArray} b - The second array.
  37388. * @param {number} offset - An index offset for the first array.
  37389. */
  37390. function setArray( a, b, offset ) {
  37391. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37392. a[ offset + i ] = b[ i ];
  37393. }
  37394. }
  37395. /**
  37396. * Returns `true` if the given arrays are equal.
  37397. *
  37398. * @private
  37399. * @param {TypedArray} a - The first array.
  37400. * @param {TypedArray} b - The second array.
  37401. * @param {number} offset - An index offset for the first array.
  37402. * @return {boolean} Whether the given arrays are equal or not.
  37403. */
  37404. function arraysEqual( a, b, offset ) {
  37405. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37406. if ( a[ offset + i ] !== b[ i ] ) return false;
  37407. }
  37408. return true;
  37409. }
  37410. let _id$3 = 0;
  37411. /**
  37412. * A special form of uniforms group that represents
  37413. * the individual uniforms as node-based uniforms.
  37414. *
  37415. * @private
  37416. * @augments UniformsGroup
  37417. */
  37418. class NodeUniformsGroup extends UniformsGroup {
  37419. /**
  37420. * Constructs a new node-based uniforms group.
  37421. *
  37422. * @param {string} name - The group's name.
  37423. * @param {UniformGroupNode} groupNode - The uniform group node.
  37424. */
  37425. constructor( name, groupNode ) {
  37426. super( name );
  37427. /**
  37428. * The group's ID.
  37429. *
  37430. * @type {number}
  37431. */
  37432. this.id = _id$3 ++;
  37433. /**
  37434. * The uniform group node.
  37435. *
  37436. * @type {UniformGroupNode}
  37437. */
  37438. this.groupNode = groupNode;
  37439. /**
  37440. * This flag can be used for type testing.
  37441. *
  37442. * @type {boolean}
  37443. * @readonly
  37444. * @default true
  37445. */
  37446. this.isNodeUniformsGroup = true;
  37447. }
  37448. }
  37449. let _id$2 = 0;
  37450. /**
  37451. * Represents a sampled texture binding type.
  37452. *
  37453. * @private
  37454. * @augments Binding
  37455. */
  37456. class SampledTexture extends Binding {
  37457. /**
  37458. * Constructs a new sampled texture.
  37459. *
  37460. * @param {string} name - The sampled texture's name.
  37461. * @param {?Texture} texture - The texture this binding is referring to.
  37462. */
  37463. constructor( name, texture ) {
  37464. super( name );
  37465. /**
  37466. * This identifier.
  37467. *
  37468. * @type {number}
  37469. */
  37470. this.id = _id$2 ++;
  37471. /**
  37472. * The texture this binding is referring to.
  37473. *
  37474. * @type {?Texture}
  37475. */
  37476. this.texture = texture;
  37477. /**
  37478. * The binding's version.
  37479. *
  37480. * @type {number}
  37481. */
  37482. this.version = texture ? texture.version : 0;
  37483. /**
  37484. * Whether the texture is a storage texture or not.
  37485. *
  37486. * @type {boolean}
  37487. * @default false
  37488. */
  37489. this.store = false;
  37490. /**
  37491. * The binding's generation which is an additional version
  37492. * qualifier.
  37493. *
  37494. * @type {?number}
  37495. * @default null
  37496. */
  37497. this.generation = null;
  37498. /**
  37499. * This flag can be used for type testing.
  37500. *
  37501. * @type {boolean}
  37502. * @readonly
  37503. * @default true
  37504. */
  37505. this.isSampledTexture = true;
  37506. }
  37507. /**
  37508. * Returns `true` whether this binding requires an update for the
  37509. * given generation.
  37510. *
  37511. * @param {number} generation - The generation.
  37512. * @return {boolean} Whether an update is required or not.
  37513. */
  37514. needsBindingsUpdate( generation ) {
  37515. const { texture } = this;
  37516. if ( generation !== this.generation ) {
  37517. this.generation = generation;
  37518. return true;
  37519. }
  37520. return texture.isVideoTexture;
  37521. }
  37522. /**
  37523. * Updates the binding.
  37524. *
  37525. * @return {boolean} Whether the texture has been updated and must be
  37526. * uploaded to the GPU.
  37527. */
  37528. update() {
  37529. const { texture, version } = this;
  37530. if ( version !== texture.version ) {
  37531. this.version = texture.version;
  37532. return true;
  37533. }
  37534. return false;
  37535. }
  37536. }
  37537. /**
  37538. * A special form of sampled texture binding type.
  37539. * It's texture value is managed by a node object.
  37540. *
  37541. * @private
  37542. * @augments SampledTexture
  37543. */
  37544. class NodeSampledTexture extends SampledTexture {
  37545. /**
  37546. * Constructs a new node-based sampled texture.
  37547. *
  37548. * @param {string} name - The textures's name.
  37549. * @param {TextureNode} textureNode - The texture node.
  37550. * @param {UniformGroupNode} groupNode - The uniform group node.
  37551. * @param {?string} [access=null] - The access type.
  37552. */
  37553. constructor( name, textureNode, groupNode, access = null ) {
  37554. super( name, textureNode ? textureNode.value : null );
  37555. /**
  37556. * The texture node.
  37557. *
  37558. * @type {TextureNode}
  37559. */
  37560. this.textureNode = textureNode;
  37561. /**
  37562. * The uniform group node.
  37563. *
  37564. * @type {UniformGroupNode}
  37565. */
  37566. this.groupNode = groupNode;
  37567. /**
  37568. * The access type.
  37569. *
  37570. * @type {?string}
  37571. * @default null
  37572. */
  37573. this.access = access;
  37574. }
  37575. /**
  37576. * Overwrites the default to additionally check if the node value has changed.
  37577. *
  37578. * @param {number} generation - The generation.
  37579. * @return {boolean} Whether an update is required or not.
  37580. */
  37581. needsBindingsUpdate( generation ) {
  37582. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  37583. }
  37584. /**
  37585. * Updates the binding.
  37586. *
  37587. * @return {boolean} Whether the texture has been updated and must be
  37588. * uploaded to the GPU.
  37589. */
  37590. update() {
  37591. const { textureNode } = this;
  37592. if ( this.texture !== textureNode.value ) {
  37593. this.texture = textureNode.value;
  37594. return true;
  37595. }
  37596. return super.update();
  37597. }
  37598. }
  37599. /**
  37600. * A special form of sampled cube texture binding type.
  37601. * It's texture value is managed by a node object.
  37602. *
  37603. * @private
  37604. * @augments NodeSampledTexture
  37605. */
  37606. class NodeSampledCubeTexture extends NodeSampledTexture {
  37607. /**
  37608. * Constructs a new node-based sampled cube texture.
  37609. *
  37610. * @param {string} name - The textures's name.
  37611. * @param {TextureNode} textureNode - The texture node.
  37612. * @param {UniformGroupNode} groupNode - The uniform group node.
  37613. * @param {?string} [access=null] - The access type.
  37614. */
  37615. constructor( name, textureNode, groupNode, access = null ) {
  37616. super( name, textureNode, groupNode, access );
  37617. /**
  37618. * This flag can be used for type testing.
  37619. *
  37620. * @type {boolean}
  37621. * @readonly
  37622. * @default true
  37623. */
  37624. this.isSampledCubeTexture = true;
  37625. }
  37626. }
  37627. /**
  37628. * A special form of sampled 3D texture binding type.
  37629. * It's texture value is managed by a node object.
  37630. *
  37631. * @private
  37632. * @augments NodeSampledTexture
  37633. */
  37634. class NodeSampledTexture3D extends NodeSampledTexture {
  37635. /**
  37636. * Constructs a new node-based sampled 3D texture.
  37637. *
  37638. * @param {string} name - The textures's name.
  37639. * @param {TextureNode} textureNode - The texture node.
  37640. * @param {UniformGroupNode} groupNode - The uniform group node.
  37641. * @param {?string} [access=null] - The access type.
  37642. */
  37643. constructor( name, textureNode, groupNode, access = null ) {
  37644. super( name, textureNode, groupNode, access );
  37645. /**
  37646. * This flag can be used for type testing.
  37647. *
  37648. * @type {boolean}
  37649. * @readonly
  37650. * @default true
  37651. */
  37652. this.isSampledTexture3D = true;
  37653. }
  37654. }
  37655. const glslMethods = {
  37656. textureDimensions: 'textureSize',
  37657. equals: 'equal'
  37658. };
  37659. const precisionLib = {
  37660. low: 'lowp',
  37661. medium: 'mediump',
  37662. high: 'highp'
  37663. };
  37664. const supports$1 = {
  37665. swizzleAssign: true,
  37666. storageBuffer: false
  37667. };
  37668. const defaultPrecisions = `
  37669. precision highp float;
  37670. precision highp int;
  37671. precision highp sampler2D;
  37672. precision highp sampler3D;
  37673. precision highp samplerCube;
  37674. precision highp sampler2DArray;
  37675. precision highp usampler2D;
  37676. precision highp usampler3D;
  37677. precision highp usamplerCube;
  37678. precision highp usampler2DArray;
  37679. precision highp isampler2D;
  37680. precision highp isampler3D;
  37681. precision highp isamplerCube;
  37682. precision highp isampler2DArray;
  37683. precision lowp sampler2DShadow;
  37684. `;
  37685. /**
  37686. * A node builder targeting GLSL.
  37687. *
  37688. * This module generates GLSL shader code from node materials and also
  37689. * generates the respective bindings and vertex buffer definitions. These
  37690. * data are later used by the renderer to create render and compute pipelines
  37691. * for render objects.
  37692. *
  37693. * @augments NodeBuilder
  37694. */
  37695. class GLSLNodeBuilder extends NodeBuilder {
  37696. /**
  37697. * Constructs a new GLSL node builder renderer.
  37698. *
  37699. * @param {Object3D} object - The 3D object.
  37700. * @param {Renderer} renderer - The renderer.
  37701. */
  37702. constructor( object, renderer ) {
  37703. super( object, renderer, new GLSLNodeParser() );
  37704. /**
  37705. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  37706. * another dictionary which manages UBOs per group ('render','frame','object').
  37707. *
  37708. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  37709. */
  37710. this.uniformGroups = {};
  37711. /**
  37712. * An array that holds objects defining the varying and attribute data in
  37713. * context of Transform Feedback.
  37714. *
  37715. * @type {Object<string,Map<string,Object>>}
  37716. */
  37717. this.transforms = [];
  37718. /**
  37719. * A dictionary that holds for each shader stage a Map of used extensions.
  37720. *
  37721. * @type {Object<string,Map<string,Object>>}
  37722. */
  37723. this.extensions = {};
  37724. /**
  37725. * A dictionary that holds for each shader stage an Array of used builtins.
  37726. *
  37727. * @type {Object<string,Array<string>>}
  37728. */
  37729. this.builtins = { vertex: [], fragment: [], compute: [] };
  37730. /**
  37731. * Whether comparison in shader code are generated with methods or not.
  37732. *
  37733. * @type {boolean}
  37734. * @default true
  37735. */
  37736. this.useComparisonMethod = true;
  37737. }
  37738. /**
  37739. * Checks if the given texture requires a manual conversion to the working color space.
  37740. *
  37741. * @param {Texture} texture - The texture to check.
  37742. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  37743. */
  37744. needsToWorkingColorSpace( texture ) {
  37745. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  37746. }
  37747. /**
  37748. * Returns the native shader method name for a given generic name.
  37749. *
  37750. * @param {string} method - The method name to resolve.
  37751. * @return {string} The resolved GLSL method name.
  37752. */
  37753. getMethod( method ) {
  37754. return glslMethods[ method ] || method;
  37755. }
  37756. /**
  37757. * Returns the output struct name. Not relevant for GLSL.
  37758. *
  37759. * @return {string}
  37760. */
  37761. getOutputStructName() {
  37762. return '';
  37763. }
  37764. /**
  37765. * Builds the given shader node.
  37766. *
  37767. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37768. * @return {string} The GLSL function code.
  37769. */
  37770. buildFunctionCode( shaderNode ) {
  37771. const layout = shaderNode.layout;
  37772. const flowData = this.flowShaderNode( shaderNode );
  37773. const parameters = [];
  37774. for ( const input of layout.inputs ) {
  37775. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37776. }
  37777. //
  37778. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37779. ${ flowData.vars }
  37780. ${ flowData.code }
  37781. return ${ flowData.result };
  37782. }`;
  37783. //
  37784. return code;
  37785. }
  37786. /**
  37787. * Setups the Pixel Buffer Object (PBO) for the given storage
  37788. * buffer node.
  37789. *
  37790. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  37791. */
  37792. setupPBO( storageBufferNode ) {
  37793. const attribute = storageBufferNode.value;
  37794. if ( attribute.pbo === undefined ) {
  37795. const originalArray = attribute.array;
  37796. const numElements = attribute.count * attribute.itemSize;
  37797. const { itemSize } = attribute;
  37798. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37799. let format = isInteger ? RedIntegerFormat : RedFormat;
  37800. if ( itemSize === 2 ) {
  37801. format = isInteger ? RGIntegerFormat : RGFormat;
  37802. } else if ( itemSize === 3 ) {
  37803. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37804. } else if ( itemSize === 4 ) {
  37805. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37806. }
  37807. const typeMap = {
  37808. Float32Array: FloatType,
  37809. Uint8Array: UnsignedByteType,
  37810. Uint16Array: UnsignedShortType,
  37811. Uint32Array: UnsignedIntType,
  37812. Int8Array: ByteType,
  37813. Int16Array: ShortType,
  37814. Int32Array: IntType,
  37815. Uint8ClampedArray: UnsignedByteType,
  37816. };
  37817. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37818. let height = Math.ceil( ( numElements / itemSize ) / width );
  37819. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37820. const newSize = width * height * itemSize;
  37821. const newArray = new originalArray.constructor( newSize );
  37822. newArray.set( originalArray, 0 );
  37823. attribute.array = newArray;
  37824. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37825. pboTexture.needsUpdate = true;
  37826. pboTexture.isPBOTexture = true;
  37827. const pbo = new TextureNode( pboTexture, null, null );
  37828. pbo.setPrecision( 'high' );
  37829. attribute.pboNode = pbo;
  37830. attribute.pbo = pbo.value;
  37831. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37832. }
  37833. }
  37834. /**
  37835. * Returns a GLSL snippet that represents the property name of the given node.
  37836. *
  37837. * @param {Node} node - The node.
  37838. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37839. * @return {string} The property name.
  37840. */
  37841. getPropertyName( node, shaderStage = this.shaderStage ) {
  37842. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37843. return shaderStage.charAt( 0 ) + '_' + node.name;
  37844. }
  37845. return super.getPropertyName( node, shaderStage );
  37846. }
  37847. /**
  37848. * Setups the Pixel Buffer Object (PBO) for the given storage
  37849. * buffer node.
  37850. *
  37851. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  37852. * @return {string} The property name.
  37853. */
  37854. generatePBO( storageArrayElementNode ) {
  37855. const { node, indexNode } = storageArrayElementNode;
  37856. const attribute = node.value;
  37857. if ( this.renderer.backend.has( attribute ) ) {
  37858. const attributeData = this.renderer.backend.get( attribute );
  37859. attributeData.pbo = attribute.pbo;
  37860. }
  37861. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37862. const textureName = this.getPropertyName( nodeUniform );
  37863. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  37864. const indexSnippet = indexNode.build( this, 'uint' );
  37865. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37866. let propertyName = elementNodeData.propertyName;
  37867. if ( propertyName === undefined ) {
  37868. // property element
  37869. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37870. propertyName = this.getPropertyName( nodeVar );
  37871. // property size
  37872. const bufferNodeData = this.getDataFromNode( node );
  37873. let propertySizeName = bufferNodeData.propertySizeName;
  37874. if ( propertySizeName === undefined ) {
  37875. propertySizeName = propertyName + 'Size';
  37876. this.getVarFromNode( node, propertySizeName, 'uint' );
  37877. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  37878. bufferNodeData.propertySizeName = propertySizeName;
  37879. }
  37880. //
  37881. const { itemSize } = attribute;
  37882. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37883. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37884. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37885. //
  37886. let prefix = 'vec4';
  37887. if ( attribute.pbo.type === UnsignedIntType ) {
  37888. prefix = 'uvec4';
  37889. } else if ( attribute.pbo.type === IntType ) {
  37890. prefix = 'ivec4';
  37891. }
  37892. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  37893. elementNodeData.propertyName = propertyName;
  37894. }
  37895. return propertyName;
  37896. }
  37897. /**
  37898. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  37899. *
  37900. * @param {Texture} texture - The texture.
  37901. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37902. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37903. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37904. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37905. * @return {string} The GLSL snippet.
  37906. */
  37907. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37908. if ( depthSnippet ) {
  37909. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37910. } else {
  37911. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37912. }
  37913. }
  37914. /**
  37915. * Generates the GLSL snippet for sampling/loading the given texture.
  37916. *
  37917. * @param {Texture} texture - The texture.
  37918. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37919. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37920. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37921. * @return {string} The GLSL snippet.
  37922. */
  37923. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37924. if ( texture.isDepthTexture ) {
  37925. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37926. } else {
  37927. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37928. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37929. }
  37930. }
  37931. /**
  37932. * Generates the GLSL snippet when sampling textures with explicit mip level.
  37933. *
  37934. * @param {Texture} texture - The texture.
  37935. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37936. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37937. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37938. * @return {string} The GLSL snippet.
  37939. */
  37940. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37941. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37942. }
  37943. /**
  37944. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  37945. *
  37946. * @param {Texture} texture - The texture.
  37947. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37948. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37949. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  37950. * @return {string} The GLSL snippet.
  37951. */
  37952. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37953. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37954. }
  37955. /**
  37956. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  37957. *
  37958. * @param {Texture} texture - The texture.
  37959. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37960. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37961. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  37962. * @return {string} The GLSL snippet.
  37963. */
  37964. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37965. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37966. }
  37967. /**
  37968. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  37969. * against a reference value.
  37970. *
  37971. * @param {Texture} texture - The texture.
  37972. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37973. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37974. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  37975. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  37976. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37977. * @return {string} The GLSL snippet.
  37978. */
  37979. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37980. if ( shaderStage === 'fragment' ) {
  37981. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37982. } else {
  37983. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37984. }
  37985. }
  37986. /**
  37987. * Returns the variables of the given shader stage as a GLSL string.
  37988. *
  37989. * @param {string} shaderStage - The shader stage.
  37990. * @return {string} The GLSL snippet that defines the variables.
  37991. */
  37992. getVars( shaderStage ) {
  37993. const snippets = [];
  37994. const vars = this.vars[ shaderStage ];
  37995. if ( vars !== undefined ) {
  37996. for ( const variable of vars ) {
  37997. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37998. }
  37999. }
  38000. return snippets.join( '\n\t' );
  38001. }
  38002. /**
  38003. * Returns the uniforms of the given shader stage as a GLSL string.
  38004. *
  38005. * @param {string} shaderStage - The shader stage.
  38006. * @return {string} The GLSL snippet that defines the uniforms.
  38007. */
  38008. getUniforms( shaderStage ) {
  38009. const uniforms = this.uniforms[ shaderStage ];
  38010. const bindingSnippets = [];
  38011. const uniformGroups = {};
  38012. for ( const uniform of uniforms ) {
  38013. let snippet = null;
  38014. let group = false;
  38015. if ( uniform.type === 'texture' ) {
  38016. const texture = uniform.node.value;
  38017. let typePrefix = '';
  38018. if ( texture.isDataTexture === true ) {
  38019. if ( texture.type === UnsignedIntType ) {
  38020. typePrefix = 'u';
  38021. } else if ( texture.type === IntType ) {
  38022. typePrefix = 'i';
  38023. }
  38024. }
  38025. if ( texture.compareFunction ) {
  38026. snippet = `sampler2DShadow ${ uniform.name };`;
  38027. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38028. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38029. } else {
  38030. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38031. }
  38032. } else if ( uniform.type === 'cubeTexture' ) {
  38033. snippet = `samplerCube ${ uniform.name };`;
  38034. } else if ( uniform.type === 'texture3D' ) {
  38035. snippet = `sampler3D ${ uniform.name };`;
  38036. } else if ( uniform.type === 'buffer' ) {
  38037. const bufferNode = uniform.node;
  38038. const bufferType = this.getType( bufferNode.bufferType );
  38039. const bufferCount = bufferNode.bufferCount;
  38040. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38041. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38042. } else {
  38043. const vectorType = this.getVectorType( uniform.type );
  38044. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38045. group = true;
  38046. }
  38047. const precision = uniform.node.precision;
  38048. if ( precision !== null ) {
  38049. snippet = precisionLib[ precision ] + ' ' + snippet;
  38050. }
  38051. if ( group ) {
  38052. snippet = '\t' + snippet;
  38053. const groupName = uniform.groupNode.name;
  38054. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38055. groupSnippets.push( snippet );
  38056. } else {
  38057. snippet = 'uniform ' + snippet;
  38058. bindingSnippets.push( snippet );
  38059. }
  38060. }
  38061. let output = '';
  38062. for ( const name in uniformGroups ) {
  38063. const groupSnippets = uniformGroups[ name ];
  38064. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38065. }
  38066. output += bindingSnippets.join( '\n' );
  38067. return output;
  38068. }
  38069. /**
  38070. * Returns the type for a given buffer attribute.
  38071. *
  38072. * @param {BufferAttribute} attribute - The buffer attribute.
  38073. * @return {string} The type.
  38074. */
  38075. getTypeFromAttribute( attribute ) {
  38076. let nodeType = super.getTypeFromAttribute( attribute );
  38077. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38078. let dataAttribute = attribute;
  38079. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38080. const array = dataAttribute.array;
  38081. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38082. nodeType = nodeType.slice( 1 );
  38083. }
  38084. }
  38085. return nodeType;
  38086. }
  38087. /**
  38088. * Returns the shader attributes of the given shader stage as a GLSL string.
  38089. *
  38090. * @param {string} shaderStage - The shader stage.
  38091. * @return {string} The GLSL snippet that defines the shader attributes.
  38092. */
  38093. getAttributes( shaderStage ) {
  38094. let snippet = '';
  38095. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38096. const attributes = this.getAttributesArray();
  38097. let location = 0;
  38098. for ( const attribute of attributes ) {
  38099. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38100. }
  38101. }
  38102. return snippet;
  38103. }
  38104. /**
  38105. * Returns the members of the given struct type node as a GLSL string.
  38106. *
  38107. * @param {StructTypeNode} struct - The struct type node.
  38108. * @return {string} The GLSL snippet that defines the struct members.
  38109. */
  38110. getStructMembers( struct ) {
  38111. const snippets = [];
  38112. for ( const member of struct.members ) {
  38113. snippets.push( `\t${ member.type } ${ member.name };` );
  38114. }
  38115. return snippets.join( '\n' );
  38116. }
  38117. /**
  38118. * Returns the structs of the given shader stage as a GLSL string.
  38119. *
  38120. * @param {string} shaderStage - The shader stage.
  38121. * @return {string} The GLSL snippet that defines the structs.
  38122. */
  38123. getStructs( shaderStage ) {
  38124. const snippets = [];
  38125. const structs = this.structs[ shaderStage ];
  38126. const outputSnippet = [];
  38127. for ( const struct of structs ) {
  38128. if ( struct.output ) {
  38129. for ( const member of struct.members ) {
  38130. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  38131. }
  38132. } else {
  38133. let snippet = 'struct ' + struct.name + ' {\n';
  38134. snippet += this.getStructMembers( struct );
  38135. snippet += '\n};\n';
  38136. snippets.push( snippet );
  38137. }
  38138. }
  38139. if ( outputSnippet.length === 0 ) {
  38140. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  38141. }
  38142. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  38143. }
  38144. /**
  38145. * Returns the varyings of the given shader stage as a GLSL string.
  38146. *
  38147. * @param {string} shaderStage - The shader stage.
  38148. * @return {string} The GLSL snippet that defines the varyings.
  38149. */
  38150. getVaryings( shaderStage ) {
  38151. let snippet = '';
  38152. const varyings = this.varyings;
  38153. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38154. for ( const varying of varyings ) {
  38155. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38156. const type = this.getType( varying.type );
  38157. if ( varying.needsInterpolation ) {
  38158. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38159. snippet += `${flat} out ${type} ${varying.name};\n`;
  38160. } else {
  38161. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  38162. }
  38163. }
  38164. } else if ( shaderStage === 'fragment' ) {
  38165. for ( const varying of varyings ) {
  38166. if ( varying.needsInterpolation ) {
  38167. const type = this.getType( varying.type );
  38168. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38169. snippet += `${flat}in ${type} ${varying.name};\n`;
  38170. }
  38171. }
  38172. }
  38173. for ( const builtin of this.builtins[ shaderStage ] ) {
  38174. snippet += `${builtin};\n`;
  38175. }
  38176. return snippet;
  38177. }
  38178. /**
  38179. * Returns the vertex index builtin.
  38180. *
  38181. * @return {string} The vertex index.
  38182. */
  38183. getVertexIndex() {
  38184. return 'uint( gl_VertexID )';
  38185. }
  38186. /**
  38187. * Returns the instance index builtin.
  38188. *
  38189. * @return {string} The instance index.
  38190. */
  38191. getInstanceIndex() {
  38192. return 'uint( gl_InstanceID )';
  38193. }
  38194. /**
  38195. * Returns the invocation local index builtin.
  38196. *
  38197. * @return {string} The invocation local index.
  38198. */
  38199. getInvocationLocalIndex() {
  38200. const workgroupSize = this.object.workgroupSize;
  38201. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38202. return `uint( gl_InstanceID ) % ${size}u`;
  38203. }
  38204. /**
  38205. * Returns the draw index builtin.
  38206. *
  38207. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  38208. */
  38209. getDrawIndex() {
  38210. const extensions = this.renderer.backend.extensions;
  38211. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38212. return 'uint( gl_DrawID )';
  38213. }
  38214. return null;
  38215. }
  38216. /**
  38217. * Returns the front facing builtin.
  38218. *
  38219. * @return {string} The front facing builtin.
  38220. */
  38221. getFrontFacing() {
  38222. return 'gl_FrontFacing';
  38223. }
  38224. /**
  38225. * Returns the frag coord builtin.
  38226. *
  38227. * @return {string} The frag coord builtin.
  38228. */
  38229. getFragCoord() {
  38230. return 'gl_FragCoord.xy';
  38231. }
  38232. /**
  38233. * Returns the frag depth builtin.
  38234. *
  38235. * @return {string} The frag depth builtin.
  38236. */
  38237. getFragDepth() {
  38238. return 'gl_FragDepth';
  38239. }
  38240. /**
  38241. * Enables the given extension.
  38242. *
  38243. * @param {string} name - The extension name.
  38244. * @param {string} behavior - The extension behavior.
  38245. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  38246. */
  38247. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38248. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38249. if ( map.has( name ) === false ) {
  38250. map.set( name, {
  38251. name,
  38252. behavior
  38253. } );
  38254. }
  38255. }
  38256. /**
  38257. * Returns the enabled extensions of the given shader stage as a GLSL string.
  38258. *
  38259. * @param {string} shaderStage - The shader stage.
  38260. * @return {string} The GLSL snippet that defines the enabled extensions.
  38261. */
  38262. getExtensions( shaderStage ) {
  38263. const snippets = [];
  38264. if ( shaderStage === 'vertex' ) {
  38265. const ext = this.renderer.backend.extensions;
  38266. const isBatchedMesh = this.object.isBatchedMesh;
  38267. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38268. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38269. }
  38270. }
  38271. const extensions = this.extensions[ shaderStage ];
  38272. if ( extensions !== undefined ) {
  38273. for ( const { name, behavior } of extensions.values() ) {
  38274. snippets.push( `#extension ${name} : ${behavior}` );
  38275. }
  38276. }
  38277. return snippets.join( '\n' );
  38278. }
  38279. /**
  38280. * Returns the clip distances builtin.
  38281. *
  38282. * @return {string} The clip distances builtin.
  38283. */
  38284. getClipDistance() {
  38285. return 'gl_ClipDistance';
  38286. }
  38287. /**
  38288. * Whether the requested feature is available or not.
  38289. *
  38290. * @param {string} name - The requested feature.
  38291. * @return {boolean} Whether the requested feature is supported or not.
  38292. */
  38293. isAvailable( name ) {
  38294. let result = supports$1[ name ];
  38295. if ( result === undefined ) {
  38296. let extensionName;
  38297. result = false;
  38298. switch ( name ) {
  38299. case 'float32Filterable':
  38300. extensionName = 'OES_texture_float_linear';
  38301. break;
  38302. case 'clipDistance':
  38303. extensionName = 'WEBGL_clip_cull_distance';
  38304. break;
  38305. }
  38306. if ( extensionName !== undefined ) {
  38307. const extensions = this.renderer.backend.extensions;
  38308. if ( extensions.has( extensionName ) ) {
  38309. extensions.get( extensionName );
  38310. result = true;
  38311. }
  38312. }
  38313. supports$1[ name ] = result;
  38314. }
  38315. return result;
  38316. }
  38317. /**
  38318. * Whether to flip texture data along its vertical axis or not.
  38319. *
  38320. * @return {boolean} Returns always `true` in context of GLSL.
  38321. */
  38322. isFlipY() {
  38323. return true;
  38324. }
  38325. /**
  38326. * Enables hardware clipping.
  38327. *
  38328. * @param {string} planeCount - The clipping plane count.
  38329. */
  38330. enableHardwareClipping( planeCount ) {
  38331. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  38332. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  38333. }
  38334. /**
  38335. * Registers a transform in context of Transform Feedback.
  38336. *
  38337. * @param {string} varyingName - The varying name.
  38338. * @param {AttributeNode} attributeNode - The attribute node.
  38339. */
  38340. registerTransform( varyingName, attributeNode ) {
  38341. this.transforms.push( { varyingName, attributeNode } );
  38342. }
  38343. /**
  38344. * Returns the transforms of the given shader stage as a GLSL string.
  38345. *
  38346. * @param {string} shaderStage - The shader stage.
  38347. * @return {string} The GLSL snippet that defines the transforms.
  38348. */
  38349. getTransforms( /* shaderStage */ ) {
  38350. const transforms = this.transforms;
  38351. let snippet = '';
  38352. for ( let i = 0; i < transforms.length; i ++ ) {
  38353. const transform = transforms[ i ];
  38354. const attributeName = this.getPropertyName( transform.attributeNode );
  38355. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38356. }
  38357. return snippet;
  38358. }
  38359. /**
  38360. * Returns a GLSL struct based on the given name and variables.
  38361. *
  38362. * @private
  38363. * @param {string} name - The struct name.
  38364. * @param {string} vars - The struct variables.
  38365. * @return {string} The GLSL snippet representing a struct.
  38366. */
  38367. _getGLSLUniformStruct( name, vars ) {
  38368. return `
  38369. layout( std140 ) uniform ${name} {
  38370. ${vars}
  38371. };`;
  38372. }
  38373. /**
  38374. * Returns a GLSL vertex shader based on the given shader data.
  38375. *
  38376. * @private
  38377. * @param {Object} shaderData - The shader data.
  38378. * @return {string} The vertex shader.
  38379. */
  38380. _getGLSLVertexCode( shaderData ) {
  38381. return `#version 300 es
  38382. ${ this.getSignature() }
  38383. // extensions
  38384. ${shaderData.extensions}
  38385. // precision
  38386. ${ defaultPrecisions }
  38387. // uniforms
  38388. ${shaderData.uniforms}
  38389. // varyings
  38390. ${shaderData.varyings}
  38391. // attributes
  38392. ${shaderData.attributes}
  38393. // codes
  38394. ${shaderData.codes}
  38395. void main() {
  38396. // vars
  38397. ${shaderData.vars}
  38398. // transforms
  38399. ${shaderData.transforms}
  38400. // flow
  38401. ${shaderData.flow}
  38402. gl_PointSize = 1.0;
  38403. }
  38404. `;
  38405. }
  38406. /**
  38407. * Returns a GLSL fragment shader based on the given shader data.
  38408. *
  38409. * @private
  38410. * @param {Object} shaderData - The shader data.
  38411. * @return {string} The vertex shader.
  38412. */
  38413. _getGLSLFragmentCode( shaderData ) {
  38414. return `#version 300 es
  38415. ${ this.getSignature() }
  38416. // precision
  38417. ${ defaultPrecisions }
  38418. // uniforms
  38419. ${shaderData.uniforms}
  38420. // varyings
  38421. ${shaderData.varyings}
  38422. // codes
  38423. ${shaderData.codes}
  38424. // structs
  38425. ${shaderData.structs}
  38426. void main() {
  38427. // vars
  38428. ${shaderData.vars}
  38429. // flow
  38430. ${shaderData.flow}
  38431. }
  38432. `;
  38433. }
  38434. /**
  38435. * Controls the code build of the shader stages.
  38436. */
  38437. buildCode() {
  38438. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38439. this.sortBindingGroups();
  38440. for ( const shaderStage in shadersData ) {
  38441. let flow = '// code\n\n';
  38442. flow += this.flowCode[ shaderStage ];
  38443. const flowNodes = this.flowNodes[ shaderStage ];
  38444. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38445. for ( const node of flowNodes ) {
  38446. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38447. const slotName = node.name;
  38448. if ( slotName ) {
  38449. if ( flow.length > 0 ) flow += '\n';
  38450. flow += `\t// flow -> ${ slotName }\n\t`;
  38451. }
  38452. flow += `${ flowSlotData.code }\n\t`;
  38453. if ( node === mainNode && shaderStage !== 'compute' ) {
  38454. flow += '// result\n\t';
  38455. if ( shaderStage === 'vertex' ) {
  38456. flow += 'gl_Position = ';
  38457. flow += `${ flowSlotData.result };`;
  38458. } else if ( shaderStage === 'fragment' ) {
  38459. if ( ! node.outputNode.isOutputStructNode ) {
  38460. flow += 'fragColor = ';
  38461. flow += `${ flowSlotData.result };`;
  38462. }
  38463. }
  38464. }
  38465. }
  38466. const stageData = shadersData[ shaderStage ];
  38467. stageData.extensions = this.getExtensions( shaderStage );
  38468. stageData.uniforms = this.getUniforms( shaderStage );
  38469. stageData.attributes = this.getAttributes( shaderStage );
  38470. stageData.varyings = this.getVaryings( shaderStage );
  38471. stageData.vars = this.getVars( shaderStage );
  38472. stageData.structs = this.getStructs( shaderStage );
  38473. stageData.codes = this.getCodes( shaderStage );
  38474. stageData.transforms = this.getTransforms( shaderStage );
  38475. stageData.flow = flow;
  38476. }
  38477. if ( this.material !== null ) {
  38478. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38479. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38480. } else {
  38481. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38482. }
  38483. }
  38484. /**
  38485. * This method is one of the more important ones since it's responsible
  38486. * for generating a matching binding instance for the given uniform node.
  38487. *
  38488. * These bindings are later used in the renderer to create bind groups
  38489. * and layouts.
  38490. *
  38491. * @param {UniformNode} node - The uniform node.
  38492. * @param {string} type - The node data type.
  38493. * @param {string} shaderStage - The shader stage.
  38494. * @param {?string} [name=null] - An optional uniform name.
  38495. * @return {NodeUniform} The node uniform object.
  38496. */
  38497. getUniformFromNode( node, type, shaderStage, name = null ) {
  38498. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38499. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38500. let uniformGPU = nodeData.uniformGPU;
  38501. if ( uniformGPU === undefined ) {
  38502. const group = node.groupNode;
  38503. const groupName = group.name;
  38504. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38505. if ( type === 'texture' ) {
  38506. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38507. bindings.push( uniformGPU );
  38508. } else if ( type === 'cubeTexture' ) {
  38509. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38510. bindings.push( uniformGPU );
  38511. } else if ( type === 'texture3D' ) {
  38512. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38513. bindings.push( uniformGPU );
  38514. } else if ( type === 'buffer' ) {
  38515. node.name = `NodeBuffer_${ node.id }`;
  38516. uniformNode.name = `buffer${ node.id }`;
  38517. const buffer = new NodeUniformBuffer( node, group );
  38518. buffer.name = node.name;
  38519. bindings.push( buffer );
  38520. uniformGPU = buffer;
  38521. } else {
  38522. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38523. let uniformsGroup = uniformsStage[ groupName ];
  38524. if ( uniformsGroup === undefined ) {
  38525. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38526. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38527. uniformsStage[ groupName ] = uniformsGroup;
  38528. bindings.push( uniformsGroup );
  38529. }
  38530. uniformGPU = this.getNodeUniform( uniformNode, type );
  38531. uniformsGroup.addUniform( uniformGPU );
  38532. }
  38533. nodeData.uniformGPU = uniformGPU;
  38534. }
  38535. return uniformNode;
  38536. }
  38537. }
  38538. let _vector2 = null;
  38539. let _color4 = null;
  38540. /**
  38541. * Most of the rendering related logic is implemented in the
  38542. * {@link Renderer} module and related management components.
  38543. * Sometimes it is required though to execute commands which are
  38544. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  38545. * This abstract base class defines an interface that encapsulates
  38546. * all backend-related logic. Derived classes for each backend must
  38547. * implement the interface.
  38548. *
  38549. * @abstract
  38550. * @private
  38551. */
  38552. class Backend {
  38553. /**
  38554. * Constructs a new backend.
  38555. *
  38556. * @param {Object} parameters - An object holding parameters for the backend.
  38557. */
  38558. constructor( parameters = {} ) {
  38559. /**
  38560. * The parameters of the backend.
  38561. *
  38562. * @type {Object}
  38563. */
  38564. this.parameters = Object.assign( {}, parameters );
  38565. /**
  38566. * This weak map holds backend-specific data of objects
  38567. * like textures, attributes or render targets.
  38568. *
  38569. * @type {WeakMap}
  38570. */
  38571. this.data = new WeakMap();
  38572. /**
  38573. * A reference to the renderer.
  38574. *
  38575. * @type {?Renderer}
  38576. * @default null
  38577. */
  38578. this.renderer = null;
  38579. /**
  38580. * A reference to the canvas element the renderer is drawing to.
  38581. *
  38582. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  38583. * @default null
  38584. */
  38585. this.domElement = null;
  38586. /**
  38587. * A reference to the timestamp query pool.
  38588. *
  38589. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  38590. */
  38591. this.timestampQueryPool = {
  38592. 'render': null,
  38593. 'compute': null
  38594. };
  38595. }
  38596. /**
  38597. * Initializes the backend so it is ready for usage. Concrete backends
  38598. * are supposed to implement their rendering context creation and related
  38599. * operations in this method.
  38600. *
  38601. * @async
  38602. * @param {Renderer} renderer - The renderer.
  38603. * @return {Promise} A Promise that resolves when the backend has been initialized.
  38604. */
  38605. async init( renderer ) {
  38606. this.renderer = renderer;
  38607. }
  38608. /**
  38609. * The coordinate system of the backend.
  38610. *
  38611. * @abstract
  38612. * @type {number}
  38613. * @readonly
  38614. */
  38615. get coordinateSystem() {}
  38616. // render context
  38617. /**
  38618. * This method is executed at the beginning of a render call and
  38619. * can be used by the backend to prepare the state for upcoming
  38620. * draw calls.
  38621. *
  38622. * @abstract
  38623. * @param {RenderContext} renderContext - The render context.
  38624. */
  38625. beginRender( /*renderContext*/ ) {}
  38626. /**
  38627. * This method is executed at the end of a render call and
  38628. * can be used by the backend to finalize work after draw
  38629. * calls.
  38630. *
  38631. * @abstract
  38632. * @param {RenderContext} renderContext - The render context.
  38633. */
  38634. finishRender( /*renderContext*/ ) {}
  38635. /**
  38636. * This method is executed at the beginning of a compute call and
  38637. * can be used by the backend to prepare the state for upcoming
  38638. * compute tasks.
  38639. *
  38640. * @abstract
  38641. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38642. */
  38643. beginCompute( /*computeGroup*/ ) {}
  38644. /**
  38645. * This method is executed at the end of a compute call and
  38646. * can be used by the backend to finalize work after compute
  38647. * tasks.
  38648. *
  38649. * @abstract
  38650. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38651. */
  38652. finishCompute( /*computeGroup*/ ) {}
  38653. // render object
  38654. /**
  38655. * Executes a draw command for the given render object.
  38656. *
  38657. * @abstract
  38658. * @param {RenderObject} renderObject - The render object to draw.
  38659. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  38660. */
  38661. draw( /*renderObject, info*/ ) { }
  38662. // compute node
  38663. /**
  38664. * Executes a compute command for the given compute node.
  38665. *
  38666. * @abstract
  38667. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  38668. * @param {Node} computeNode - The compute node.
  38669. * @param {Array<BindGroup>} bindings - The bindings.
  38670. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38671. */
  38672. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  38673. // program
  38674. /**
  38675. * Creates a shader program from the given programmable stage.
  38676. *
  38677. * @abstract
  38678. * @param {ProgrammableStage} program - The programmable stage.
  38679. */
  38680. createProgram( /*program*/ ) { }
  38681. /**
  38682. * Destroys the shader program of the given programmable stage.
  38683. *
  38684. * @abstract
  38685. * @param {ProgrammableStage} program - The programmable stage.
  38686. */
  38687. destroyProgram( /*program*/ ) { }
  38688. // bindings
  38689. /**
  38690. * Creates bindings from the given bind group definition.
  38691. *
  38692. * @abstract
  38693. * @param {BindGroup} bindGroup - The bind group.
  38694. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38695. * @param {number} cacheIndex - The cache index.
  38696. * @param {number} version - The version.
  38697. */
  38698. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38699. /**
  38700. * Updates the given bind group definition.
  38701. *
  38702. * @abstract
  38703. * @param {BindGroup} bindGroup - The bind group.
  38704. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38705. * @param {number} cacheIndex - The cache index.
  38706. * @param {number} version - The version.
  38707. */
  38708. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38709. /**
  38710. * Updates a buffer binding.
  38711. *
  38712. * @abstract
  38713. * @param {Buffer} binding - The buffer binding to update.
  38714. */
  38715. updateBinding( /*binding*/ ) { }
  38716. // pipeline
  38717. /**
  38718. * Creates a render pipeline for the given render object.
  38719. *
  38720. * @abstract
  38721. * @param {RenderObject} renderObject - The render object.
  38722. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38723. */
  38724. createRenderPipeline( /*renderObject, promises*/ ) { }
  38725. /**
  38726. * Creates a compute pipeline for the given compute node.
  38727. *
  38728. * @abstract
  38729. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38730. * @param {Array<BindGroup>} bindings - The bindings.
  38731. */
  38732. createComputePipeline( /*computePipeline, bindings*/ ) { }
  38733. // cache key
  38734. /**
  38735. * Returns `true` if the render pipeline requires an update.
  38736. *
  38737. * @abstract
  38738. * @param {RenderObject} renderObject - The render object.
  38739. * @return {boolean} Whether the render pipeline requires an update or not.
  38740. */
  38741. needsRenderUpdate( /*renderObject*/ ) { }
  38742. /**
  38743. * Returns a cache key that is used to identify render pipelines.
  38744. *
  38745. * @abstract
  38746. * @param {RenderObject} renderObject - The render object.
  38747. * @return {string} The cache key.
  38748. */
  38749. getRenderCacheKey( /*renderObject*/ ) { }
  38750. // node builder
  38751. /**
  38752. * Returns a node builder for the given render object.
  38753. *
  38754. * @abstract
  38755. * @param {RenderObject} renderObject - The render object.
  38756. * @param {Renderer} renderer - The renderer.
  38757. * @return {NodeBuilder} The node builder.
  38758. */
  38759. createNodeBuilder( /*renderObject, renderer*/ ) { }
  38760. // textures
  38761. /**
  38762. * Creates a GPU sampler for the given texture.
  38763. *
  38764. * @abstract
  38765. * @param {Texture} texture - The texture to create the sampler for.
  38766. */
  38767. createSampler( /*texture*/ ) { }
  38768. /**
  38769. * Destroys the GPU sampler for the given texture.
  38770. *
  38771. * @abstract
  38772. * @param {Texture} texture - The texture to destroy the sampler for.
  38773. */
  38774. destroySampler( /*texture*/ ) {}
  38775. /**
  38776. * Creates a default texture for the given texture that can be used
  38777. * as a placeholder until the actual texture is ready for usage.
  38778. *
  38779. * @abstract
  38780. * @param {Texture} texture - The texture to create a default texture for.
  38781. */
  38782. createDefaultTexture( /*texture*/ ) { }
  38783. /**
  38784. * Defines a texture on the GPU for the given texture object.
  38785. *
  38786. * @abstract
  38787. * @param {Texture} texture - The texture.
  38788. * @param {Object} [options={}] - Optional configuration parameter.
  38789. */
  38790. createTexture( /*texture, options={}*/ ) { }
  38791. /**
  38792. * Uploads the updated texture data to the GPU.
  38793. *
  38794. * @abstract
  38795. * @param {Texture} texture - The texture.
  38796. * @param {Object} [options={}] - Optional configuration parameter.
  38797. */
  38798. updateTexture( /*texture, options = {}*/ ) { }
  38799. /**
  38800. * Generates mipmaps for the given texture.
  38801. *
  38802. * @abstract
  38803. * @param {Texture} texture - The texture.
  38804. */
  38805. generateMipmaps( /*texture*/ ) { }
  38806. /**
  38807. * Destroys the GPU data for the given texture object.
  38808. *
  38809. * @abstract
  38810. * @param {Texture} texture - The texture.
  38811. */
  38812. destroyTexture( /*texture*/ ) { }
  38813. /**
  38814. * Returns texture data as a typed array.
  38815. *
  38816. * @abstract
  38817. * @async
  38818. * @param {Texture} texture - The texture to copy.
  38819. * @param {number} x - The x coordinate of the copy origin.
  38820. * @param {number} y - The y coordinate of the copy origin.
  38821. * @param {number} width - The width of the copy.
  38822. * @param {number} height - The height of the copy.
  38823. * @param {number} faceIndex - The face index.
  38824. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38825. */
  38826. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  38827. /**
  38828. * Copies data of the given source texture to the given destination texture.
  38829. *
  38830. * @abstract
  38831. * @param {Texture} srcTexture - The source texture.
  38832. * @param {Texture} dstTexture - The destination texture.
  38833. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  38834. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  38835. * @param {number} [level=0] - The mip level to copy.
  38836. */
  38837. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  38838. /**
  38839. * Copies the current bound framebuffer to the given texture.
  38840. *
  38841. * @abstract
  38842. * @param {Texture} texture - The destination texture.
  38843. * @param {RenderContext} renderContext - The render context.
  38844. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38845. */
  38846. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  38847. // attributes
  38848. /**
  38849. * Creates the GPU buffer of a shader attribute.
  38850. *
  38851. * @abstract
  38852. * @param {BufferAttribute} attribute - The buffer attribute.
  38853. */
  38854. createAttribute( /*attribute*/ ) { }
  38855. /**
  38856. * Creates the GPU buffer of an indexed shader attribute.
  38857. *
  38858. * @abstract
  38859. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38860. */
  38861. createIndexAttribute( /*attribute*/ ) { }
  38862. /**
  38863. * Creates the GPU buffer of a storage attribute.
  38864. *
  38865. * @abstract
  38866. * @param {BufferAttribute} attribute - The buffer attribute.
  38867. */
  38868. createStorageAttribute( /*attribute*/ ) { }
  38869. /**
  38870. * Updates the GPU buffer of a shader attribute.
  38871. *
  38872. * @abstract
  38873. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38874. */
  38875. updateAttribute( /*attribute*/ ) { }
  38876. /**
  38877. * Destroys the GPU buffer of a shader attribute.
  38878. *
  38879. * @abstract
  38880. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  38881. */
  38882. destroyAttribute( /*attribute*/ ) { }
  38883. // canvas
  38884. /**
  38885. * Returns the backend's rendering context.
  38886. *
  38887. * @abstract
  38888. * @return {Object} The rendering context.
  38889. */
  38890. getContext() { }
  38891. /**
  38892. * Backends can use this method if they have to run
  38893. * logic when the renderer gets resized.
  38894. *
  38895. * @abstract
  38896. */
  38897. updateSize() { }
  38898. /**
  38899. * Updates the viewport with the values from the given render context.
  38900. *
  38901. * @abstract
  38902. * @param {RenderContext} renderContext - The render context.
  38903. */
  38904. updateViewport( /*renderContext*/ ) {}
  38905. // utils
  38906. /**
  38907. * Returns `true` if the given 3D object is fully occluded by other
  38908. * 3D objects in the scene. Backends must implement this method by using
  38909. * a Occlusion Query API.
  38910. *
  38911. * @abstract
  38912. * @param {RenderContext} renderContext - The render context.
  38913. * @param {Object3D} object - The 3D object to test.
  38914. * @return {boolean} Whether the 3D object is fully occluded or not.
  38915. */
  38916. isOccluded( /*renderContext, object*/ ) {}
  38917. /**
  38918. * Resolves the time stamp for the given render context and type.
  38919. *
  38920. * @async
  38921. * @abstract
  38922. * @param {string} [type='render'] - The type of the time stamp.
  38923. * @return {Promise<number>} A Promise that resolves with the time stamp.
  38924. */
  38925. async resolveTimestampsAsync( type = 'render' ) {
  38926. if ( ! this.trackTimestamp ) {
  38927. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  38928. return;
  38929. }
  38930. const queryPool = this.timestampQueryPool[ type ];
  38931. if ( ! queryPool ) {
  38932. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  38933. return;
  38934. }
  38935. const duration = await queryPool.resolveQueriesAsync();
  38936. this.renderer.info[ type ].timestamp = duration;
  38937. return duration;
  38938. }
  38939. /**
  38940. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38941. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38942. *
  38943. * @async
  38944. * @abstract
  38945. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38946. */
  38947. async waitForGPU() {}
  38948. /**
  38949. * This method performs a readback operation by moving buffer data from
  38950. * a storage buffer attribute from the GPU to the CPU.
  38951. *
  38952. * @async
  38953. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38954. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38955. */
  38956. async getArrayBufferAsync( /* attribute */ ) {}
  38957. /**
  38958. * Checks if the given feature is supported by the backend.
  38959. *
  38960. * @async
  38961. * @abstract
  38962. * @param {string} name - The feature's name.
  38963. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38964. */
  38965. async hasFeatureAsync( /*name*/ ) { }
  38966. /**
  38967. * Checks if the given feature is supported by the backend.
  38968. *
  38969. * @abstract
  38970. * @param {string} name - The feature's name.
  38971. * @return {boolean} Whether the feature is supported or not.
  38972. */
  38973. hasFeature( /*name*/ ) {}
  38974. /**
  38975. * Returns the maximum anisotropy texture filtering value.
  38976. *
  38977. * @abstract
  38978. * @return {number} The maximum anisotropy texture filtering value.
  38979. */
  38980. getMaxAnisotropy() {}
  38981. /**
  38982. * Returns the drawing buffer size.
  38983. *
  38984. * @return {Vector2} The drawing buffer size.
  38985. */
  38986. getDrawingBufferSize() {
  38987. _vector2 = _vector2 || new Vector2();
  38988. return this.renderer.getDrawingBufferSize( _vector2 );
  38989. }
  38990. /**
  38991. * Defines the scissor test.
  38992. *
  38993. * @abstract
  38994. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38995. */
  38996. setScissorTest( /*boolean*/ ) { }
  38997. /**
  38998. * Returns the clear color and alpha into a single
  38999. * color object.
  39000. *
  39001. * @return {Color4} The clear color.
  39002. */
  39003. getClearColor() {
  39004. const renderer = this.renderer;
  39005. _color4 = _color4 || new Color4();
  39006. renderer.getClearColor( _color4 );
  39007. _color4.getRGB( _color4 );
  39008. return _color4;
  39009. }
  39010. /**
  39011. * Returns the DOM element. If no DOM element exists, the backend
  39012. * creates a new one.
  39013. *
  39014. * @return {HTMLCanvasElement} The DOM element.
  39015. */
  39016. getDomElement() {
  39017. let domElement = this.domElement;
  39018. if ( domElement === null ) {
  39019. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39020. // OffscreenCanvas does not have setAttribute, see #22811
  39021. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39022. this.domElement = domElement;
  39023. }
  39024. return domElement;
  39025. }
  39026. /**
  39027. * Sets a dictionary for the given object into the
  39028. * internal data structure.
  39029. *
  39030. * @param {Object} object - The object.
  39031. * @param {Object} value - The dictionary to set.
  39032. */
  39033. set( object, value ) {
  39034. this.data.set( object, value );
  39035. }
  39036. /**
  39037. * Returns the dictionary for the given object.
  39038. *
  39039. * @param {Object} object - The object.
  39040. * @return {Object} The object's dictionary.
  39041. */
  39042. get( object ) {
  39043. let map = this.data.get( object );
  39044. if ( map === undefined ) {
  39045. map = {};
  39046. this.data.set( object, map );
  39047. }
  39048. return map;
  39049. }
  39050. /**
  39051. * Checks if the given object has a dictionary
  39052. * with data defined.
  39053. *
  39054. * @param {Object} object - The object.
  39055. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  39056. */
  39057. has( object ) {
  39058. return this.data.has( object );
  39059. }
  39060. /**
  39061. * Deletes an object from the internal data structure.
  39062. *
  39063. * @param {Object} object - The object to delete.
  39064. */
  39065. delete( object ) {
  39066. this.data.delete( object );
  39067. }
  39068. /**
  39069. * Frees internal resources.
  39070. *
  39071. * @abstract
  39072. */
  39073. dispose() { }
  39074. }
  39075. let _id$1 = 0;
  39076. /**
  39077. * This module is internally used in context of compute shaders.
  39078. * This type of shader is not natively supported in WebGL 2 and
  39079. * thus implemented via Transform Feedback. `DualAttributeData`
  39080. * manages the related data.
  39081. *
  39082. * @private
  39083. */
  39084. class DualAttributeData {
  39085. constructor( attributeData, dualBuffer ) {
  39086. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39087. this.type = attributeData.type;
  39088. this.bufferType = attributeData.bufferType;
  39089. this.pbo = attributeData.pbo;
  39090. this.byteLength = attributeData.byteLength;
  39091. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39092. this.version = attributeData.version;
  39093. this.isInteger = attributeData.isInteger;
  39094. this.activeBufferIndex = 0;
  39095. this.baseId = attributeData.id;
  39096. }
  39097. get id() {
  39098. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39099. }
  39100. get bufferGPU() {
  39101. return this.buffers[ this.activeBufferIndex ];
  39102. }
  39103. get transformBuffer() {
  39104. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39105. }
  39106. switchBuffers() {
  39107. this.activeBufferIndex ^= 1;
  39108. }
  39109. }
  39110. /**
  39111. * A WebGL 2 backend utility module for managing shader attributes.
  39112. *
  39113. * @private
  39114. */
  39115. class WebGLAttributeUtils {
  39116. /**
  39117. * Constructs a new utility object.
  39118. *
  39119. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39120. */
  39121. constructor( backend ) {
  39122. /**
  39123. * A reference to the WebGL 2 backend.
  39124. *
  39125. * @type {WebGLBackend}
  39126. */
  39127. this.backend = backend;
  39128. }
  39129. /**
  39130. * Creates the GPU buffer for the given buffer attribute.
  39131. *
  39132. * @param {BufferAttribute} attribute - The buffer attribute.
  39133. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39134. */
  39135. createAttribute( attribute, bufferType ) {
  39136. const backend = this.backend;
  39137. const { gl } = backend;
  39138. const array = attribute.array;
  39139. const usage = attribute.usage || gl.STATIC_DRAW;
  39140. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39141. const bufferData = backend.get( bufferAttribute );
  39142. let bufferGPU = bufferData.bufferGPU;
  39143. if ( bufferGPU === undefined ) {
  39144. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39145. bufferData.bufferGPU = bufferGPU;
  39146. bufferData.bufferType = bufferType;
  39147. bufferData.version = bufferAttribute.version;
  39148. }
  39149. //attribute.onUploadCallback();
  39150. let type;
  39151. if ( array instanceof Float32Array ) {
  39152. type = gl.FLOAT;
  39153. } else if ( array instanceof Uint16Array ) {
  39154. if ( attribute.isFloat16BufferAttribute ) {
  39155. type = gl.HALF_FLOAT;
  39156. } else {
  39157. type = gl.UNSIGNED_SHORT;
  39158. }
  39159. } else if ( array instanceof Int16Array ) {
  39160. type = gl.SHORT;
  39161. } else if ( array instanceof Uint32Array ) {
  39162. type = gl.UNSIGNED_INT;
  39163. } else if ( array instanceof Int32Array ) {
  39164. type = gl.INT;
  39165. } else if ( array instanceof Int8Array ) {
  39166. type = gl.BYTE;
  39167. } else if ( array instanceof Uint8Array ) {
  39168. type = gl.UNSIGNED_BYTE;
  39169. } else if ( array instanceof Uint8ClampedArray ) {
  39170. type = gl.UNSIGNED_BYTE;
  39171. } else {
  39172. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39173. }
  39174. let attributeData = {
  39175. bufferGPU,
  39176. bufferType,
  39177. type,
  39178. byteLength: array.byteLength,
  39179. bytesPerElement: array.BYTES_PER_ELEMENT,
  39180. version: attribute.version,
  39181. pbo: attribute.pbo,
  39182. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39183. id: _id$1 ++
  39184. };
  39185. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39186. // create buffer for transform feedback use
  39187. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39188. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39189. }
  39190. backend.set( attribute, attributeData );
  39191. }
  39192. /**
  39193. * Updates the GPU buffer of the given buffer attribute.
  39194. *
  39195. * @param {BufferAttribute} attribute - The buffer attribute.
  39196. */
  39197. updateAttribute( attribute ) {
  39198. const backend = this.backend;
  39199. const { gl } = backend;
  39200. const array = attribute.array;
  39201. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39202. const bufferData = backend.get( bufferAttribute );
  39203. const bufferType = bufferData.bufferType;
  39204. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39205. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39206. if ( updateRanges.length === 0 ) {
  39207. // Not using update ranges
  39208. gl.bufferSubData( bufferType, 0, array );
  39209. } else {
  39210. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39211. const range = updateRanges[ i ];
  39212. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39213. array, range.start, range.count );
  39214. }
  39215. bufferAttribute.clearUpdateRanges();
  39216. }
  39217. gl.bindBuffer( bufferType, null );
  39218. bufferData.version = bufferAttribute.version;
  39219. }
  39220. /**
  39221. * Destroys the GPU buffer of the given buffer attribute.
  39222. *
  39223. * @param {BufferAttribute} attribute - The buffer attribute.
  39224. */
  39225. destroyAttribute( attribute ) {
  39226. const backend = this.backend;
  39227. const { gl } = backend;
  39228. if ( attribute.isInterleavedBufferAttribute ) {
  39229. backend.delete( attribute.data );
  39230. }
  39231. const attributeData = backend.get( attribute );
  39232. gl.deleteBuffer( attributeData.bufferGPU );
  39233. backend.delete( attribute );
  39234. }
  39235. /**
  39236. * This method performs a readback operation by moving buffer data from
  39237. * a storage buffer attribute from the GPU to the CPU.
  39238. *
  39239. * @async
  39240. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39241. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39242. */
  39243. async getArrayBufferAsync( attribute ) {
  39244. const backend = this.backend;
  39245. const { gl } = backend;
  39246. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39247. const { bufferGPU } = backend.get( bufferAttribute );
  39248. const array = attribute.array;
  39249. const byteLength = array.byteLength;
  39250. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39251. const writeBuffer = gl.createBuffer();
  39252. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39253. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39254. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39255. await backend.utils._clientWaitAsync();
  39256. const dstBuffer = new attribute.array.constructor( array.length );
  39257. // Ensure the buffer is bound before reading
  39258. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39259. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39260. gl.deleteBuffer( writeBuffer );
  39261. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39262. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39263. return dstBuffer.buffer;
  39264. }
  39265. /**
  39266. * Creates a WebGL buffer with the given data.
  39267. *
  39268. * @private
  39269. * @param {WebGL2RenderingContext} gl - The rendering context.
  39270. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39271. * @param {TypedArray} array - The array of the buffer attribute.
  39272. * @param {GLenum} usage - The usage.
  39273. * @return {WebGLBuffer} The WebGL buffer.
  39274. */
  39275. _createBuffer( gl, bufferType, array, usage ) {
  39276. const bufferGPU = gl.createBuffer();
  39277. gl.bindBuffer( bufferType, bufferGPU );
  39278. gl.bufferData( bufferType, array, usage );
  39279. gl.bindBuffer( bufferType, null );
  39280. return bufferGPU;
  39281. }
  39282. }
  39283. let equationToGL, factorToGL;
  39284. /**
  39285. * A WebGL 2 backend utility module for managing the WebGL state.
  39286. *
  39287. * The major goal of this module is to reduce the number of state changes
  39288. * by caching the WEbGL state with a series of variables. In this way, the
  39289. * renderer only executes state change commands when necessary which
  39290. * improves the overall performance.
  39291. *
  39292. * @private
  39293. */
  39294. class WebGLState {
  39295. /**
  39296. * Constructs a new utility object.
  39297. *
  39298. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39299. */
  39300. constructor( backend ) {
  39301. /**
  39302. * A reference to the WebGL 2 backend.
  39303. *
  39304. * @type {WebGLBackend}
  39305. */
  39306. this.backend = backend;
  39307. /**
  39308. * A reference to the rendering context.
  39309. *
  39310. * @type {WebGL2RenderingContext}
  39311. */
  39312. this.gl = this.backend.gl;
  39313. // Below properties are intended to cache
  39314. // the WebGL state and are not explicitly
  39315. // documented for convenience reasons.
  39316. this.enabled = {};
  39317. this.currentFlipSided = null;
  39318. this.currentCullFace = null;
  39319. this.currentProgram = null;
  39320. this.currentBlendingEnabled = false;
  39321. this.currentBlending = null;
  39322. this.currentBlendSrc = null;
  39323. this.currentBlendDst = null;
  39324. this.currentBlendSrcAlpha = null;
  39325. this.currentBlendDstAlpha = null;
  39326. this.currentPremultipledAlpha = null;
  39327. this.currentPolygonOffsetFactor = null;
  39328. this.currentPolygonOffsetUnits = null;
  39329. this.currentColorMask = null;
  39330. this.currentDepthFunc = null;
  39331. this.currentDepthMask = null;
  39332. this.currentStencilFunc = null;
  39333. this.currentStencilRef = null;
  39334. this.currentStencilFuncMask = null;
  39335. this.currentStencilFail = null;
  39336. this.currentStencilZFail = null;
  39337. this.currentStencilZPass = null;
  39338. this.currentStencilMask = null;
  39339. this.currentLineWidth = null;
  39340. this.currentClippingPlanes = 0;
  39341. this.currentBoundFramebuffers = {};
  39342. this.currentDrawbuffers = new WeakMap();
  39343. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39344. this.currentTextureSlot = null;
  39345. this.currentBoundTextures = {};
  39346. this.currentBoundBufferBases = {};
  39347. this._init();
  39348. }
  39349. /**
  39350. * Inits the state of the utility.
  39351. *
  39352. * @private
  39353. */
  39354. _init() {
  39355. const gl = this.gl;
  39356. // Store only WebGL constants here.
  39357. equationToGL = {
  39358. [ AddEquation ]: gl.FUNC_ADD,
  39359. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39360. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39361. };
  39362. factorToGL = {
  39363. [ ZeroFactor ]: gl.ZERO,
  39364. [ OneFactor ]: gl.ONE,
  39365. [ SrcColorFactor ]: gl.SRC_COLOR,
  39366. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39367. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39368. [ DstColorFactor ]: gl.DST_COLOR,
  39369. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39370. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39371. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39372. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39373. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39374. };
  39375. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  39376. const viewportParam = gl.getParameter( gl.VIEWPORT );
  39377. this.currentScissor = new Vector4().fromArray( scissorParam );
  39378. this.currentViewport = new Vector4().fromArray( viewportParam );
  39379. this._tempVec4 = new Vector4();
  39380. }
  39381. /**
  39382. * Enables the given WebGL capability.
  39383. *
  39384. * This method caches the capability state so
  39385. * `gl.enable()` is only called when necessary.
  39386. *
  39387. * @param {GLenum} id - The capability to enable.
  39388. */
  39389. enable( id ) {
  39390. const { enabled } = this;
  39391. if ( enabled[ id ] !== true ) {
  39392. this.gl.enable( id );
  39393. enabled[ id ] = true;
  39394. }
  39395. }
  39396. /**
  39397. * Disables the given WebGL capability.
  39398. *
  39399. * This method caches the capability state so
  39400. * `gl.disable()` is only called when necessary.
  39401. *
  39402. * @param {GLenum} id - The capability to enable.
  39403. */
  39404. disable( id ) {
  39405. const { enabled } = this;
  39406. if ( enabled[ id ] !== false ) {
  39407. this.gl.disable( id );
  39408. enabled[ id ] = false;
  39409. }
  39410. }
  39411. /**
  39412. * Specifies whether polygons are front- or back-facing
  39413. * by setting the winding orientation.
  39414. *
  39415. * This method caches the state so `gl.frontFace()` is only
  39416. * called when necessary.
  39417. *
  39418. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  39419. */
  39420. setFlipSided( flipSided ) {
  39421. if ( this.currentFlipSided !== flipSided ) {
  39422. const { gl } = this;
  39423. if ( flipSided ) {
  39424. gl.frontFace( gl.CW );
  39425. } else {
  39426. gl.frontFace( gl.CCW );
  39427. }
  39428. this.currentFlipSided = flipSided;
  39429. }
  39430. }
  39431. /**
  39432. * Specifies whether or not front- and/or back-facing
  39433. * polygons can be culled.
  39434. *
  39435. * This method caches the state so `gl.cullFace()` is only
  39436. * called when necessary.
  39437. *
  39438. * @param {number} cullFace - Defines which polygons are candidates for culling.
  39439. */
  39440. setCullFace( cullFace ) {
  39441. const { gl } = this;
  39442. if ( cullFace !== CullFaceNone ) {
  39443. this.enable( gl.CULL_FACE );
  39444. if ( cullFace !== this.currentCullFace ) {
  39445. if ( cullFace === CullFaceBack ) {
  39446. gl.cullFace( gl.BACK );
  39447. } else if ( cullFace === CullFaceFront ) {
  39448. gl.cullFace( gl.FRONT );
  39449. } else {
  39450. gl.cullFace( gl.FRONT_AND_BACK );
  39451. }
  39452. }
  39453. } else {
  39454. this.disable( gl.CULL_FACE );
  39455. }
  39456. this.currentCullFace = cullFace;
  39457. }
  39458. /**
  39459. * Specifies the width of line primitives.
  39460. *
  39461. * This method caches the state so `gl.lineWidth()` is only
  39462. * called when necessary.
  39463. *
  39464. * @param {number} width - The line width.
  39465. */
  39466. setLineWidth( width ) {
  39467. const { currentLineWidth, gl } = this;
  39468. if ( width !== currentLineWidth ) {
  39469. gl.lineWidth( width );
  39470. this.currentLineWidth = width;
  39471. }
  39472. }
  39473. /**
  39474. * Defines the blending.
  39475. *
  39476. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  39477. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  39478. *
  39479. * @param {number} blending - The blending type.
  39480. * @param {number} blendEquation - The blending equation.
  39481. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  39482. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  39483. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  39484. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  39485. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  39486. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  39487. */
  39488. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39489. const { gl } = this;
  39490. if ( blending === NoBlending ) {
  39491. if ( this.currentBlendingEnabled === true ) {
  39492. this.disable( gl.BLEND );
  39493. this.currentBlendingEnabled = false;
  39494. }
  39495. return;
  39496. }
  39497. if ( this.currentBlendingEnabled === false ) {
  39498. this.enable( gl.BLEND );
  39499. this.currentBlendingEnabled = true;
  39500. }
  39501. if ( blending !== CustomBlending ) {
  39502. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39503. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39504. gl.blendEquation( gl.FUNC_ADD );
  39505. this.currentBlendEquation = AddEquation;
  39506. this.currentBlendEquationAlpha = AddEquation;
  39507. }
  39508. if ( premultipliedAlpha ) {
  39509. switch ( blending ) {
  39510. case NormalBlending:
  39511. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39512. break;
  39513. case AdditiveBlending:
  39514. gl.blendFunc( gl.ONE, gl.ONE );
  39515. break;
  39516. case SubtractiveBlending:
  39517. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39518. break;
  39519. case MultiplyBlending:
  39520. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39521. break;
  39522. default:
  39523. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39524. break;
  39525. }
  39526. } else {
  39527. switch ( blending ) {
  39528. case NormalBlending:
  39529. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39530. break;
  39531. case AdditiveBlending:
  39532. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39533. break;
  39534. case SubtractiveBlending:
  39535. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39536. break;
  39537. case MultiplyBlending:
  39538. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39539. break;
  39540. default:
  39541. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39542. break;
  39543. }
  39544. }
  39545. this.currentBlendSrc = null;
  39546. this.currentBlendDst = null;
  39547. this.currentBlendSrcAlpha = null;
  39548. this.currentBlendDstAlpha = null;
  39549. this.currentBlending = blending;
  39550. this.currentPremultipledAlpha = premultipliedAlpha;
  39551. }
  39552. return;
  39553. }
  39554. // custom blending
  39555. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39556. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39557. blendDstAlpha = blendDstAlpha || blendDst;
  39558. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39559. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39560. this.currentBlendEquation = blendEquation;
  39561. this.currentBlendEquationAlpha = blendEquationAlpha;
  39562. }
  39563. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39564. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39565. this.currentBlendSrc = blendSrc;
  39566. this.currentBlendDst = blendDst;
  39567. this.currentBlendSrcAlpha = blendSrcAlpha;
  39568. this.currentBlendDstAlpha = blendDstAlpha;
  39569. }
  39570. this.currentBlending = blending;
  39571. this.currentPremultipledAlpha = false;
  39572. }
  39573. /**
  39574. * Specifies whether colors can be written when rendering
  39575. * into a framebuffer or not.
  39576. *
  39577. * This method caches the state so `gl.colorMask()` is only
  39578. * called when necessary.
  39579. *
  39580. * @param {boolean} colorMask - The color mask.
  39581. */
  39582. setColorMask( colorMask ) {
  39583. if ( this.currentColorMask !== colorMask ) {
  39584. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39585. this.currentColorMask = colorMask;
  39586. }
  39587. }
  39588. /**
  39589. * Specifies whether the depth test is enabled or not.
  39590. *
  39591. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  39592. */
  39593. setDepthTest( depthTest ) {
  39594. const { gl } = this;
  39595. if ( depthTest ) {
  39596. this.enable( gl.DEPTH_TEST );
  39597. } else {
  39598. this.disable( gl.DEPTH_TEST );
  39599. }
  39600. }
  39601. /**
  39602. * Specifies whether depth values can be written when rendering
  39603. * into a framebuffer or not.
  39604. *
  39605. * This method caches the state so `gl.depthMask()` is only
  39606. * called when necessary.
  39607. *
  39608. * @param {boolean} depthMask - The depth mask.
  39609. */
  39610. setDepthMask( depthMask ) {
  39611. if ( this.currentDepthMask !== depthMask ) {
  39612. this.gl.depthMask( depthMask );
  39613. this.currentDepthMask = depthMask;
  39614. }
  39615. }
  39616. /**
  39617. * Specifies the depth compare function.
  39618. *
  39619. * This method caches the state so `gl.depthFunc()` is only
  39620. * called when necessary.
  39621. *
  39622. * @param {number} depthFunc - The depth compare function.
  39623. */
  39624. setDepthFunc( depthFunc ) {
  39625. if ( this.currentDepthFunc !== depthFunc ) {
  39626. const { gl } = this;
  39627. switch ( depthFunc ) {
  39628. case NeverDepth:
  39629. gl.depthFunc( gl.NEVER );
  39630. break;
  39631. case AlwaysDepth:
  39632. gl.depthFunc( gl.ALWAYS );
  39633. break;
  39634. case LessDepth:
  39635. gl.depthFunc( gl.LESS );
  39636. break;
  39637. case LessEqualDepth:
  39638. gl.depthFunc( gl.LEQUAL );
  39639. break;
  39640. case EqualDepth:
  39641. gl.depthFunc( gl.EQUAL );
  39642. break;
  39643. case GreaterEqualDepth:
  39644. gl.depthFunc( gl.GEQUAL );
  39645. break;
  39646. case GreaterDepth:
  39647. gl.depthFunc( gl.GREATER );
  39648. break;
  39649. case NotEqualDepth:
  39650. gl.depthFunc( gl.NOTEQUAL );
  39651. break;
  39652. default:
  39653. gl.depthFunc( gl.LEQUAL );
  39654. }
  39655. this.currentDepthFunc = depthFunc;
  39656. }
  39657. }
  39658. /**
  39659. * Specifies the scissor box.
  39660. *
  39661. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  39662. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  39663. * @param {number} width - The width of the viewport.
  39664. * @param {number} height - The height of the viewport.
  39665. *
  39666. */
  39667. scissor( x, y, width, height ) {
  39668. const scissor = this._tempVec4.set( x, y, width, height );
  39669. if ( this.currentScissor.equals( scissor ) === false ) {
  39670. const { gl } = this;
  39671. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  39672. this.currentScissor.copy( scissor );
  39673. }
  39674. }
  39675. /**
  39676. * Specifies the viewport.
  39677. *
  39678. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  39679. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  39680. * @param {number} width - The width of the viewport.
  39681. * @param {number} height - The height of the viewport.
  39682. *
  39683. */
  39684. viewport( x, y, width, height ) {
  39685. const viewport = this._tempVec4.set( x, y, width, height );
  39686. if ( this.currentViewport.equals( viewport ) === false ) {
  39687. const { gl } = this;
  39688. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39689. this.currentViewport.copy( viewport );
  39690. }
  39691. }
  39692. /**
  39693. * Defines the scissor test.
  39694. *
  39695. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39696. */
  39697. setScissorTest( boolean ) {
  39698. const gl = this.gl;
  39699. if ( boolean ) {
  39700. gl.enable( gl.SCISSOR_TEST );
  39701. } else {
  39702. gl.disable( gl.SCISSOR_TEST );
  39703. }
  39704. }
  39705. /**
  39706. * Specifies whether the stencil test is enabled or not.
  39707. *
  39708. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  39709. */
  39710. setStencilTest( stencilTest ) {
  39711. const { gl } = this;
  39712. if ( stencilTest ) {
  39713. this.enable( gl.STENCIL_TEST );
  39714. } else {
  39715. this.disable( gl.STENCIL_TEST );
  39716. }
  39717. }
  39718. /**
  39719. * Specifies whether stencil values can be written when rendering
  39720. * into a framebuffer or not.
  39721. *
  39722. * This method caches the state so `gl.stencilMask()` is only
  39723. * called when necessary.
  39724. *
  39725. * @param {boolean} stencilMask - The stencil mask.
  39726. */
  39727. setStencilMask( stencilMask ) {
  39728. if ( this.currentStencilMask !== stencilMask ) {
  39729. this.gl.stencilMask( stencilMask );
  39730. this.currentStencilMask = stencilMask;
  39731. }
  39732. }
  39733. /**
  39734. * Specifies whether the stencil test functions.
  39735. *
  39736. * This method caches the state so `gl.stencilFunc()` is only
  39737. * called when necessary.
  39738. *
  39739. * @param {number} stencilFunc - The stencil compare function.
  39740. * @param {number} stencilRef - The reference value for the stencil test.
  39741. * @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.
  39742. */
  39743. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39744. if ( this.currentStencilFunc !== stencilFunc ||
  39745. this.currentStencilRef !== stencilRef ||
  39746. this.currentStencilFuncMask !== stencilMask ) {
  39747. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39748. this.currentStencilFunc = stencilFunc;
  39749. this.currentStencilRef = stencilRef;
  39750. this.currentStencilFuncMask = stencilMask;
  39751. }
  39752. }
  39753. /**
  39754. * Specifies whether the stencil test operation.
  39755. *
  39756. * This method caches the state so `gl.stencilOp()` is only
  39757. * called when necessary.
  39758. *
  39759. * @param {number} stencilFail - The function to use when the stencil test fails.
  39760. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  39761. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  39762. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  39763. */
  39764. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39765. if ( this.currentStencilFail !== stencilFail ||
  39766. this.currentStencilZFail !== stencilZFail ||
  39767. this.currentStencilZPass !== stencilZPass ) {
  39768. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39769. this.currentStencilFail = stencilFail;
  39770. this.currentStencilZFail = stencilZFail;
  39771. this.currentStencilZPass = stencilZPass;
  39772. }
  39773. }
  39774. /**
  39775. * Configures the WebGL state for the given material.
  39776. *
  39777. * @param {Material} material - The material to configure the state for.
  39778. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  39779. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  39780. */
  39781. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  39782. const { gl } = this;
  39783. material.side === DoubleSide
  39784. ? this.disable( gl.CULL_FACE )
  39785. : this.enable( gl.CULL_FACE );
  39786. let flipSided = ( material.side === BackSide );
  39787. if ( frontFaceCW ) flipSided = ! flipSided;
  39788. this.setFlipSided( flipSided );
  39789. ( material.blending === NormalBlending && material.transparent === false )
  39790. ? this.setBlending( NoBlending )
  39791. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39792. this.setDepthFunc( material.depthFunc );
  39793. this.setDepthTest( material.depthTest );
  39794. this.setDepthMask( material.depthWrite );
  39795. this.setColorMask( material.colorWrite );
  39796. const stencilWrite = material.stencilWrite;
  39797. this.setStencilTest( stencilWrite );
  39798. if ( stencilWrite ) {
  39799. this.setStencilMask( material.stencilWriteMask );
  39800. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39801. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39802. }
  39803. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39804. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39805. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39806. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39807. if ( hardwareClippingPlanes > 0 ) {
  39808. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  39809. const CLIP_DISTANCE0_WEBGL = 0x3000;
  39810. for ( let i = 0; i < 8; i ++ ) {
  39811. if ( i < hardwareClippingPlanes ) {
  39812. this.enable( CLIP_DISTANCE0_WEBGL + i );
  39813. } else {
  39814. this.disable( CLIP_DISTANCE0_WEBGL + i );
  39815. }
  39816. }
  39817. }
  39818. }
  39819. }
  39820. /**
  39821. * Specifies the polygon offset.
  39822. *
  39823. * This method caches the state so `gl.polygonOffset()` is only
  39824. * called when necessary.
  39825. *
  39826. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  39827. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  39828. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  39829. */
  39830. setPolygonOffset( polygonOffset, factor, units ) {
  39831. const { gl } = this;
  39832. if ( polygonOffset ) {
  39833. this.enable( gl.POLYGON_OFFSET_FILL );
  39834. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39835. gl.polygonOffset( factor, units );
  39836. this.currentPolygonOffsetFactor = factor;
  39837. this.currentPolygonOffsetUnits = units;
  39838. }
  39839. } else {
  39840. this.disable( gl.POLYGON_OFFSET_FILL );
  39841. }
  39842. }
  39843. /**
  39844. * Defines the usage of the given WebGL program.
  39845. *
  39846. * This method caches the state so `gl.useProgram()` is only
  39847. * called when necessary.
  39848. *
  39849. * @param {WebGLProgram} program - The WebGL program to use.
  39850. * @return {boolean} Whether a program change has been executed or not.
  39851. */
  39852. useProgram( program ) {
  39853. if ( this.currentProgram !== program ) {
  39854. this.gl.useProgram( program );
  39855. this.currentProgram = program;
  39856. return true;
  39857. }
  39858. return false;
  39859. }
  39860. // framebuffer
  39861. /**
  39862. * Binds the given framebuffer.
  39863. *
  39864. * This method caches the state so `gl.bindFramebuffer()` is only
  39865. * called when necessary.
  39866. *
  39867. * @param {number} target - The binding point (target).
  39868. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  39869. * @return {boolean} Whether a bind has been executed or not.
  39870. */
  39871. bindFramebuffer( target, framebuffer ) {
  39872. const { gl, currentBoundFramebuffers } = this;
  39873. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39874. gl.bindFramebuffer( target, framebuffer );
  39875. currentBoundFramebuffers[ target ] = framebuffer;
  39876. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39877. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39878. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39879. }
  39880. if ( target === gl.FRAMEBUFFER ) {
  39881. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39882. }
  39883. return true;
  39884. }
  39885. return false;
  39886. }
  39887. /**
  39888. * Defines draw buffers to which fragment colors are written into.
  39889. * Configures the MRT setup of custom framebuffers.
  39890. *
  39891. * This method caches the state so `gl.drawBuffers()` is only
  39892. * called when necessary.
  39893. *
  39894. * @param {RenderContext} renderContext - The render context.
  39895. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  39896. */
  39897. drawBuffers( renderContext, framebuffer ) {
  39898. const { gl } = this;
  39899. let drawBuffers = [];
  39900. let needsUpdate = false;
  39901. if ( renderContext.textures !== null ) {
  39902. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39903. if ( drawBuffers === undefined ) {
  39904. drawBuffers = [];
  39905. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39906. }
  39907. const textures = renderContext.textures;
  39908. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39909. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39910. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39911. }
  39912. drawBuffers.length = textures.length;
  39913. needsUpdate = true;
  39914. }
  39915. } else {
  39916. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39917. drawBuffers[ 0 ] = gl.BACK;
  39918. needsUpdate = true;
  39919. }
  39920. }
  39921. if ( needsUpdate ) {
  39922. gl.drawBuffers( drawBuffers );
  39923. }
  39924. }
  39925. // texture
  39926. /**
  39927. * Makes the given texture unit active.
  39928. *
  39929. * This method caches the state so `gl.activeTexture()` is only
  39930. * called when necessary.
  39931. *
  39932. * @param {number} webglSlot - The texture unit to make active.
  39933. */
  39934. activeTexture( webglSlot ) {
  39935. const { gl, currentTextureSlot, maxTextures } = this;
  39936. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39937. if ( currentTextureSlot !== webglSlot ) {
  39938. gl.activeTexture( webglSlot );
  39939. this.currentTextureSlot = webglSlot;
  39940. }
  39941. }
  39942. /**
  39943. * Binds the given WebGL texture to a target.
  39944. *
  39945. * This method caches the state so `gl.bindTexture()` is only
  39946. * called when necessary.
  39947. *
  39948. * @param {number} webglType - The binding point (target).
  39949. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  39950. * @param {number} webglSlot - The texture.
  39951. */
  39952. bindTexture( webglType, webglTexture, webglSlot ) {
  39953. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39954. if ( webglSlot === undefined ) {
  39955. if ( currentTextureSlot === null ) {
  39956. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39957. } else {
  39958. webglSlot = currentTextureSlot;
  39959. }
  39960. }
  39961. let boundTexture = currentBoundTextures[ webglSlot ];
  39962. if ( boundTexture === undefined ) {
  39963. boundTexture = { type: undefined, texture: undefined };
  39964. currentBoundTextures[ webglSlot ] = boundTexture;
  39965. }
  39966. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39967. if ( currentTextureSlot !== webglSlot ) {
  39968. gl.activeTexture( webglSlot );
  39969. this.currentTextureSlot = webglSlot;
  39970. }
  39971. gl.bindTexture( webglType, webglTexture );
  39972. boundTexture.type = webglType;
  39973. boundTexture.texture = webglTexture;
  39974. }
  39975. }
  39976. /**
  39977. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  39978. *
  39979. * This method caches the state so `gl.bindBufferBase()` is only
  39980. * called when necessary.
  39981. *
  39982. * @param {number} target - The target for the bind operation.
  39983. * @param {number} index - The index of the target.
  39984. * @param {WebGLBuffer} buffer - The WebGL buffer.
  39985. * @return {boolean} Whether a bind has been executed or not.
  39986. */
  39987. bindBufferBase( target, index, buffer ) {
  39988. const { gl } = this;
  39989. const key = `${target}-${index}`;
  39990. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39991. gl.bindBufferBase( target, index, buffer );
  39992. this.currentBoundBufferBases[ key ] = buffer;
  39993. return true;
  39994. }
  39995. return false;
  39996. }
  39997. /**
  39998. * Unbinds the current bound texture.
  39999. *
  40000. * This method caches the state so `gl.bindTexture()` is only
  40001. * called when necessary.
  40002. */
  40003. unbindTexture() {
  40004. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40005. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40006. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40007. gl.bindTexture( boundTexture.type, null );
  40008. boundTexture.type = undefined;
  40009. boundTexture.texture = undefined;
  40010. }
  40011. }
  40012. }
  40013. /**
  40014. * A WebGL 2 backend utility module with common helpers.
  40015. *
  40016. * @private
  40017. */
  40018. class WebGLUtils {
  40019. /**
  40020. * Constructs a new utility object.
  40021. *
  40022. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40023. */
  40024. constructor( backend ) {
  40025. /**
  40026. * A reference to the WebGL 2 backend.
  40027. *
  40028. * @type {WebGLBackend}
  40029. */
  40030. this.backend = backend;
  40031. /**
  40032. * A reference to the rendering context.
  40033. *
  40034. * @type {WebGL2RenderingContext}
  40035. */
  40036. this.gl = this.backend.gl;
  40037. /**
  40038. * A reference to a backend module holding extension-related
  40039. * utility functions.
  40040. *
  40041. * @type {WebGLExtensions}
  40042. */
  40043. this.extensions = backend.extensions;
  40044. }
  40045. /**
  40046. * Converts the given three.js constant into a WebGL constant.
  40047. * The method currently supports the conversion of texture formats
  40048. * and types.
  40049. *
  40050. * @param {number} p - The three.js constant.
  40051. * @param {string} [colorSpace=NoColorSpace] - The color space.
  40052. * @return {number} The corresponding WebGL constant.
  40053. */
  40054. convert( p, colorSpace = NoColorSpace ) {
  40055. const { gl, extensions } = this;
  40056. let extension;
  40057. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40058. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40059. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40060. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40061. if ( p === ByteType ) return gl.BYTE;
  40062. if ( p === ShortType ) return gl.SHORT;
  40063. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40064. if ( p === IntType ) return gl.INT;
  40065. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40066. if ( p === FloatType ) return gl.FLOAT;
  40067. if ( p === HalfFloatType ) {
  40068. return gl.HALF_FLOAT;
  40069. }
  40070. if ( p === AlphaFormat ) return gl.ALPHA;
  40071. if ( p === RGBFormat ) return gl.RGB;
  40072. if ( p === RGBAFormat ) return gl.RGBA;
  40073. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40074. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40075. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40076. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40077. // WebGL2 formats.
  40078. if ( p === RedFormat ) return gl.RED;
  40079. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40080. if ( p === RGFormat ) return gl.RG;
  40081. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40082. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40083. // S3TC
  40084. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40085. if ( colorSpace === SRGBColorSpace ) {
  40086. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40087. if ( extension !== null ) {
  40088. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40089. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40090. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40091. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40092. } else {
  40093. return null;
  40094. }
  40095. } else {
  40096. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40097. if ( extension !== null ) {
  40098. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40099. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40100. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40101. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40102. } else {
  40103. return null;
  40104. }
  40105. }
  40106. }
  40107. // PVRTC
  40108. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40109. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40110. if ( extension !== null ) {
  40111. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40112. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40113. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40114. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40115. } else {
  40116. return null;
  40117. }
  40118. }
  40119. // ETC
  40120. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40121. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40122. if ( extension !== null ) {
  40123. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40124. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40125. } else {
  40126. return null;
  40127. }
  40128. }
  40129. // ASTC
  40130. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40131. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40132. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40133. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40134. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40135. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40136. if ( extension !== null ) {
  40137. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40138. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40139. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40140. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40141. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40142. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40143. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40144. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40145. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40146. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40147. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40148. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40149. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40150. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40151. } else {
  40152. return null;
  40153. }
  40154. }
  40155. // BPTC
  40156. if ( p === RGBA_BPTC_Format ) {
  40157. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40158. if ( extension !== null ) {
  40159. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40160. } else {
  40161. return null;
  40162. }
  40163. }
  40164. // RGTC
  40165. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40166. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40167. if ( extension !== null ) {
  40168. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40169. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40170. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40171. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40172. } else {
  40173. return null;
  40174. }
  40175. }
  40176. //
  40177. if ( p === UnsignedInt248Type ) {
  40178. return gl.UNSIGNED_INT_24_8;
  40179. }
  40180. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40181. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40182. }
  40183. /**
  40184. * This method can be used to synchronize the CPU with the GPU by waiting until
  40185. * ongoing GPU commands have been completed.
  40186. *
  40187. * @private
  40188. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  40189. */
  40190. _clientWaitAsync() {
  40191. const { gl } = this;
  40192. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40193. gl.flush();
  40194. return new Promise( ( resolve, reject ) => {
  40195. function test() {
  40196. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40197. if ( res === gl.WAIT_FAILED ) {
  40198. gl.deleteSync( sync );
  40199. reject();
  40200. return;
  40201. }
  40202. if ( res === gl.TIMEOUT_EXPIRED ) {
  40203. requestAnimationFrame( test );
  40204. return;
  40205. }
  40206. gl.deleteSync( sync );
  40207. resolve();
  40208. }
  40209. test();
  40210. } );
  40211. }
  40212. }
  40213. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40214. /**
  40215. * A WebGL 2 backend utility module for managing textures.
  40216. *
  40217. * @private
  40218. */
  40219. class WebGLTextureUtils {
  40220. /**
  40221. * Constructs a new utility object.
  40222. *
  40223. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40224. */
  40225. constructor( backend ) {
  40226. /**
  40227. * A reference to the WebGL 2 backend.
  40228. *
  40229. * @type {WebGLBackend}
  40230. */
  40231. this.backend = backend;
  40232. /**
  40233. * A reference to the rendering context.
  40234. *
  40235. * @type {WebGL2RenderingContext}
  40236. */
  40237. this.gl = backend.gl;
  40238. /**
  40239. * A reference to a backend module holding extension-related
  40240. * utility functions.
  40241. *
  40242. * @type {WebGLExtensions}
  40243. */
  40244. this.extensions = backend.extensions;
  40245. /**
  40246. * A dictionary for managing default textures. The key
  40247. * is the binding point (target), the value the WEbGL texture object.
  40248. *
  40249. * @type {Object<GLenum,WebGLTexture>}
  40250. */
  40251. this.defaultTextures = {};
  40252. if ( initialized === false ) {
  40253. this._init();
  40254. initialized = true;
  40255. }
  40256. }
  40257. /**
  40258. * Inits the state of the utility.
  40259. *
  40260. * @private
  40261. */
  40262. _init() {
  40263. const gl = this.gl;
  40264. // Store only WebGL constants here.
  40265. wrappingToGL = {
  40266. [ RepeatWrapping ]: gl.REPEAT,
  40267. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40268. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40269. };
  40270. filterToGL = {
  40271. [ NearestFilter ]: gl.NEAREST,
  40272. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40273. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40274. [ LinearFilter ]: gl.LINEAR,
  40275. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40276. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40277. };
  40278. compareToGL = {
  40279. [ NeverCompare ]: gl.NEVER,
  40280. [ AlwaysCompare ]: gl.ALWAYS,
  40281. [ LessCompare ]: gl.LESS,
  40282. [ LessEqualCompare ]: gl.LEQUAL,
  40283. [ EqualCompare ]: gl.EQUAL,
  40284. [ GreaterEqualCompare ]: gl.GEQUAL,
  40285. [ GreaterCompare ]: gl.GREATER,
  40286. [ NotEqualCompare ]: gl.NOTEQUAL
  40287. };
  40288. }
  40289. /**
  40290. * Returns the native texture type for the given texture.
  40291. *
  40292. * @param {Texture} texture - The texture.
  40293. * @return {GLenum} The native texture type.
  40294. */
  40295. getGLTextureType( texture ) {
  40296. const { gl } = this;
  40297. let glTextureType;
  40298. if ( texture.isCubeTexture === true ) {
  40299. glTextureType = gl.TEXTURE_CUBE_MAP;
  40300. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40301. glTextureType = gl.TEXTURE_2D_ARRAY;
  40302. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40303. glTextureType = gl.TEXTURE_3D;
  40304. } else {
  40305. glTextureType = gl.TEXTURE_2D;
  40306. }
  40307. return glTextureType;
  40308. }
  40309. /**
  40310. * Returns the native texture type for the given texture.
  40311. *
  40312. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  40313. * @param {GLenum} glFormat - The WebGL format.
  40314. * @param {GLenum} glType - The WebGL type.
  40315. * @param {string} colorSpace - The texture's color space.
  40316. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  40317. * @return {GLenum} The internal format.
  40318. */
  40319. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40320. const { gl, extensions } = this;
  40321. if ( internalFormatName !== null ) {
  40322. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40323. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40324. }
  40325. let internalFormat = glFormat;
  40326. if ( glFormat === gl.RED ) {
  40327. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40328. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40329. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40330. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40331. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40332. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40333. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40334. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40335. }
  40336. if ( glFormat === gl.RED_INTEGER ) {
  40337. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40338. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40339. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40340. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40341. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40342. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40343. }
  40344. if ( glFormat === gl.RG ) {
  40345. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40346. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40347. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40348. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40349. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40350. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40351. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40352. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40353. }
  40354. if ( glFormat === gl.RG_INTEGER ) {
  40355. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40356. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40357. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40358. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40359. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40360. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40361. }
  40362. if ( glFormat === gl.RGB ) {
  40363. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40364. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40365. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40366. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40367. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40368. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40369. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40370. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40371. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40372. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40373. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40374. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40375. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40376. }
  40377. if ( glFormat === gl.RGB_INTEGER ) {
  40378. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40379. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40380. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40381. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40382. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40383. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40384. }
  40385. if ( glFormat === gl.RGBA ) {
  40386. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40387. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40388. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40389. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40390. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40391. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40392. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40393. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40394. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40395. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40396. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40397. }
  40398. if ( glFormat === gl.RGBA_INTEGER ) {
  40399. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40400. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40401. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40402. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40403. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40404. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40405. }
  40406. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40407. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  40408. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  40409. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40410. }
  40411. if ( glFormat === gl.DEPTH_STENCIL ) {
  40412. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40413. }
  40414. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40415. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40416. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40417. extensions.get( 'EXT_color_buffer_float' );
  40418. }
  40419. return internalFormat;
  40420. }
  40421. /**
  40422. * Sets the texture parameters for the given texture.
  40423. *
  40424. * @param {GLenum} textureType - The texture type.
  40425. * @param {Texture} texture - The texture.
  40426. */
  40427. setTextureParameters( textureType, texture ) {
  40428. const { gl, extensions, backend } = this;
  40429. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40430. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40431. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40432. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40433. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40434. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40435. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40436. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40437. }
  40438. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40439. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40440. // follow WebGPU backend mapping for texture filtering
  40441. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40442. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40443. if ( texture.compareFunction ) {
  40444. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40445. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40446. }
  40447. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40448. if ( texture.magFilter === NearestFilter ) return;
  40449. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40450. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40451. if ( texture.anisotropy > 1 ) {
  40452. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40453. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40454. }
  40455. }
  40456. }
  40457. /**
  40458. * Creates a default texture for the given texture that can be used
  40459. * as a placeholder until the actual texture is ready for usage.
  40460. *
  40461. * @param {Texture} texture - The texture to create a default texture for.
  40462. */
  40463. createDefaultTexture( texture ) {
  40464. const { gl, backend, defaultTextures } = this;
  40465. const glTextureType = this.getGLTextureType( texture );
  40466. let textureGPU = defaultTextures[ glTextureType ];
  40467. if ( textureGPU === undefined ) {
  40468. textureGPU = gl.createTexture();
  40469. backend.state.bindTexture( glTextureType, textureGPU );
  40470. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40471. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40472. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40473. defaultTextures[ glTextureType ] = textureGPU;
  40474. }
  40475. backend.set( texture, {
  40476. textureGPU,
  40477. glTextureType,
  40478. isDefault: true
  40479. } );
  40480. }
  40481. /**
  40482. * Defines a texture on the GPU for the given texture object.
  40483. *
  40484. * @param {Texture} texture - The texture.
  40485. * @param {Object} [options={}] - Optional configuration parameter.
  40486. * @return {undefined}
  40487. */
  40488. createTexture( texture, options ) {
  40489. const { gl, backend } = this;
  40490. const { levels, width, height, depth } = options;
  40491. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40492. const glType = backend.utils.convert( texture.type );
  40493. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40494. const textureGPU = gl.createTexture();
  40495. const glTextureType = this.getGLTextureType( texture );
  40496. backend.state.bindTexture( glTextureType, textureGPU );
  40497. this.setTextureParameters( glTextureType, texture );
  40498. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40499. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40500. } else if ( texture.isData3DTexture ) {
  40501. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40502. } else if ( ! texture.isVideoTexture ) {
  40503. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40504. }
  40505. backend.set( texture, {
  40506. textureGPU,
  40507. glTextureType,
  40508. glFormat,
  40509. glType,
  40510. glInternalFormat
  40511. } );
  40512. }
  40513. /**
  40514. * Uploads texture buffer data to the GPU memory.
  40515. *
  40516. * @param {WebGLBuffer} buffer - The buffer data.
  40517. * @param {Texture} texture - The texture,
  40518. */
  40519. copyBufferToTexture( buffer, texture ) {
  40520. const { gl, backend } = this;
  40521. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40522. const { width, height } = texture.source.data;
  40523. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40524. backend.state.bindTexture( glTextureType, textureGPU );
  40525. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40526. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40527. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40528. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40529. backend.state.unbindTexture();
  40530. // debug
  40531. // const framebuffer = gl.createFramebuffer();
  40532. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40533. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40534. // const readout = new Float32Array( width * height * 4 );
  40535. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40536. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40537. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40538. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40539. // console.log( readout );
  40540. }
  40541. /**
  40542. * Uploads the updated texture data to the GPU.
  40543. *
  40544. * @param {Texture} texture - The texture.
  40545. * @param {Object} [options={}] - Optional configuration parameter.
  40546. */
  40547. updateTexture( texture, options ) {
  40548. const { gl } = this;
  40549. const { width, height } = options;
  40550. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40551. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40552. return;
  40553. const getImage = ( source ) => {
  40554. if ( source.isDataTexture ) {
  40555. return source.image.data;
  40556. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  40557. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  40558. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  40559. source instanceof OffscreenCanvas ) {
  40560. return source;
  40561. }
  40562. return source.data;
  40563. };
  40564. this.backend.state.bindTexture( glTextureType, textureGPU );
  40565. this.setTextureParameters( glTextureType, texture );
  40566. if ( texture.isCompressedTexture ) {
  40567. const mipmaps = texture.mipmaps;
  40568. const image = options.image;
  40569. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40570. const mipmap = mipmaps[ i ];
  40571. if ( texture.isCompressedArrayTexture ) {
  40572. if ( texture.format !== gl.RGBA ) {
  40573. if ( glFormat !== null ) {
  40574. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40575. } else {
  40576. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40577. }
  40578. } else {
  40579. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40580. }
  40581. } else {
  40582. if ( glFormat !== null ) {
  40583. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40584. } else {
  40585. console.warn( 'Unsupported compressed texture format' );
  40586. }
  40587. }
  40588. }
  40589. } else if ( texture.isCubeTexture ) {
  40590. const images = options.images;
  40591. for ( let i = 0; i < 6; i ++ ) {
  40592. const image = getImage( images[ i ] );
  40593. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40594. }
  40595. } else if ( texture.isDataArrayTexture ) {
  40596. const image = options.image;
  40597. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40598. } else if ( texture.isData3DTexture ) {
  40599. const image = options.image;
  40600. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40601. } else if ( texture.isVideoTexture ) {
  40602. texture.update();
  40603. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40604. } else {
  40605. const image = getImage( options.image );
  40606. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40607. }
  40608. }
  40609. /**
  40610. * Generates mipmaps for the given texture.
  40611. *
  40612. * @param {Texture} texture - The texture.
  40613. */
  40614. generateMipmaps( texture ) {
  40615. const { gl, backend } = this;
  40616. const { textureGPU, glTextureType } = backend.get( texture );
  40617. backend.state.bindTexture( glTextureType, textureGPU );
  40618. gl.generateMipmap( glTextureType );
  40619. }
  40620. /**
  40621. * Deallocates the render buffers of the given render target.
  40622. *
  40623. * @param {RenderTarget} renderTarget - The render target.
  40624. */
  40625. deallocateRenderBuffers( renderTarget ) {
  40626. const { gl, backend } = this;
  40627. // remove framebuffer reference
  40628. if ( renderTarget ) {
  40629. const renderContextData = backend.get( renderTarget );
  40630. renderContextData.renderBufferStorageSetup = undefined;
  40631. if ( renderContextData.framebuffers ) {
  40632. for ( const cacheKey in renderContextData.framebuffers ) {
  40633. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40634. }
  40635. delete renderContextData.framebuffers;
  40636. }
  40637. if ( renderContextData.depthRenderbuffer ) {
  40638. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40639. delete renderContextData.depthRenderbuffer;
  40640. }
  40641. if ( renderContextData.stencilRenderbuffer ) {
  40642. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40643. delete renderContextData.stencilRenderbuffer;
  40644. }
  40645. if ( renderContextData.msaaFrameBuffer ) {
  40646. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40647. delete renderContextData.msaaFrameBuffer;
  40648. }
  40649. if ( renderContextData.msaaRenderbuffers ) {
  40650. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40651. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40652. }
  40653. delete renderContextData.msaaRenderbuffers;
  40654. }
  40655. }
  40656. }
  40657. /**
  40658. * Destroys the GPU data for the given texture object.
  40659. *
  40660. * @param {Texture} texture - The texture.
  40661. */
  40662. destroyTexture( texture ) {
  40663. const { gl, backend } = this;
  40664. const { textureGPU, renderTarget } = backend.get( texture );
  40665. this.deallocateRenderBuffers( renderTarget );
  40666. gl.deleteTexture( textureGPU );
  40667. backend.delete( texture );
  40668. }
  40669. /**
  40670. * Copies data of the given source texture to the given destination texture.
  40671. *
  40672. * @param {Texture} srcTexture - The source texture.
  40673. * @param {Texture} dstTexture - The destination texture.
  40674. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  40675. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40676. * @param {number} [level=0] - The mip level to copy.
  40677. */
  40678. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40679. const { gl, backend } = this;
  40680. const { state } = this.backend;
  40681. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40682. let width, height, minX, minY;
  40683. let dstX, dstY;
  40684. if ( srcRegion !== null ) {
  40685. width = srcRegion.max.x - srcRegion.min.x;
  40686. height = srcRegion.max.y - srcRegion.min.y;
  40687. minX = srcRegion.min.x;
  40688. minY = srcRegion.min.y;
  40689. } else {
  40690. width = srcTexture.image.width;
  40691. height = srcTexture.image.height;
  40692. minX = 0;
  40693. minY = 0;
  40694. }
  40695. if ( dstPosition !== null ) {
  40696. dstX = dstPosition.x;
  40697. dstY = dstPosition.y;
  40698. } else {
  40699. dstX = 0;
  40700. dstY = 0;
  40701. }
  40702. state.bindTexture( glTextureType, dstTextureGPU );
  40703. // As another texture upload may have changed pixelStorei
  40704. // parameters, make sure they are correct for the dstTexture
  40705. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40706. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40707. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40708. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40709. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40710. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40711. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40712. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40713. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40714. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40715. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40716. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40717. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40718. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40719. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40720. const srcTextureData = backend.get( srcTexture );
  40721. const dstTextureData = backend.get( dstTexture );
  40722. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40723. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40724. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40725. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40726. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40727. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40728. let mask = gl.COLOR_BUFFER_BIT;
  40729. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40730. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40731. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40732. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40733. } else {
  40734. if ( srcTexture.isDataTexture ) {
  40735. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40736. } else {
  40737. if ( srcTexture.isCompressedTexture ) {
  40738. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40739. } else {
  40740. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40741. }
  40742. }
  40743. }
  40744. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40745. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40746. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40747. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40748. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40749. // Generate mipmaps only when copying level 0
  40750. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40751. state.unbindTexture();
  40752. }
  40753. /**
  40754. * Copies the current bound framebuffer to the given texture.
  40755. *
  40756. * @param {Texture} texture - The destination texture.
  40757. * @param {RenderContext} renderContext - The render context.
  40758. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40759. */
  40760. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40761. const { gl } = this;
  40762. const { state } = this.backend;
  40763. const { textureGPU } = this.backend.get( texture );
  40764. const { x, y, z: width, w: height } = rectangle;
  40765. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40766. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  40767. if ( requireDrawFrameBuffer ) {
  40768. const partial = ( x !== 0 || y !== 0 );
  40769. let mask;
  40770. let attachment;
  40771. if ( texture.isDepthTexture === true ) {
  40772. mask = gl.DEPTH_BUFFER_BIT;
  40773. attachment = gl.DEPTH_ATTACHMENT;
  40774. if ( renderContext.stencil ) {
  40775. mask |= gl.STENCIL_BUFFER_BIT;
  40776. }
  40777. } else {
  40778. mask = gl.COLOR_BUFFER_BIT;
  40779. attachment = gl.COLOR_ATTACHMENT0;
  40780. }
  40781. if ( partial ) {
  40782. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40783. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40784. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40785. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40786. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40787. const flippedY = srcHeight - y - height;
  40788. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40789. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40790. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40791. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40792. state.unbindTexture();
  40793. } else {
  40794. const fb = gl.createFramebuffer();
  40795. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40796. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40797. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40798. gl.deleteFramebuffer( fb );
  40799. }
  40800. } else {
  40801. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40802. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40803. state.unbindTexture();
  40804. }
  40805. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40806. this.backend._setFramebuffer( renderContext );
  40807. }
  40808. /**
  40809. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  40810. *
  40811. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  40812. * @param {RenderContext} renderContext - The render context.
  40813. * @param {number} samples - The MSAA sample count.
  40814. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  40815. */
  40816. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  40817. const { gl } = this;
  40818. const renderTarget = renderContext.renderTarget;
  40819. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40820. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40821. if ( depthBuffer && ! stencilBuffer ) {
  40822. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40823. if ( useMultisampledRTT === true ) {
  40824. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40825. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  40826. } else if ( samples > 0 ) {
  40827. if ( depthTexture && depthTexture.isDepthTexture ) {
  40828. if ( depthTexture.type === gl.FLOAT ) {
  40829. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40830. }
  40831. }
  40832. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40833. } else {
  40834. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40835. }
  40836. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40837. } else if ( depthBuffer && stencilBuffer ) {
  40838. if ( samples > 0 ) {
  40839. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40840. } else {
  40841. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40842. }
  40843. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40844. }
  40845. }
  40846. /**
  40847. * Returns texture data as a typed array.
  40848. *
  40849. * @async
  40850. * @param {Texture} texture - The texture to copy.
  40851. * @param {number} x - The x coordinate of the copy origin.
  40852. * @param {number} y - The y coordinate of the copy origin.
  40853. * @param {number} width - The width of the copy.
  40854. * @param {number} height - The height of the copy.
  40855. * @param {number} faceIndex - The face index.
  40856. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40857. */
  40858. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40859. const { backend, gl } = this;
  40860. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40861. const fb = gl.createFramebuffer();
  40862. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40863. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40864. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40865. const typedArrayType = this._getTypedArrayType( glType );
  40866. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40867. const elementCount = width * height;
  40868. const byteLength = elementCount * bytesPerTexel;
  40869. const buffer = gl.createBuffer();
  40870. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40871. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40872. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40873. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40874. await backend.utils._clientWaitAsync();
  40875. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40876. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40877. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40878. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40879. gl.deleteFramebuffer( fb );
  40880. return dstBuffer;
  40881. }
  40882. /**
  40883. * Returns the corresponding typed array type for the given WebGL data type.
  40884. *
  40885. * @private
  40886. * @param {GLenum} glType - The WebGL data type.
  40887. * @return {TypedArray.constructor} The typed array type.
  40888. */
  40889. _getTypedArrayType( glType ) {
  40890. const { gl } = this;
  40891. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40892. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40893. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40894. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40895. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40896. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40897. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40898. if ( glType === gl.FLOAT ) return Float32Array;
  40899. throw new Error( `Unsupported WebGL type: ${glType}` );
  40900. }
  40901. /**
  40902. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  40903. *
  40904. * @private
  40905. * @param {GLenum} glType - The WebGL data type.
  40906. * @param {GLenum} glFormat - The WebGL texture format.
  40907. * @return {number} The bytes-per-texel.
  40908. */
  40909. _getBytesPerTexel( glType, glFormat ) {
  40910. const { gl } = this;
  40911. let bytesPerComponent = 0;
  40912. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40913. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40914. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40915. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40916. glType === gl.UNSIGNED_SHORT ||
  40917. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40918. if ( glType === gl.UNSIGNED_INT ||
  40919. glType === gl.FLOAT ) bytesPerComponent = 4;
  40920. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40921. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40922. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40923. }
  40924. }
  40925. /**
  40926. * A WebGL 2 backend utility module for managing extensions.
  40927. *
  40928. * @private
  40929. */
  40930. class WebGLExtensions {
  40931. /**
  40932. * Constructs a new utility object.
  40933. *
  40934. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40935. */
  40936. constructor( backend ) {
  40937. /**
  40938. * A reference to the WebGL 2 backend.
  40939. *
  40940. * @type {WebGLBackend}
  40941. */
  40942. this.backend = backend;
  40943. /**
  40944. * A reference to the rendering context.
  40945. *
  40946. * @type {WebGL2RenderingContext}
  40947. */
  40948. this.gl = this.backend.gl;
  40949. /**
  40950. * A list with all the supported WebGL extensions.
  40951. *
  40952. * @type {Array<string>}
  40953. */
  40954. this.availableExtensions = this.gl.getSupportedExtensions();
  40955. /**
  40956. * A dictionary with requested WebGL extensions.
  40957. * The key is the name of the extension, the value
  40958. * the requested extension object.
  40959. *
  40960. * @type {Object<string,Object>}
  40961. */
  40962. this.extensions = {};
  40963. }
  40964. /**
  40965. * Returns the extension object for the given extension name.
  40966. *
  40967. * @param {string} name - The extension name.
  40968. * @return {Object} The extension object.
  40969. */
  40970. get( name ) {
  40971. let extension = this.extensions[ name ];
  40972. if ( extension === undefined ) {
  40973. extension = this.gl.getExtension( name );
  40974. this.extensions[ name ] = extension;
  40975. }
  40976. return extension;
  40977. }
  40978. /**
  40979. * Returns `true` if the requested extension is available.
  40980. *
  40981. * @param {string} name - The extension name.
  40982. * @return {boolean} Whether the given extension is available or not.
  40983. */
  40984. has( name ) {
  40985. return this.availableExtensions.includes( name );
  40986. }
  40987. }
  40988. /**
  40989. * A WebGL 2 backend utility module for managing the device's capabilities.
  40990. *
  40991. * @private
  40992. */
  40993. class WebGLCapabilities {
  40994. /**
  40995. * Constructs a new utility object.
  40996. *
  40997. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40998. */
  40999. constructor( backend ) {
  41000. /**
  41001. * A reference to the WebGL 2 backend.
  41002. *
  41003. * @type {WebGLBackend}
  41004. */
  41005. this.backend = backend;
  41006. /**
  41007. * This value holds the cached max anisotropy value.
  41008. *
  41009. * @type {?number}
  41010. * @default null
  41011. */
  41012. this.maxAnisotropy = null;
  41013. }
  41014. /**
  41015. * Returns the maximum anisotropy texture filtering value. This value
  41016. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  41017. * WebGL extension.
  41018. *
  41019. * @return {number} The maximum anisotropy texture filtering value.
  41020. */
  41021. getMaxAnisotropy() {
  41022. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41023. const gl = this.backend.gl;
  41024. const extensions = this.backend.extensions;
  41025. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41026. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41027. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41028. } else {
  41029. this.maxAnisotropy = 0;
  41030. }
  41031. return this.maxAnisotropy;
  41032. }
  41033. }
  41034. const GLFeatureName = {
  41035. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41036. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41037. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41038. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41039. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41040. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41041. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41042. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41043. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41044. };
  41045. class WebGLBufferRenderer {
  41046. constructor( backend ) {
  41047. this.gl = backend.gl;
  41048. this.extensions = backend.extensions;
  41049. this.info = backend.renderer.info;
  41050. this.mode = null;
  41051. this.index = 0;
  41052. this.type = null;
  41053. this.object = null;
  41054. }
  41055. render( start, count ) {
  41056. const { gl, mode, object, type, info, index } = this;
  41057. if ( index !== 0 ) {
  41058. gl.drawElements( mode, count, type, start );
  41059. } else {
  41060. gl.drawArrays( mode, start, count );
  41061. }
  41062. info.update( object, count, 1 );
  41063. }
  41064. renderInstances( start, count, primcount ) {
  41065. const { gl, mode, type, index, object, info } = this;
  41066. if ( primcount === 0 ) return;
  41067. if ( index !== 0 ) {
  41068. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41069. } else {
  41070. gl.drawArraysInstanced( mode, start, count, primcount );
  41071. }
  41072. info.update( object, count, primcount );
  41073. }
  41074. renderMultiDraw( starts, counts, drawCount ) {
  41075. const { extensions, mode, object, info } = this;
  41076. if ( drawCount === 0 ) return;
  41077. const extension = extensions.get( 'WEBGL_multi_draw' );
  41078. if ( extension === null ) {
  41079. for ( let i = 0; i < drawCount; i ++ ) {
  41080. this.render( starts[ i ], counts[ i ] );
  41081. }
  41082. } else {
  41083. if ( this.index !== 0 ) {
  41084. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41085. } else {
  41086. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41087. }
  41088. let elementCount = 0;
  41089. for ( let i = 0; i < drawCount; i ++ ) {
  41090. elementCount += counts[ i ];
  41091. }
  41092. info.update( object, elementCount, 1 );
  41093. }
  41094. }
  41095. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41096. const { extensions, mode, object, info } = this;
  41097. if ( drawCount === 0 ) return;
  41098. const extension = extensions.get( 'WEBGL_multi_draw' );
  41099. if ( extension === null ) {
  41100. for ( let i = 0; i < drawCount; i ++ ) {
  41101. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41102. }
  41103. } else {
  41104. if ( this.index !== 0 ) {
  41105. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41106. } else {
  41107. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41108. }
  41109. let elementCount = 0;
  41110. for ( let i = 0; i < drawCount; i ++ ) {
  41111. elementCount += counts[ i ] * primcount[ i ];
  41112. }
  41113. info.update( object, elementCount, 1 );
  41114. }
  41115. }
  41116. //
  41117. }
  41118. /**
  41119. * Abstract base class of a timestamp query pool.
  41120. *
  41121. * @abstract
  41122. */
  41123. class TimestampQueryPool {
  41124. /**
  41125. * Creates a new timestamp query pool.
  41126. *
  41127. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  41128. */
  41129. constructor( maxQueries = 256 ) {
  41130. /**
  41131. * Whether to track timestamps or not.
  41132. *
  41133. * @type {boolean}
  41134. * @default true
  41135. */
  41136. this.trackTimestamp = true;
  41137. /**
  41138. * Maximum number of queries this pool can hold.
  41139. *
  41140. * @type {number}
  41141. * @default 256
  41142. */
  41143. this.maxQueries = maxQueries;
  41144. /**
  41145. * How many queries allocated so far.
  41146. *
  41147. * @type {number}
  41148. * @default 0
  41149. */
  41150. this.currentQueryIndex = 0;
  41151. /**
  41152. * Tracks offsets for different contexts.
  41153. *
  41154. * @type {Map}
  41155. */
  41156. this.queryOffsets = new Map();
  41157. /**
  41158. * Whether the pool has been disposed or not.
  41159. *
  41160. * @type {boolean}
  41161. * @default false
  41162. */
  41163. this.isDisposed = false;
  41164. /**
  41165. * TODO
  41166. *
  41167. * @type {number}
  41168. * @default 0
  41169. */
  41170. this.lastValue = 0;
  41171. /**
  41172. * TODO
  41173. *
  41174. * @type {boolean}
  41175. * @default false
  41176. */
  41177. this.pendingResolve = false;
  41178. }
  41179. /**
  41180. * Allocate queries for a specific renderContext.
  41181. *
  41182. * @abstract
  41183. * @param {Object} renderContext - The render context to allocate queries for.
  41184. */
  41185. allocateQueriesForContext( /* renderContext */ ) {}
  41186. /**
  41187. * Resolve all timestamps and return data (or process them).
  41188. *
  41189. * @abstract
  41190. * @async
  41191. * @returns {Promise<number>|number} The resolved timestamp value.
  41192. */
  41193. async resolveQueriesAsync() {}
  41194. /**
  41195. * Dispose of the query pool.
  41196. *
  41197. * @abstract
  41198. */
  41199. dispose() {}
  41200. }
  41201. /**
  41202. * Manages a pool of WebGL timestamp queries for performance measurement.
  41203. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  41204. *
  41205. * @augments TimestampQueryPool
  41206. */
  41207. class WebGLTimestampQueryPool extends TimestampQueryPool {
  41208. /**
  41209. * Creates a new WebGL timestamp query pool.
  41210. *
  41211. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  41212. * @param {string} type - The type identifier for this query pool.
  41213. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  41214. */
  41215. constructor( gl, type, maxQueries = 2048 ) {
  41216. super( maxQueries );
  41217. this.gl = gl;
  41218. this.type = type;
  41219. // Check for timer query extensions
  41220. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  41221. gl.getExtension( 'EXT_disjoint_timer_query' );
  41222. if ( ! this.ext ) {
  41223. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  41224. this.trackTimestamp = false;
  41225. return;
  41226. }
  41227. // Create query objects
  41228. this.queries = [];
  41229. for ( let i = 0; i < this.maxQueries; i ++ ) {
  41230. this.queries.push( gl.createQuery() );
  41231. }
  41232. this.activeQuery = null;
  41233. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  41234. }
  41235. /**
  41236. * Allocates a pair of queries for a given render context.
  41237. *
  41238. * @param {Object} renderContext - The render context to allocate queries for.
  41239. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  41240. */
  41241. allocateQueriesForContext( renderContext ) {
  41242. if ( ! this.trackTimestamp ) return null;
  41243. // Check if we have enough space for a new query pair
  41244. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  41245. 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() } ).` );
  41246. return null;
  41247. }
  41248. const baseOffset = this.currentQueryIndex;
  41249. this.currentQueryIndex += 2;
  41250. // Initialize query states
  41251. this.queryStates.set( baseOffset, 'inactive' );
  41252. this.queryOffsets.set( renderContext.id, baseOffset );
  41253. return baseOffset;
  41254. }
  41255. /**
  41256. * Begins a timestamp query for the specified render context.
  41257. *
  41258. * @param {Object} renderContext - The render context to begin timing for.
  41259. */
  41260. beginQuery( renderContext ) {
  41261. if ( ! this.trackTimestamp || this.isDisposed ) {
  41262. return;
  41263. }
  41264. const baseOffset = this.queryOffsets.get( renderContext.id );
  41265. if ( baseOffset == null ) {
  41266. return;
  41267. }
  41268. // Don't start a new query if there's an active one
  41269. if ( this.activeQuery !== null ) {
  41270. return;
  41271. }
  41272. const query = this.queries[ baseOffset ];
  41273. if ( ! query ) {
  41274. return;
  41275. }
  41276. try {
  41277. // Only begin if query is inactive
  41278. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  41279. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  41280. this.activeQuery = baseOffset;
  41281. this.queryStates.set( baseOffset, 'started' );
  41282. }
  41283. } catch ( error ) {
  41284. console.error( 'Error in beginQuery:', error );
  41285. this.activeQuery = null;
  41286. this.queryStates.set( baseOffset, 'inactive' );
  41287. }
  41288. }
  41289. /**
  41290. * Ends the active timestamp query for the specified render context.
  41291. *
  41292. * @param {Object} renderContext - The render context to end timing for.
  41293. * @param {string} renderContext.id - Unique identifier for the render context.
  41294. */
  41295. endQuery( renderContext ) {
  41296. if ( ! this.trackTimestamp || this.isDisposed ) {
  41297. return;
  41298. }
  41299. const baseOffset = this.queryOffsets.get( renderContext.id );
  41300. if ( baseOffset == null ) {
  41301. return;
  41302. }
  41303. // Only end if this is the active query
  41304. if ( this.activeQuery !== baseOffset ) {
  41305. return;
  41306. }
  41307. try {
  41308. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  41309. this.queryStates.set( baseOffset, 'ended' );
  41310. this.activeQuery = null;
  41311. } catch ( error ) {
  41312. console.error( 'Error in endQuery:', error );
  41313. // Reset state on error
  41314. this.queryStates.set( baseOffset, 'inactive' );
  41315. this.activeQuery = null;
  41316. }
  41317. }
  41318. /**
  41319. * Asynchronously resolves all completed queries and returns the total duration.
  41320. *
  41321. * @async
  41322. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  41323. */
  41324. async resolveQueriesAsync() {
  41325. if ( ! this.trackTimestamp || this.pendingResolve ) {
  41326. return this.lastValue;
  41327. }
  41328. this.pendingResolve = true;
  41329. try {
  41330. // Wait for all ended queries to complete
  41331. const resolvePromises = [];
  41332. for ( const [ baseOffset, state ] of this.queryStates ) {
  41333. if ( state === 'ended' ) {
  41334. const query = this.queries[ baseOffset ];
  41335. resolvePromises.push( this.resolveQuery( query ) );
  41336. }
  41337. }
  41338. if ( resolvePromises.length === 0 ) {
  41339. return this.lastValue;
  41340. }
  41341. const results = await Promise.all( resolvePromises );
  41342. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  41343. // Store the last valid result
  41344. this.lastValue = totalDuration;
  41345. // Reset states
  41346. this.currentQueryIndex = 0;
  41347. this.queryOffsets.clear();
  41348. this.queryStates.clear();
  41349. this.activeQuery = null;
  41350. return totalDuration;
  41351. } catch ( error ) {
  41352. console.error( 'Error resolving queries:', error );
  41353. return this.lastValue;
  41354. } finally {
  41355. this.pendingResolve = false;
  41356. }
  41357. }
  41358. /**
  41359. * Resolves a single query, checking for completion and disjoint operation.
  41360. *
  41361. * @async
  41362. * @param {WebGLQuery} query - The query object to resolve.
  41363. * @returns {Promise<number>} The elapsed time in milliseconds.
  41364. */
  41365. async resolveQuery( query ) {
  41366. return new Promise( ( resolve ) => {
  41367. if ( this.isDisposed ) {
  41368. resolve( this.lastValue );
  41369. return;
  41370. }
  41371. let timeoutId;
  41372. let isResolved = false;
  41373. const cleanup = () => {
  41374. if ( timeoutId ) {
  41375. clearTimeout( timeoutId );
  41376. timeoutId = null;
  41377. }
  41378. };
  41379. const finalizeResolution = ( value ) => {
  41380. if ( ! isResolved ) {
  41381. isResolved = true;
  41382. cleanup();
  41383. resolve( value );
  41384. }
  41385. };
  41386. const checkQuery = () => {
  41387. if ( this.isDisposed ) {
  41388. finalizeResolution( this.lastValue );
  41389. return;
  41390. }
  41391. try {
  41392. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  41393. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  41394. if ( disjoint ) {
  41395. finalizeResolution( this.lastValue );
  41396. return;
  41397. }
  41398. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  41399. if ( ! available ) {
  41400. timeoutId = setTimeout( checkQuery, 1 );
  41401. return;
  41402. }
  41403. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  41404. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  41405. } catch ( error ) {
  41406. console.error( 'Error checking query:', error );
  41407. resolve( this.lastValue );
  41408. }
  41409. };
  41410. checkQuery();
  41411. } );
  41412. }
  41413. /**
  41414. * Releases all resources held by this query pool.
  41415. * This includes deleting all query objects and clearing internal state.
  41416. */
  41417. dispose() {
  41418. if ( this.isDisposed ) {
  41419. return;
  41420. }
  41421. this.isDisposed = true;
  41422. if ( ! this.trackTimestamp ) return;
  41423. for ( const query of this.queries ) {
  41424. this.gl.deleteQuery( query );
  41425. }
  41426. this.queries = [];
  41427. this.queryStates.clear();
  41428. this.queryOffsets.clear();
  41429. this.lastValue = 0;
  41430. this.activeQuery = null;
  41431. }
  41432. }
  41433. /**
  41434. * A backend implementation targeting WebGL 2.
  41435. *
  41436. * @private
  41437. * @augments Backend
  41438. */
  41439. class WebGLBackend extends Backend {
  41440. /**
  41441. * Constructs a new WebGPU backend.
  41442. *
  41443. * @param {Object} parameters - The configuration parameter.
  41444. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41445. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41446. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41447. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41448. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41449. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  41450. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  41451. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  41452. */
  41453. constructor( parameters = {} ) {
  41454. super( parameters );
  41455. /**
  41456. * This flag can be used for type testing.
  41457. *
  41458. * @type {boolean}
  41459. * @readonly
  41460. * @default true
  41461. */
  41462. this.isWebGLBackend = true;
  41463. /**
  41464. * A reference to a backend module holding shader attribute-related
  41465. * utility functions.
  41466. *
  41467. * @type {?WebGLAttributeUtils}
  41468. * @default null
  41469. */
  41470. this.attributeUtils = null;
  41471. /**
  41472. * A reference to a backend module holding extension-related
  41473. * utility functions.
  41474. *
  41475. * @type {?WebGLExtensions}
  41476. * @default null
  41477. */
  41478. this.extensions = null;
  41479. /**
  41480. * A reference to a backend module holding capability-related
  41481. * utility functions.
  41482. *
  41483. * @type {?WebGLCapabilities}
  41484. * @default null
  41485. */
  41486. this.capabilities = null;
  41487. /**
  41488. * A reference to a backend module holding texture-related
  41489. * utility functions.
  41490. *
  41491. * @type {?WebGLTextureUtils}
  41492. * @default null
  41493. */
  41494. this.textureUtils = null;
  41495. /**
  41496. * A reference to a backend module holding renderer-related
  41497. * utility functions.
  41498. *
  41499. * @type {?WebGLBufferRenderer}
  41500. * @default null
  41501. */
  41502. this.bufferRenderer = null;
  41503. /**
  41504. * A reference to the rendering context.
  41505. *
  41506. * @type {?WebGL2RenderingContext}
  41507. * @default null
  41508. */
  41509. this.gl = null;
  41510. /**
  41511. * A reference to a backend module holding state-related
  41512. * utility functions.
  41513. *
  41514. * @type {?WebGLState}
  41515. * @default null
  41516. */
  41517. this.state = null;
  41518. /**
  41519. * A reference to a backend module holding common
  41520. * utility functions.
  41521. *
  41522. * @type {?WebGLUtils}
  41523. * @default null
  41524. */
  41525. this.utils = null;
  41526. /**
  41527. * Dictionary for caching VAOs.
  41528. *
  41529. * @type {Object<string,WebGLVertexArrayObject>}
  41530. */
  41531. this.vaoCache = {};
  41532. /**
  41533. * Dictionary for caching transform feedback objects.
  41534. *
  41535. * @type {Object<string,WebGLTransformFeedback>}
  41536. */
  41537. this.transformFeedbackCache = {};
  41538. /**
  41539. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  41540. * Only relevant when using compute shaders.
  41541. *
  41542. * @type {boolean}
  41543. * @default false
  41544. */
  41545. this.discard = false;
  41546. /**
  41547. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  41548. * device does not support the extension.
  41549. *
  41550. * @type {?EXTDisjointTimerQueryWebGL2}
  41551. * @default null
  41552. */
  41553. this.disjoint = null;
  41554. /**
  41555. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  41556. * device does not support the extension.
  41557. *
  41558. * @type {?KHRParallelShaderCompile}
  41559. * @default null
  41560. */
  41561. this.parallel = null;
  41562. /**
  41563. * Whether to track timestamps with a Timestamp Query API or not.
  41564. *
  41565. * @type {boolean}
  41566. * @default false
  41567. */
  41568. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41569. /**
  41570. * A reference to the current render context.
  41571. *
  41572. * @private
  41573. * @type {RenderContext}
  41574. * @default null
  41575. */
  41576. this._currentContext = null;
  41577. /**
  41578. * A unique collection of bindings.
  41579. *
  41580. * @private
  41581. * @type {WeakSet}
  41582. */
  41583. this._knownBindings = new WeakSet();
  41584. /**
  41585. * The target framebuffer when rendering with
  41586. * the WebXR device API.
  41587. *
  41588. * @private
  41589. * @type {WebGLFramebuffer}
  41590. * @default null
  41591. */
  41592. this._xrFamebuffer = null;
  41593. }
  41594. /**
  41595. * Initializes the backend so it is ready for usage.
  41596. *
  41597. * @param {Renderer} renderer - The renderer.
  41598. */
  41599. init( renderer ) {
  41600. super.init( renderer );
  41601. //
  41602. const parameters = this.parameters;
  41603. const contextAttributes = {
  41604. antialias: false, // MSAA is applied via a custom renderbuffer
  41605. alpha: true, // always true for performance reasons
  41606. depth: false, // depth and stencil are set to false since the engine always renders into a framebuffer target first
  41607. stencil: false
  41608. };
  41609. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  41610. function onContextLost( event ) {
  41611. event.preventDefault();
  41612. const contextLossInfo = {
  41613. api: 'WebGL',
  41614. message: event.statusMessage || 'Unknown reason',
  41615. reason: null,
  41616. originalEvent: event
  41617. };
  41618. renderer.onDeviceLost( contextLossInfo );
  41619. }
  41620. this._onContextLost = onContextLost;
  41621. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  41622. this.gl = glContext;
  41623. this.extensions = new WebGLExtensions( this );
  41624. this.capabilities = new WebGLCapabilities( this );
  41625. this.attributeUtils = new WebGLAttributeUtils( this );
  41626. this.textureUtils = new WebGLTextureUtils( this );
  41627. this.bufferRenderer = new WebGLBufferRenderer( this );
  41628. this.state = new WebGLState( this );
  41629. this.utils = new WebGLUtils( this );
  41630. this.extensions.get( 'EXT_color_buffer_float' );
  41631. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41632. this.extensions.get( 'OES_texture_float_linear' );
  41633. this.extensions.get( 'EXT_color_buffer_half_float' );
  41634. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41635. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41636. this.extensions.get( 'WEBGL_multi_draw' );
  41637. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41638. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41639. }
  41640. /**
  41641. * The coordinate system of the backend.
  41642. *
  41643. * @type {number}
  41644. * @readonly
  41645. */
  41646. get coordinateSystem() {
  41647. return WebGLCoordinateSystem;
  41648. }
  41649. /**
  41650. * This method performs a readback operation by moving buffer data from
  41651. * a storage buffer attribute from the GPU to the CPU.
  41652. *
  41653. * @async
  41654. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41655. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41656. */
  41657. async getArrayBufferAsync( attribute ) {
  41658. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41659. }
  41660. /**
  41661. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41662. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41663. *
  41664. * @async
  41665. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41666. */
  41667. async waitForGPU() {
  41668. await this.utils._clientWaitAsync();
  41669. }
  41670. /**
  41671. * Ensures the backend is XR compatible.
  41672. *
  41673. * @async
  41674. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  41675. */
  41676. async makeXRCompatible() {
  41677. const attributes = this.gl.getContextAttributes();
  41678. if ( attributes.xrCompatible !== true ) {
  41679. await this.gl.makeXRCompatible();
  41680. }
  41681. }
  41682. /**
  41683. * Sets the XR rendering destination.
  41684. *
  41685. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  41686. */
  41687. setXRTarget( xrFamebuffer ) {
  41688. this._xrFamebuffer = xrFamebuffer;
  41689. }
  41690. /**
  41691. * Configures the given XR render target with external textures.
  41692. *
  41693. * This method is only relevant when using the WebXR Layers API.
  41694. *
  41695. * @param {XRRenderTarget} renderTarget - The XR render target.
  41696. * @param {WebGLTexture} colorTexture - A native color texture.
  41697. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  41698. */
  41699. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  41700. const gl = this.gl;
  41701. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  41702. if ( depthTexture !== null ) {
  41703. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41704. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  41705. renderTarget.autoAllocateDepthBuffer = false;
  41706. // The multisample_render_to_texture extension doesn't work properly if there
  41707. // are midframe flushes and an external depth texture.
  41708. if ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  41709. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  41710. }
  41711. }
  41712. }
  41713. /**
  41714. * Inits a time stamp query for the given render context.
  41715. *
  41716. * @param {RenderContext} renderContext - The render context.
  41717. */
  41718. initTimestampQuery( renderContext ) {
  41719. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41720. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41721. if ( ! this.timestampQueryPool[ type ] ) {
  41722. // TODO: Variable maxQueries?
  41723. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  41724. }
  41725. const timestampQueryPool = this.timestampQueryPool[ type ];
  41726. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  41727. if ( baseOffset !== null ) {
  41728. timestampQueryPool.beginQuery( renderContext );
  41729. }
  41730. }
  41731. // timestamp utils
  41732. /**
  41733. * Prepares the timestamp buffer.
  41734. *
  41735. * @param {RenderContext} renderContext - The render context.
  41736. */
  41737. prepareTimestampBuffer( renderContext ) {
  41738. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41739. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41740. const timestampQueryPool = this.timestampQueryPool[ type ];
  41741. timestampQueryPool.endQuery( renderContext );
  41742. }
  41743. /**
  41744. * Returns the backend's rendering context.
  41745. *
  41746. * @return {WebGL2RenderingContext} The rendering context.
  41747. */
  41748. getContext() {
  41749. return this.gl;
  41750. }
  41751. /**
  41752. * This method is executed at the beginning of a render call and prepares
  41753. * the WebGL state for upcoming render calls
  41754. *
  41755. * @param {RenderContext} renderContext - The render context.
  41756. */
  41757. beginRender( renderContext ) {
  41758. const { state, gl } = this;
  41759. const renderContextData = this.get( renderContext );
  41760. //
  41761. if ( renderContext.viewport ) {
  41762. this.updateViewport( renderContext );
  41763. } else {
  41764. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41765. }
  41766. if ( renderContext.scissor ) {
  41767. const { x, y, width, height } = renderContext.scissorValue;
  41768. state.scissor( x, renderContext.height - height - y, width, height );
  41769. }
  41770. //
  41771. this.initTimestampQuery( renderContext );
  41772. renderContextData.previousContext = this._currentContext;
  41773. this._currentContext = renderContext;
  41774. this._setFramebuffer( renderContext );
  41775. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41776. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41777. if ( occlusionQueryCount > 0 ) {
  41778. // Get a reference to the array of objects with queries. The renderContextData property
  41779. // can be changed by another render pass before the async reading of all previous queries complete
  41780. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41781. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41782. renderContextData.lastOcclusionObject = null;
  41783. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41784. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41785. renderContextData.occlusionQueryIndex = 0;
  41786. }
  41787. }
  41788. /**
  41789. * This method is executed at the end of a render call and finalizes work
  41790. * after draw calls.
  41791. *
  41792. * @param {RenderContext} renderContext - The render context.
  41793. */
  41794. finishRender( renderContext ) {
  41795. const { gl, state } = this;
  41796. const renderContextData = this.get( renderContext );
  41797. const previousContext = renderContextData.previousContext;
  41798. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41799. if ( occlusionQueryCount > 0 ) {
  41800. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41801. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41802. }
  41803. this.resolveOccludedAsync( renderContext );
  41804. }
  41805. const textures = renderContext.textures;
  41806. if ( textures !== null ) {
  41807. for ( let i = 0; i < textures.length; i ++ ) {
  41808. const texture = textures[ i ];
  41809. if ( texture.generateMipmaps ) {
  41810. this.generateMipmaps( texture );
  41811. }
  41812. }
  41813. }
  41814. this._currentContext = previousContext;
  41815. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41816. const renderTargetContextData = this.get( renderContext.renderTarget );
  41817. const { samples } = renderContext.renderTarget;
  41818. if ( samples > 0 && this._useMultisampledRTT( renderContext.renderTarget ) === false ) {
  41819. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41820. const mask = gl.COLOR_BUFFER_BIT;
  41821. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41822. const textures = renderContext.textures;
  41823. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41824. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41825. for ( let i = 0; i < textures.length; i ++ ) {
  41826. // TODO Add support for MRT
  41827. if ( renderContext.scissor ) {
  41828. const { x, y, width, height } = renderContext.scissorValue;
  41829. const viewY = renderContext.height - height - y;
  41830. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41831. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41832. } else {
  41833. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41834. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41835. }
  41836. }
  41837. }
  41838. }
  41839. if ( previousContext !== null ) {
  41840. this._setFramebuffer( previousContext );
  41841. if ( previousContext.viewport ) {
  41842. this.updateViewport( previousContext );
  41843. } else {
  41844. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41845. }
  41846. }
  41847. this.prepareTimestampBuffer( renderContext );
  41848. }
  41849. /**
  41850. * This method processes the result of occlusion queries and writes it
  41851. * into render context data.
  41852. *
  41853. * @async
  41854. * @param {RenderContext} renderContext - The render context.
  41855. */
  41856. resolveOccludedAsync( renderContext ) {
  41857. const renderContextData = this.get( renderContext );
  41858. // handle occlusion query results
  41859. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41860. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41861. const occluded = new WeakSet();
  41862. const { gl } = this;
  41863. renderContextData.currentOcclusionQueryObjects = null;
  41864. renderContextData.currentOcclusionQueries = null;
  41865. const check = () => {
  41866. let completed = 0;
  41867. // check all queries and requeue as appropriate
  41868. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41869. const query = currentOcclusionQueries[ i ];
  41870. if ( query === null ) continue;
  41871. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41872. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41873. currentOcclusionQueries[ i ] = null;
  41874. gl.deleteQuery( query );
  41875. completed ++;
  41876. }
  41877. }
  41878. if ( completed < currentOcclusionQueries.length ) {
  41879. requestAnimationFrame( check );
  41880. } else {
  41881. renderContextData.occluded = occluded;
  41882. }
  41883. };
  41884. check();
  41885. }
  41886. }
  41887. /**
  41888. * Returns `true` if the given 3D object is fully occluded by other
  41889. * 3D objects in the scene.
  41890. *
  41891. * @param {RenderContext} renderContext - The render context.
  41892. * @param {Object3D} object - The 3D object to test.
  41893. * @return {boolean} Whether the 3D object is fully occluded or not.
  41894. */
  41895. isOccluded( renderContext, object ) {
  41896. const renderContextData = this.get( renderContext );
  41897. return renderContextData.occluded && renderContextData.occluded.has( object );
  41898. }
  41899. /**
  41900. * Updates the viewport with the values from the given render context.
  41901. *
  41902. * @param {RenderContext} renderContext - The render context.
  41903. */
  41904. updateViewport( renderContext ) {
  41905. const { state } = this;
  41906. const { x, y, width, height } = renderContext.viewportValue;
  41907. state.viewport( x, renderContext.height - height - y, width, height );
  41908. }
  41909. /**
  41910. * Defines the scissor test.
  41911. *
  41912. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41913. */
  41914. setScissorTest( boolean ) {
  41915. const state = this.state;
  41916. state.setScissorTest( boolean );
  41917. }
  41918. /**
  41919. * Returns the clear color and alpha into a single
  41920. * color object.
  41921. *
  41922. * @return {Color4} The clear color.
  41923. */
  41924. getClearColor() {
  41925. const clearColor = super.getClearColor();
  41926. // Since the canvas is always created with alpha: true,
  41927. // WebGL must always premultiply the clear color.
  41928. clearColor.r *= clearColor.a;
  41929. clearColor.g *= clearColor.a;
  41930. clearColor.b *= clearColor.a;
  41931. return clearColor;
  41932. }
  41933. /**
  41934. * Performs a clear operation.
  41935. *
  41936. * @param {boolean} color - Whether the color buffer should be cleared or not.
  41937. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  41938. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  41939. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  41940. * @param {boolean} [setFrameBuffer=true] - TODO.
  41941. */
  41942. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41943. const { gl, renderer } = this;
  41944. if ( descriptor === null ) {
  41945. const clearColor = this.getClearColor();
  41946. descriptor = {
  41947. textures: null,
  41948. clearColorValue: clearColor
  41949. };
  41950. }
  41951. //
  41952. let clear = 0;
  41953. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41954. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41955. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41956. if ( clear !== 0 ) {
  41957. let clearColor;
  41958. if ( descriptor.clearColorValue ) {
  41959. clearColor = descriptor.clearColorValue;
  41960. } else {
  41961. clearColor = this.getClearColor();
  41962. }
  41963. const clearDepth = renderer.getClearDepth();
  41964. const clearStencil = renderer.getClearStencil();
  41965. if ( depth ) this.state.setDepthMask( true );
  41966. if ( descriptor.textures === null ) {
  41967. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41968. gl.clear( clear );
  41969. } else {
  41970. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41971. if ( color ) {
  41972. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41973. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41974. }
  41975. }
  41976. if ( depth && stencil ) {
  41977. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  41978. } else if ( depth ) {
  41979. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  41980. } else if ( stencil ) {
  41981. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  41982. }
  41983. }
  41984. }
  41985. }
  41986. /**
  41987. * This method is executed at the beginning of a compute call and
  41988. * prepares the state for upcoming compute tasks.
  41989. *
  41990. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41991. */
  41992. beginCompute( computeGroup ) {
  41993. const { state, gl } = this;
  41994. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41995. this.initTimestampQuery( computeGroup );
  41996. }
  41997. /**
  41998. * Executes a compute command for the given compute node.
  41999. *
  42000. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42001. * @param {Node} computeNode - The compute node.
  42002. * @param {Array<BindGroup>} bindings - The bindings.
  42003. * @param {ComputePipeline} pipeline - The compute pipeline.
  42004. */
  42005. compute( computeGroup, computeNode, bindings, pipeline ) {
  42006. const { state, gl } = this;
  42007. if ( this.discard === false ) {
  42008. // required here to handle async behaviour of render.compute()
  42009. gl.enable( gl.RASTERIZER_DISCARD );
  42010. this.discard = true;
  42011. }
  42012. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  42013. const vaoKey = this._getVaoKey( null, attributes );
  42014. const vaoGPU = this.vaoCache[ vaoKey ];
  42015. if ( vaoGPU === undefined ) {
  42016. this._createVao( null, attributes );
  42017. } else {
  42018. gl.bindVertexArray( vaoGPU );
  42019. }
  42020. state.useProgram( programGPU );
  42021. this._bindUniforms( bindings );
  42022. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  42023. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42024. gl.beginTransformFeedback( gl.POINTS );
  42025. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  42026. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  42027. } else {
  42028. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  42029. }
  42030. gl.endTransformFeedback();
  42031. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42032. // switch active buffers
  42033. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42034. const dualAttributeData = transformBuffers[ i ];
  42035. if ( dualAttributeData.pbo ) {
  42036. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  42037. }
  42038. dualAttributeData.switchBuffers();
  42039. }
  42040. }
  42041. /**
  42042. * This method is executed at the end of a compute call and
  42043. * finalizes work after compute tasks.
  42044. *
  42045. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42046. */
  42047. finishCompute( computeGroup ) {
  42048. const gl = this.gl;
  42049. this.discard = false;
  42050. gl.disable( gl.RASTERIZER_DISCARD );
  42051. this.prepareTimestampBuffer( computeGroup );
  42052. if ( this._currentContext ) {
  42053. this._setFramebuffer( this._currentContext );
  42054. }
  42055. }
  42056. /**
  42057. * Executes a draw command for the given render object.
  42058. *
  42059. * @param {RenderObject} renderObject - The render object to draw.
  42060. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42061. */
  42062. draw( renderObject/*, info*/ ) {
  42063. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  42064. const { programGPU } = this.get( pipeline );
  42065. const { gl, state } = this;
  42066. const contextData = this.get( context );
  42067. const drawParams = renderObject.getDrawParameters();
  42068. if ( drawParams === null ) return;
  42069. //
  42070. this._bindUniforms( renderObject.getBindings() );
  42071. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42072. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  42073. state.useProgram( programGPU );
  42074. //
  42075. const renderObjectData = this.get( renderObject );
  42076. let vaoGPU = renderObjectData.staticVao;
  42077. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  42078. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  42079. vaoGPU = this.vaoCache[ vaoKey ];
  42080. if ( vaoGPU === undefined ) {
  42081. let staticVao;
  42082. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  42083. if ( staticVao ) {
  42084. renderObjectData.staticVao = vaoGPU;
  42085. renderObjectData.geometryId = renderObject.geometry.id;
  42086. }
  42087. }
  42088. }
  42089. gl.bindVertexArray( vaoGPU );
  42090. //
  42091. const index = renderObject.getIndex();
  42092. //
  42093. const lastObject = contextData.lastOcclusionObject;
  42094. if ( lastObject !== object && lastObject !== undefined ) {
  42095. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42096. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42097. contextData.occlusionQueryIndex ++;
  42098. }
  42099. if ( object.occlusionTest === true ) {
  42100. const query = gl.createQuery();
  42101. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42102. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42103. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42104. }
  42105. contextData.lastOcclusionObject = object;
  42106. }
  42107. //
  42108. const renderer = this.bufferRenderer;
  42109. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42110. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42111. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42112. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42113. else {
  42114. if ( material.wireframe === true ) {
  42115. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42116. renderer.mode = gl.LINES;
  42117. } else {
  42118. renderer.mode = gl.TRIANGLES;
  42119. }
  42120. }
  42121. //
  42122. const { vertexCount, instanceCount } = drawParams;
  42123. let { firstVertex } = drawParams;
  42124. renderer.object = object;
  42125. if ( index !== null ) {
  42126. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42127. const indexData = this.get( index );
  42128. renderer.index = index.count;
  42129. renderer.type = indexData.type;
  42130. } else {
  42131. renderer.index = 0;
  42132. }
  42133. const draw = () => {
  42134. if ( object.isBatchedMesh ) {
  42135. if ( object._multiDrawInstances !== null ) {
  42136. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42137. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42138. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42139. } else {
  42140. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42141. }
  42142. } else if ( instanceCount > 1 ) {
  42143. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42144. } else {
  42145. renderer.render( firstVertex, vertexCount );
  42146. }
  42147. };
  42148. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  42149. const cameraData = this.get( renderObject.camera );
  42150. const cameras = renderObject.camera.cameras;
  42151. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  42152. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  42153. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  42154. const indexesGPU = [];
  42155. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42156. const bufferGPU = gl.createBuffer();
  42157. data[ 0 ] = i;
  42158. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42159. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  42160. indexesGPU.push( bufferGPU );
  42161. }
  42162. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  42163. }
  42164. const cameraIndexData = this.get( cameraIndex );
  42165. const pixelRatio = this.renderer.getPixelRatio();
  42166. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42167. const subCamera = cameras[ i ];
  42168. if ( object.layers.test( subCamera.layers ) ) {
  42169. const vp = subCamera.viewport;
  42170. const x = vp.x * pixelRatio;
  42171. const y = vp.y * pixelRatio;
  42172. const width = vp.width * pixelRatio;
  42173. const height = vp.height * pixelRatio;
  42174. state.viewport(
  42175. Math.floor( x ),
  42176. Math.floor( renderObject.context.height - height - y ),
  42177. Math.floor( width ),
  42178. Math.floor( height )
  42179. );
  42180. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  42181. draw();
  42182. }
  42183. }
  42184. } else {
  42185. draw();
  42186. }
  42187. //
  42188. gl.bindVertexArray( null );
  42189. }
  42190. /**
  42191. * Explain why always null is returned.
  42192. *
  42193. * @param {RenderObject} renderObject - The render object.
  42194. * @return {boolean} Whether the render pipeline requires an update or not.
  42195. */
  42196. needsRenderUpdate( /*renderObject*/ ) {
  42197. return false;
  42198. }
  42199. /**
  42200. * Explain why no cache key is computed.
  42201. *
  42202. * @param {RenderObject} renderObject - The render object.
  42203. * @return {string} The cache key.
  42204. */
  42205. getRenderCacheKey( /*renderObject*/ ) {
  42206. return '';
  42207. }
  42208. // textures
  42209. /**
  42210. * Creates a default texture for the given texture that can be used
  42211. * as a placeholder until the actual texture is ready for usage.
  42212. *
  42213. * @param {Texture} texture - The texture to create a default texture for.
  42214. */
  42215. createDefaultTexture( texture ) {
  42216. this.textureUtils.createDefaultTexture( texture );
  42217. }
  42218. /**
  42219. * Defines a texture on the GPU for the given texture object.
  42220. *
  42221. * @param {Texture} texture - The texture.
  42222. * @param {Object} [options={}] - Optional configuration parameter.
  42223. */
  42224. createTexture( texture, options ) {
  42225. this.textureUtils.createTexture( texture, options );
  42226. }
  42227. /**
  42228. * Uploads the updated texture data to the GPU.
  42229. *
  42230. * @param {Texture} texture - The texture.
  42231. * @param {Object} [options={}] - Optional configuration parameter.
  42232. */
  42233. updateTexture( texture, options ) {
  42234. this.textureUtils.updateTexture( texture, options );
  42235. }
  42236. /**
  42237. * Generates mipmaps for the given texture.
  42238. *
  42239. * @param {Texture} texture - The texture.
  42240. */
  42241. generateMipmaps( texture ) {
  42242. this.textureUtils.generateMipmaps( texture );
  42243. }
  42244. /**
  42245. * Destroys the GPU data for the given texture object.
  42246. *
  42247. * @param {Texture} texture - The texture.
  42248. */
  42249. destroyTexture( texture ) {
  42250. this.textureUtils.destroyTexture( texture );
  42251. }
  42252. /**
  42253. * Returns texture data as a typed array.
  42254. *
  42255. * @async
  42256. * @param {Texture} texture - The texture to copy.
  42257. * @param {number} x - The x coordinate of the copy origin.
  42258. * @param {number} y - The y coordinate of the copy origin.
  42259. * @param {number} width - The width of the copy.
  42260. * @param {number} height - The height of the copy.
  42261. * @param {number} faceIndex - The face index.
  42262. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42263. */
  42264. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42265. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42266. }
  42267. /**
  42268. * This method does nothing since WebGL 2 has no concept of samplers.
  42269. *
  42270. * @param {Texture} texture - The texture to create the sampler for.
  42271. */
  42272. createSampler( /*texture*/ ) {
  42273. //console.warn( 'Abstract class.' );
  42274. }
  42275. /**
  42276. * This method does nothing since WebGL 2 has no concept of samplers.
  42277. *
  42278. * @param {Texture} texture - The texture to destroy the sampler for.
  42279. */
  42280. destroySampler( /*texture*/ ) {}
  42281. // node builder
  42282. /**
  42283. * Returns a node builder for the given render object.
  42284. *
  42285. * @param {RenderObject} object - The render object.
  42286. * @param {Renderer} renderer - The renderer.
  42287. * @return {GLSLNodeBuilder} The node builder.
  42288. */
  42289. createNodeBuilder( object, renderer ) {
  42290. return new GLSLNodeBuilder( object, renderer );
  42291. }
  42292. // program
  42293. /**
  42294. * Creates a shader program from the given programmable stage.
  42295. *
  42296. * @param {ProgrammableStage} program - The programmable stage.
  42297. */
  42298. createProgram( program ) {
  42299. const gl = this.gl;
  42300. const { stage, code } = program;
  42301. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42302. gl.shaderSource( shader, code );
  42303. gl.compileShader( shader );
  42304. this.set( program, {
  42305. shaderGPU: shader
  42306. } );
  42307. }
  42308. /**
  42309. * Destroys the shader program of the given programmable stage.
  42310. *
  42311. * @param {ProgrammableStage} program - The programmable stage.
  42312. */
  42313. destroyProgram( program ) {
  42314. this.delete( program );
  42315. }
  42316. /**
  42317. * Creates a render pipeline for the given render object.
  42318. *
  42319. * @param {RenderObject} renderObject - The render object.
  42320. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42321. */
  42322. createRenderPipeline( renderObject, promises ) {
  42323. const gl = this.gl;
  42324. const pipeline = renderObject.pipeline;
  42325. // Program
  42326. const { fragmentProgram, vertexProgram } = pipeline;
  42327. const programGPU = gl.createProgram();
  42328. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42329. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42330. gl.attachShader( programGPU, fragmentShader );
  42331. gl.attachShader( programGPU, vertexShader );
  42332. gl.linkProgram( programGPU );
  42333. this.set( pipeline, {
  42334. programGPU,
  42335. fragmentShader,
  42336. vertexShader
  42337. } );
  42338. if ( promises !== null && this.parallel ) {
  42339. const p = new Promise( ( resolve /*, reject*/ ) => {
  42340. const parallel = this.parallel;
  42341. const checkStatus = () => {
  42342. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42343. this._completeCompile( renderObject, pipeline );
  42344. resolve();
  42345. } else {
  42346. requestAnimationFrame( checkStatus );
  42347. }
  42348. };
  42349. checkStatus();
  42350. } );
  42351. promises.push( p );
  42352. return;
  42353. }
  42354. this._completeCompile( renderObject, pipeline );
  42355. }
  42356. /**
  42357. * Formats the source code of error messages.
  42358. *
  42359. * @private
  42360. * @param {string} string - The code.
  42361. * @param {number} errorLine - The error line.
  42362. * @return {string} The formatted code.
  42363. */
  42364. _handleSource( string, errorLine ) {
  42365. const lines = string.split( '\n' );
  42366. const lines2 = [];
  42367. const from = Math.max( errorLine - 6, 0 );
  42368. const to = Math.min( errorLine + 6, lines.length );
  42369. for ( let i = from; i < to; i ++ ) {
  42370. const line = i + 1;
  42371. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  42372. }
  42373. return lines2.join( '\n' );
  42374. }
  42375. /**
  42376. * Gets the shader compilation errors from the info log.
  42377. *
  42378. * @private
  42379. * @param {WebGL2RenderingContext} gl - The rendering context.
  42380. * @param {WebGLShader} shader - The WebGL shader object.
  42381. * @param {string} type - The shader type.
  42382. * @return {string} The shader errors.
  42383. */
  42384. _getShaderErrors( gl, shader, type ) {
  42385. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  42386. const errors = gl.getShaderInfoLog( shader ).trim();
  42387. if ( status && errors === '' ) return '';
  42388. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  42389. if ( errorMatches ) {
  42390. const errorLine = parseInt( errorMatches[ 1 ] );
  42391. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  42392. } else {
  42393. return errors;
  42394. }
  42395. }
  42396. /**
  42397. * Logs shader compilation errors.
  42398. *
  42399. * @private
  42400. * @param {WebGLProgram} programGPU - The WebGL program.
  42401. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  42402. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  42403. */
  42404. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  42405. if ( this.renderer.debug.checkShaderErrors ) {
  42406. const gl = this.gl;
  42407. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  42408. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42409. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  42410. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  42411. } else {
  42412. // default error reporting
  42413. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  42414. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  42415. console.error(
  42416. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  42417. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  42418. 'Program Info Log: ' + programLog + '\n' +
  42419. vertexErrors + '\n' +
  42420. fragmentErrors
  42421. );
  42422. }
  42423. } else if ( programLog !== '' ) {
  42424. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  42425. }
  42426. }
  42427. }
  42428. /**
  42429. * Completes the shader program setup for the given render object.
  42430. *
  42431. * @private
  42432. * @param {RenderObject} renderObject - The render object.
  42433. * @param {RenderPipeline} pipeline - The render pipeline.
  42434. */
  42435. _completeCompile( renderObject, pipeline ) {
  42436. const { state, gl } = this;
  42437. const pipelineData = this.get( pipeline );
  42438. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  42439. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42440. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42441. }
  42442. state.useProgram( programGPU );
  42443. // Bindings
  42444. const bindings = renderObject.getBindings();
  42445. this._setupBindings( bindings, programGPU );
  42446. //
  42447. this.set( pipeline, {
  42448. programGPU
  42449. } );
  42450. }
  42451. /**
  42452. * Creates a compute pipeline for the given compute node.
  42453. *
  42454. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42455. * @param {Array<BindGroup>} bindings - The bindings.
  42456. */
  42457. createComputePipeline( computePipeline, bindings ) {
  42458. const { state, gl } = this;
  42459. // Program
  42460. const fragmentProgram = {
  42461. stage: 'fragment',
  42462. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  42463. };
  42464. this.createProgram( fragmentProgram );
  42465. const { computeProgram } = computePipeline;
  42466. const programGPU = gl.createProgram();
  42467. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42468. const vertexShader = this.get( computeProgram ).shaderGPU;
  42469. const transforms = computeProgram.transforms;
  42470. const transformVaryingNames = [];
  42471. const transformAttributeNodes = [];
  42472. for ( let i = 0; i < transforms.length; i ++ ) {
  42473. const transform = transforms[ i ];
  42474. transformVaryingNames.push( transform.varyingName );
  42475. transformAttributeNodes.push( transform.attributeNode );
  42476. }
  42477. gl.attachShader( programGPU, fragmentShader );
  42478. gl.attachShader( programGPU, vertexShader );
  42479. gl.transformFeedbackVaryings(
  42480. programGPU,
  42481. transformVaryingNames,
  42482. gl.SEPARATE_ATTRIBS
  42483. );
  42484. gl.linkProgram( programGPU );
  42485. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42486. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42487. }
  42488. state.useProgram( programGPU );
  42489. // Bindings
  42490. this._setupBindings( bindings, programGPU );
  42491. const attributeNodes = computeProgram.attributes;
  42492. const attributes = [];
  42493. const transformBuffers = [];
  42494. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  42495. const attribute = attributeNodes[ i ].node.attribute;
  42496. attributes.push( attribute );
  42497. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42498. }
  42499. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  42500. const attribute = transformAttributeNodes[ i ].attribute;
  42501. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42502. const attributeData = this.get( attribute );
  42503. transformBuffers.push( attributeData );
  42504. }
  42505. //
  42506. this.set( computePipeline, {
  42507. programGPU,
  42508. transformBuffers,
  42509. attributes
  42510. } );
  42511. }
  42512. /**
  42513. * Creates bindings from the given bind group definition.
  42514. *
  42515. * @param {BindGroup} bindGroup - The bind group.
  42516. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42517. * @param {number} cacheIndex - The cache index.
  42518. * @param {number} version - The version.
  42519. */
  42520. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  42521. if ( this._knownBindings.has( bindings ) === false ) {
  42522. this._knownBindings.add( bindings );
  42523. let uniformBuffers = 0;
  42524. let textures = 0;
  42525. for ( const bindGroup of bindings ) {
  42526. this.set( bindGroup, {
  42527. textures: textures,
  42528. uniformBuffers: uniformBuffers
  42529. } );
  42530. for ( const binding of bindGroup.bindings ) {
  42531. if ( binding.isUniformBuffer ) uniformBuffers ++;
  42532. if ( binding.isSampledTexture ) textures ++;
  42533. }
  42534. }
  42535. }
  42536. this.updateBindings( bindGroup, bindings );
  42537. }
  42538. /**
  42539. * Updates the given bind group definition.
  42540. *
  42541. * @param {BindGroup} bindGroup - The bind group.
  42542. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42543. * @param {number} cacheIndex - The cache index.
  42544. * @param {number} version - The version.
  42545. */
  42546. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  42547. const { gl } = this;
  42548. const bindGroupData = this.get( bindGroup );
  42549. let i = bindGroupData.uniformBuffers;
  42550. let t = bindGroupData.textures;
  42551. for ( const binding of bindGroup.bindings ) {
  42552. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42553. const data = binding.buffer;
  42554. const bufferGPU = gl.createBuffer();
  42555. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42556. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42557. this.set( binding, {
  42558. index: i ++,
  42559. bufferGPU
  42560. } );
  42561. } else if ( binding.isSampledTexture ) {
  42562. const { textureGPU, glTextureType } = this.get( binding.texture );
  42563. this.set( binding, {
  42564. index: t ++,
  42565. textureGPU,
  42566. glTextureType
  42567. } );
  42568. }
  42569. }
  42570. }
  42571. /**
  42572. * Updates a buffer binding.
  42573. *
  42574. * @param {Buffer} binding - The buffer binding to update.
  42575. */
  42576. updateBinding( binding ) {
  42577. const gl = this.gl;
  42578. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42579. const bindingData = this.get( binding );
  42580. const bufferGPU = bindingData.bufferGPU;
  42581. const data = binding.buffer;
  42582. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42583. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42584. }
  42585. }
  42586. // attributes
  42587. /**
  42588. * Creates the GPU buffer of an indexed shader attribute.
  42589. *
  42590. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42591. */
  42592. createIndexAttribute( attribute ) {
  42593. const gl = this.gl;
  42594. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  42595. }
  42596. /**
  42597. * Creates the GPU buffer of a shader attribute.
  42598. *
  42599. * @param {BufferAttribute} attribute - The buffer attribute.
  42600. */
  42601. createAttribute( attribute ) {
  42602. if ( this.has( attribute ) ) return;
  42603. const gl = this.gl;
  42604. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42605. }
  42606. /**
  42607. * Creates the GPU buffer of a storage attribute.
  42608. *
  42609. * @param {BufferAttribute} attribute - The buffer attribute.
  42610. */
  42611. createStorageAttribute( attribute ) {
  42612. if ( this.has( attribute ) ) return;
  42613. const gl = this.gl;
  42614. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42615. }
  42616. /**
  42617. * Updates the GPU buffer of a shader attribute.
  42618. *
  42619. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42620. */
  42621. updateAttribute( attribute ) {
  42622. this.attributeUtils.updateAttribute( attribute );
  42623. }
  42624. /**
  42625. * Destroys the GPU buffer of a shader attribute.
  42626. *
  42627. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42628. */
  42629. destroyAttribute( attribute ) {
  42630. this.attributeUtils.destroyAttribute( attribute );
  42631. }
  42632. /**
  42633. * Checks if the given feature is supported by the backend.
  42634. *
  42635. * @param {string} name - The feature's name.
  42636. * @return {boolean} Whether the feature is supported or not.
  42637. */
  42638. hasFeature( name ) {
  42639. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  42640. const extensions = this.extensions;
  42641. for ( let i = 0; i < keysMatching.length; i ++ ) {
  42642. if ( extensions.has( keysMatching[ i ] ) ) return true;
  42643. }
  42644. return false;
  42645. }
  42646. /**
  42647. * Returns the maximum anisotropy texture filtering value.
  42648. *
  42649. * @return {number} The maximum anisotropy texture filtering value.
  42650. */
  42651. getMaxAnisotropy() {
  42652. return this.capabilities.getMaxAnisotropy();
  42653. }
  42654. /**
  42655. * Copies data of the given source texture to the given destination texture.
  42656. *
  42657. * @param {Texture} srcTexture - The source texture.
  42658. * @param {Texture} dstTexture - The destination texture.
  42659. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  42660. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42661. * @param {number} [level=0] - The mip level to copy.
  42662. */
  42663. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42664. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  42665. }
  42666. /**
  42667. * Copies the current bound framebuffer to the given texture.
  42668. *
  42669. * @param {Texture} texture - The destination texture.
  42670. * @param {RenderContext} renderContext - The render context.
  42671. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42672. */
  42673. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42674. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  42675. }
  42676. /**
  42677. * Configures the active framebuffer from the given render context.
  42678. *
  42679. * @private
  42680. * @param {RenderContext} descriptor - The render context.
  42681. */
  42682. _setFramebuffer( descriptor ) {
  42683. const { gl, state } = this;
  42684. let currentFrameBuffer = null;
  42685. if ( descriptor.textures !== null ) {
  42686. const renderTarget = descriptor.renderTarget;
  42687. const renderTargetContextData = this.get( renderTarget );
  42688. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  42689. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  42690. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  42691. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  42692. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  42693. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  42694. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  42695. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  42696. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42697. const useMultisampledRTT = this._useMultisampledRTT( renderTarget );
  42698. const cacheKey = getCacheKey( descriptor );
  42699. let fb;
  42700. if ( isCube ) {
  42701. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  42702. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  42703. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  42704. fb = this._xrFamebuffer;
  42705. } else {
  42706. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  42707. fb = renderTargetContextData.framebuffers[ cacheKey ];
  42708. }
  42709. if ( fb === undefined ) {
  42710. fb = gl.createFramebuffer();
  42711. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42712. const textures = descriptor.textures;
  42713. if ( isCube ) {
  42714. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  42715. const { textureGPU } = this.get( textures[ 0 ] );
  42716. const cubeFace = this.renderer._activeCubeFace;
  42717. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  42718. } else {
  42719. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  42720. for ( let i = 0; i < textures.length; i ++ ) {
  42721. const texture = textures[ i ];
  42722. const textureData = this.get( texture );
  42723. textureData.renderTarget = descriptor.renderTarget;
  42724. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42725. const attachment = gl.COLOR_ATTACHMENT0 + i;
  42726. if ( isRenderTarget3D || isRenderTargetArray ) {
  42727. const layer = this.renderer._activeCubeFace;
  42728. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  42729. } else {
  42730. if ( useMultisampledRTT ) {
  42731. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42732. } else {
  42733. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42734. }
  42735. }
  42736. }
  42737. state.drawBuffers( descriptor, fb );
  42738. }
  42739. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  42740. const renderbuffer = gl.createRenderbuffer();
  42741. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  42742. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  42743. } else {
  42744. if ( descriptor.depthTexture !== null ) {
  42745. const textureData = this.get( descriptor.depthTexture );
  42746. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42747. textureData.renderTarget = descriptor.renderTarget;
  42748. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42749. if ( useMultisampledRTT ) {
  42750. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42751. } else {
  42752. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42753. }
  42754. }
  42755. }
  42756. } else {
  42757. // rebind external XR textures
  42758. if ( isXRRenderTarget && hasExternalTextures ) {
  42759. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42760. // rebind color
  42761. const textureData = this.get( descriptor.textures[ 0 ] );
  42762. if ( useMultisampledRTT ) {
  42763. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42764. } else {
  42765. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42766. }
  42767. // rebind depth
  42768. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42769. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  42770. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  42771. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42772. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  42773. } else {
  42774. const textureData = this.get( descriptor.depthTexture );
  42775. if ( useMultisampledRTT ) {
  42776. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42777. } else {
  42778. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42779. }
  42780. }
  42781. }
  42782. }
  42783. if ( samples > 0 && useMultisampledRTT === false ) {
  42784. if ( msaaFb === undefined ) {
  42785. const invalidationArray = [];
  42786. msaaFb = gl.createFramebuffer();
  42787. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  42788. const msaaRenderbuffers = [];
  42789. const textures = descriptor.textures;
  42790. for ( let i = 0; i < textures.length; i ++ ) {
  42791. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42792. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42793. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42794. if ( depthBuffer ) {
  42795. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42796. invalidationArray.push( depthStyle );
  42797. }
  42798. const texture = descriptor.textures[ i ];
  42799. const textureData = this.get( texture );
  42800. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42801. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42802. }
  42803. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42804. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42805. if ( depthRenderbuffer === undefined ) {
  42806. depthRenderbuffer = gl.createRenderbuffer();
  42807. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  42808. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42809. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42810. invalidationArray.push( depthStyle );
  42811. }
  42812. renderTargetContextData.invalidationArray = invalidationArray;
  42813. }
  42814. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42815. } else {
  42816. currentFrameBuffer = fb;
  42817. }
  42818. }
  42819. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42820. }
  42821. /**
  42822. * Computes the VAO key for the given index and attributes.
  42823. *
  42824. * @private
  42825. * @param {?BufferAttribute} index - The index. `null` for non-indexed geometries.
  42826. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42827. * @return {string} The VAO key.
  42828. */
  42829. _getVaoKey( index, attributes ) {
  42830. let key = '';
  42831. if ( index !== null ) {
  42832. const indexData = this.get( index );
  42833. key += ':' + indexData.id;
  42834. }
  42835. for ( let i = 0; i < attributes.length; i ++ ) {
  42836. const attributeData = this.get( attributes[ i ] );
  42837. key += ':' + attributeData.id;
  42838. }
  42839. return key;
  42840. }
  42841. /**
  42842. * Creates a VAO from the index and attributes.
  42843. *
  42844. * @private
  42845. * @param {?BufferAttribute} index - The index. `null` for non-indexed geometries.
  42846. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42847. * @return {Object} The VAO data.
  42848. */
  42849. _createVao( index, attributes ) {
  42850. const { gl } = this;
  42851. const vaoGPU = gl.createVertexArray();
  42852. let key = '';
  42853. let staticVao = true;
  42854. gl.bindVertexArray( vaoGPU );
  42855. if ( index !== null ) {
  42856. const indexData = this.get( index );
  42857. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42858. key += ':' + indexData.id;
  42859. }
  42860. for ( let i = 0; i < attributes.length; i ++ ) {
  42861. const attribute = attributes[ i ];
  42862. const attributeData = this.get( attribute );
  42863. key += ':' + attributeData.id;
  42864. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42865. gl.enableVertexAttribArray( i );
  42866. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42867. let stride, offset;
  42868. if ( attribute.isInterleavedBufferAttribute === true ) {
  42869. stride = attribute.data.stride * attributeData.bytesPerElement;
  42870. offset = attribute.offset * attributeData.bytesPerElement;
  42871. } else {
  42872. stride = 0;
  42873. offset = 0;
  42874. }
  42875. if ( attributeData.isInteger ) {
  42876. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42877. } else {
  42878. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42879. }
  42880. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42881. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42882. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42883. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42884. }
  42885. }
  42886. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42887. this.vaoCache[ key ] = vaoGPU;
  42888. return { vaoGPU, staticVao };
  42889. }
  42890. /**
  42891. * Creates a transform feedback from the given transform buffers.
  42892. *
  42893. * @private
  42894. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  42895. * @return {WebGLTransformFeedback} The transform feedback.
  42896. */
  42897. _getTransformFeedback( transformBuffers ) {
  42898. let key = '';
  42899. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42900. key += ':' + transformBuffers[ i ].id;
  42901. }
  42902. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42903. if ( transformFeedbackGPU !== undefined ) {
  42904. return transformFeedbackGPU;
  42905. }
  42906. const { gl } = this;
  42907. transformFeedbackGPU = gl.createTransformFeedback();
  42908. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42909. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42910. const attributeData = transformBuffers[ i ];
  42911. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42912. }
  42913. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42914. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42915. return transformFeedbackGPU;
  42916. }
  42917. /**
  42918. * Setups the given bindings.
  42919. *
  42920. * @private
  42921. * @param {Array<BindGroup>} bindings - The bindings.
  42922. * @param {WebGLProgram} programGPU - The WebGL program.
  42923. */
  42924. _setupBindings( bindings, programGPU ) {
  42925. const gl = this.gl;
  42926. for ( const bindGroup of bindings ) {
  42927. for ( const binding of bindGroup.bindings ) {
  42928. const bindingData = this.get( binding );
  42929. const index = bindingData.index;
  42930. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42931. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42932. gl.uniformBlockBinding( programGPU, location, index );
  42933. } else if ( binding.isSampledTexture ) {
  42934. const location = gl.getUniformLocation( programGPU, binding.name );
  42935. gl.uniform1i( location, index );
  42936. }
  42937. }
  42938. }
  42939. }
  42940. /**
  42941. * Binds the given uniforms.
  42942. *
  42943. * @private
  42944. * @param {Array<BindGroup>} bindings - The bindings.
  42945. */
  42946. _bindUniforms( bindings ) {
  42947. const { gl, state } = this;
  42948. for ( const bindGroup of bindings ) {
  42949. for ( const binding of bindGroup.bindings ) {
  42950. const bindingData = this.get( binding );
  42951. const index = bindingData.index;
  42952. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42953. // TODO USE bindBufferRange to group multiple uniform buffers
  42954. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42955. } else if ( binding.isSampledTexture ) {
  42956. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42957. }
  42958. }
  42959. }
  42960. }
  42961. /**
  42962. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  42963. * should be used when MSAA is enabled.
  42964. *
  42965. * @private
  42966. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  42967. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  42968. */
  42969. _useMultisampledRTT( renderTarget ) {
  42970. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  42971. }
  42972. /**
  42973. * Frees internal resources.
  42974. */
  42975. dispose() {
  42976. const extension = this.extensions.get( 'WEBGL_lose_context' );
  42977. if ( extension ) extension.loseContext();
  42978. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  42979. }
  42980. }
  42981. const GPUPrimitiveTopology = {
  42982. PointList: 'point-list',
  42983. LineList: 'line-list',
  42984. LineStrip: 'line-strip',
  42985. TriangleList: 'triangle-list',
  42986. TriangleStrip: 'triangle-strip',
  42987. };
  42988. const GPUCompareFunction = {
  42989. Never: 'never',
  42990. Less: 'less',
  42991. Equal: 'equal',
  42992. LessEqual: 'less-equal',
  42993. Greater: 'greater',
  42994. NotEqual: 'not-equal',
  42995. GreaterEqual: 'greater-equal',
  42996. Always: 'always'
  42997. };
  42998. const GPUStoreOp = {
  42999. Store: 'store'};
  43000. const GPULoadOp = {
  43001. Load: 'load',
  43002. Clear: 'clear'
  43003. };
  43004. const GPUFrontFace = {
  43005. CCW: 'ccw'};
  43006. const GPUCullMode = {
  43007. None: 'none',
  43008. Front: 'front',
  43009. Back: 'back'
  43010. };
  43011. const GPUIndexFormat = {
  43012. Uint16: 'uint16',
  43013. Uint32: 'uint32'
  43014. };
  43015. const GPUTextureFormat = {
  43016. // 8-bit formats
  43017. R8Unorm: 'r8unorm',
  43018. R8Snorm: 'r8snorm',
  43019. R8Uint: 'r8uint',
  43020. R8Sint: 'r8sint',
  43021. // 16-bit formats
  43022. R16Uint: 'r16uint',
  43023. R16Sint: 'r16sint',
  43024. R16Float: 'r16float',
  43025. RG8Unorm: 'rg8unorm',
  43026. RG8Snorm: 'rg8snorm',
  43027. RG8Uint: 'rg8uint',
  43028. RG8Sint: 'rg8sint',
  43029. // 32-bit formats
  43030. R32Uint: 'r32uint',
  43031. R32Sint: 'r32sint',
  43032. R32Float: 'r32float',
  43033. RG16Uint: 'rg16uint',
  43034. RG16Sint: 'rg16sint',
  43035. RG16Float: 'rg16float',
  43036. RGBA8Unorm: 'rgba8unorm',
  43037. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  43038. RGBA8Snorm: 'rgba8snorm',
  43039. RGBA8Uint: 'rgba8uint',
  43040. RGBA8Sint: 'rgba8sint',
  43041. BGRA8Unorm: 'bgra8unorm',
  43042. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  43043. // Packed 32-bit formats
  43044. RGB9E5UFloat: 'rgb9e5ufloat',
  43045. RGB10A2Unorm: 'rgb10a2unorm',
  43046. // 64-bit formats
  43047. RG32Uint: 'rg32uint',
  43048. RG32Sint: 'rg32sint',
  43049. RG32Float: 'rg32float',
  43050. RGBA16Uint: 'rgba16uint',
  43051. RGBA16Sint: 'rgba16sint',
  43052. RGBA16Float: 'rgba16float',
  43053. // 128-bit formats
  43054. RGBA32Uint: 'rgba32uint',
  43055. RGBA32Sint: 'rgba32sint',
  43056. RGBA32Float: 'rgba32float',
  43057. Depth16Unorm: 'depth16unorm',
  43058. Depth24Plus: 'depth24plus',
  43059. Depth24PlusStencil8: 'depth24plus-stencil8',
  43060. Depth32Float: 'depth32float',
  43061. // 'depth32float-stencil8' extension
  43062. Depth32FloatStencil8: 'depth32float-stencil8',
  43063. // BC compressed formats usable if 'texture-compression-bc' is both
  43064. // supported by the device/user agent and enabled in requestDevice.
  43065. BC1RGBAUnorm: 'bc1-rgba-unorm',
  43066. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  43067. BC2RGBAUnorm: 'bc2-rgba-unorm',
  43068. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  43069. BC3RGBAUnorm: 'bc3-rgba-unorm',
  43070. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  43071. BC4RUnorm: 'bc4-r-unorm',
  43072. BC5RGUnorm: 'bc5-rg-unorm',
  43073. BC5RGSnorm: 'bc5-rg-snorm',
  43074. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  43075. BC6HRGBFloat: 'bc6h-rgb-float',
  43076. BC7RGBAUnorm: 'bc7-rgba-unorm',
  43077. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  43078. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  43079. // supported by the device/user agent and enabled in requestDevice.
  43080. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  43081. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  43082. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  43083. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  43084. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  43085. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  43086. EACR11Unorm: 'eac-r11unorm',
  43087. EACR11Snorm: 'eac-r11snorm',
  43088. EACRG11Unorm: 'eac-rg11unorm',
  43089. EACRG11Snorm: 'eac-rg11snorm',
  43090. // ASTC compressed formats usable if 'texture-compression-astc' is both
  43091. // supported by the device/user agent and enabled in requestDevice.
  43092. ASTC4x4Unorm: 'astc-4x4-unorm',
  43093. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  43094. ASTC5x4Unorm: 'astc-5x4-unorm',
  43095. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  43096. ASTC5x5Unorm: 'astc-5x5-unorm',
  43097. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  43098. ASTC6x5Unorm: 'astc-6x5-unorm',
  43099. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  43100. ASTC6x6Unorm: 'astc-6x6-unorm',
  43101. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  43102. ASTC8x5Unorm: 'astc-8x5-unorm',
  43103. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  43104. ASTC8x6Unorm: 'astc-8x6-unorm',
  43105. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  43106. ASTC8x8Unorm: 'astc-8x8-unorm',
  43107. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  43108. ASTC10x5Unorm: 'astc-10x5-unorm',
  43109. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  43110. ASTC10x6Unorm: 'astc-10x6-unorm',
  43111. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  43112. ASTC10x8Unorm: 'astc-10x8-unorm',
  43113. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  43114. ASTC10x10Unorm: 'astc-10x10-unorm',
  43115. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  43116. ASTC12x10Unorm: 'astc-12x10-unorm',
  43117. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  43118. ASTC12x12Unorm: 'astc-12x12-unorm',
  43119. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  43120. };
  43121. const GPUAddressMode = {
  43122. ClampToEdge: 'clamp-to-edge',
  43123. Repeat: 'repeat',
  43124. MirrorRepeat: 'mirror-repeat'
  43125. };
  43126. const GPUFilterMode = {
  43127. Linear: 'linear',
  43128. Nearest: 'nearest'
  43129. };
  43130. const GPUBlendFactor = {
  43131. Zero: 'zero',
  43132. One: 'one',
  43133. Src: 'src',
  43134. OneMinusSrc: 'one-minus-src',
  43135. SrcAlpha: 'src-alpha',
  43136. OneMinusSrcAlpha: 'one-minus-src-alpha',
  43137. Dst: 'dst',
  43138. OneMinusDstColor: 'one-minus-dst',
  43139. DstAlpha: 'dst-alpha',
  43140. OneMinusDstAlpha: 'one-minus-dst-alpha',
  43141. SrcAlphaSaturated: 'src-alpha-saturated',
  43142. Constant: 'constant',
  43143. OneMinusConstant: 'one-minus-constant'
  43144. };
  43145. const GPUBlendOperation = {
  43146. Add: 'add',
  43147. Subtract: 'subtract',
  43148. ReverseSubtract: 'reverse-subtract',
  43149. Min: 'min',
  43150. Max: 'max'
  43151. };
  43152. const GPUColorWriteFlags = {
  43153. None: 0,
  43154. All: 0xF
  43155. };
  43156. const GPUStencilOperation = {
  43157. Keep: 'keep',
  43158. Zero: 'zero',
  43159. Replace: 'replace',
  43160. Invert: 'invert',
  43161. IncrementClamp: 'increment-clamp',
  43162. DecrementClamp: 'decrement-clamp',
  43163. IncrementWrap: 'increment-wrap',
  43164. DecrementWrap: 'decrement-wrap'
  43165. };
  43166. const GPUBufferBindingType = {
  43167. Storage: 'storage',
  43168. ReadOnlyStorage: 'read-only-storage'
  43169. };
  43170. const GPUStorageTextureAccess = {
  43171. WriteOnly: 'write-only',
  43172. ReadOnly: 'read-only',
  43173. ReadWrite: 'read-write',
  43174. };
  43175. const GPUTextureSampleType = {
  43176. Float: 'float',
  43177. UnfilterableFloat: 'unfilterable-float',
  43178. Depth: 'depth',
  43179. SInt: 'sint',
  43180. UInt: 'uint'
  43181. };
  43182. const GPUTextureDimension = {
  43183. TwoD: '2d',
  43184. ThreeD: '3d'
  43185. };
  43186. const GPUTextureViewDimension = {
  43187. TwoD: '2d',
  43188. TwoDArray: '2d-array',
  43189. Cube: 'cube',
  43190. ThreeD: '3d'
  43191. };
  43192. const GPUTextureAspect = {
  43193. All: 'all'};
  43194. const GPUInputStepMode = {
  43195. Vertex: 'vertex',
  43196. Instance: 'instance'
  43197. };
  43198. const GPUFeatureName = {
  43199. DepthClipControl: 'depth-clip-control',
  43200. Depth32FloatStencil8: 'depth32float-stencil8',
  43201. TextureCompressionBC: 'texture-compression-bc',
  43202. TextureCompressionETC2: 'texture-compression-etc2',
  43203. TextureCompressionASTC: 'texture-compression-astc',
  43204. TimestampQuery: 'timestamp-query',
  43205. IndirectFirstInstance: 'indirect-first-instance',
  43206. ShaderF16: 'shader-f16',
  43207. RG11B10UFloat: 'rg11b10ufloat-renderable',
  43208. BGRA8UNormStorage: 'bgra8unorm-storage',
  43209. Float32Filterable: 'float32-filterable',
  43210. ClipDistances: 'clip-distances',
  43211. DualSourceBlending: 'dual-source-blending',
  43212. Subgroups: 'subgroups'
  43213. };
  43214. /**
  43215. * Represents a sampler binding type.
  43216. *
  43217. * @private
  43218. * @augments Binding
  43219. */
  43220. class Sampler extends Binding {
  43221. /**
  43222. * Constructs a new sampler.
  43223. *
  43224. * @param {string} name - The samplers's name.
  43225. * @param {?Texture} texture - The texture this binding is referring to.
  43226. */
  43227. constructor( name, texture ) {
  43228. super( name );
  43229. /**
  43230. * The texture the sampler is referring to.
  43231. *
  43232. * @type {?Texture}
  43233. */
  43234. this.texture = texture;
  43235. /**
  43236. * The binding's version.
  43237. *
  43238. * @type {number}
  43239. */
  43240. this.version = texture ? texture.version : 0;
  43241. /**
  43242. * This flag can be used for type testing.
  43243. *
  43244. * @type {boolean}
  43245. * @readonly
  43246. * @default true
  43247. */
  43248. this.isSampler = true;
  43249. }
  43250. }
  43251. /**
  43252. * A special form of sampler binding type.
  43253. * It's texture value is managed by a node object.
  43254. *
  43255. * @private
  43256. * @augments Sampler
  43257. */
  43258. class NodeSampler extends Sampler {
  43259. /**
  43260. * Constructs a new node-based sampler.
  43261. *
  43262. * @param {string} name - The samplers's name.
  43263. * @param {TextureNode} textureNode - The texture node.
  43264. * @param {UniformGroupNode} groupNode - The uniform group node.
  43265. */
  43266. constructor( name, textureNode, groupNode ) {
  43267. super( name, textureNode ? textureNode.value : null );
  43268. /**
  43269. * The texture node.
  43270. *
  43271. * @type {TextureNode}
  43272. */
  43273. this.textureNode = textureNode;
  43274. /**
  43275. * The uniform group node.
  43276. *
  43277. * @type {UniformGroupNode}
  43278. */
  43279. this.groupNode = groupNode;
  43280. }
  43281. /**
  43282. * Updates the texture value of this sampler.
  43283. */
  43284. update() {
  43285. this.texture = this.textureNode.value;
  43286. }
  43287. }
  43288. /**
  43289. * Represents a storage buffer binding type.
  43290. *
  43291. * @private
  43292. * @augments Buffer
  43293. */
  43294. class StorageBuffer extends Buffer {
  43295. /**
  43296. * Constructs a new uniform buffer.
  43297. *
  43298. * @param {string} name - The buffer's name.
  43299. * @param {BufferAttribute} attribute - The buffer attribute.
  43300. */
  43301. constructor( name, attribute ) {
  43302. super( name, attribute ? attribute.array : null );
  43303. /**
  43304. * This flag can be used for type testing.
  43305. *
  43306. * @type {BufferAttribute}
  43307. */
  43308. this.attribute = attribute;
  43309. /**
  43310. * This flag can be used for type testing.
  43311. *
  43312. * @type {boolean}
  43313. * @readonly
  43314. * @default true
  43315. */
  43316. this.isStorageBuffer = true;
  43317. }
  43318. }
  43319. let _id = 0;
  43320. /**
  43321. * A special form of storage buffer binding type.
  43322. * It's buffer value is managed by a node object.
  43323. *
  43324. * @private
  43325. * @augments StorageBuffer
  43326. */
  43327. class NodeStorageBuffer extends StorageBuffer {
  43328. /**
  43329. * Constructs a new node-based storage buffer.
  43330. *
  43331. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  43332. * @param {UniformGroupNode} groupNode - The uniform group node.
  43333. */
  43334. constructor( nodeUniform, groupNode ) {
  43335. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  43336. /**
  43337. * The node uniform.
  43338. *
  43339. * @type {StorageBufferNode}
  43340. */
  43341. this.nodeUniform = nodeUniform;
  43342. /**
  43343. * The access type.
  43344. *
  43345. * @type {string}
  43346. */
  43347. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  43348. /**
  43349. * The uniform group node.
  43350. *
  43351. * @type {UniformGroupNode}
  43352. */
  43353. this.groupNode = groupNode;
  43354. }
  43355. /**
  43356. * The storage buffer.
  43357. *
  43358. * @type {BufferAttribute}
  43359. */
  43360. get buffer() {
  43361. return this.nodeUniform.value;
  43362. }
  43363. }
  43364. /**
  43365. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  43366. *
  43367. * @private
  43368. */
  43369. class WebGPUTexturePassUtils extends DataMap {
  43370. /**
  43371. * Constructs a new utility object.
  43372. *
  43373. * @param {GPUDevice} device - The WebGPU device.
  43374. */
  43375. constructor( device ) {
  43376. super();
  43377. /**
  43378. * The WebGPU device.
  43379. *
  43380. * @type {GPUDevice}
  43381. */
  43382. this.device = device;
  43383. const mipmapVertexSource = `
  43384. struct VarysStruct {
  43385. @builtin( position ) Position: vec4<f32>,
  43386. @location( 0 ) vTex : vec2<f32>
  43387. };
  43388. @vertex
  43389. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  43390. var Varys : VarysStruct;
  43391. var pos = array< vec2<f32>, 4 >(
  43392. vec2<f32>( -1.0, 1.0 ),
  43393. vec2<f32>( 1.0, 1.0 ),
  43394. vec2<f32>( -1.0, -1.0 ),
  43395. vec2<f32>( 1.0, -1.0 )
  43396. );
  43397. var tex = array< vec2<f32>, 4 >(
  43398. vec2<f32>( 0.0, 0.0 ),
  43399. vec2<f32>( 1.0, 0.0 ),
  43400. vec2<f32>( 0.0, 1.0 ),
  43401. vec2<f32>( 1.0, 1.0 )
  43402. );
  43403. Varys.vTex = tex[ vertexIndex ];
  43404. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  43405. return Varys;
  43406. }
  43407. `;
  43408. const mipmapFragmentSource = `
  43409. @group( 0 ) @binding( 0 )
  43410. var imgSampler : sampler;
  43411. @group( 0 ) @binding( 1 )
  43412. var img : texture_2d<f32>;
  43413. @fragment
  43414. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  43415. return textureSample( img, imgSampler, vTex );
  43416. }
  43417. `;
  43418. const flipYFragmentSource = `
  43419. @group( 0 ) @binding( 0 )
  43420. var imgSampler : sampler;
  43421. @group( 0 ) @binding( 1 )
  43422. var img : texture_2d<f32>;
  43423. @fragment
  43424. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  43425. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  43426. }
  43427. `;
  43428. /**
  43429. * The mipmap GPU sampler.
  43430. *
  43431. * @type {GPUSampler}
  43432. */
  43433. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  43434. /**
  43435. * The flipY GPU sampler.
  43436. *
  43437. * @type {GPUSampler}
  43438. */
  43439. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  43440. /**
  43441. * A cache for GPU render pipelines used for copy/transfer passes.
  43442. * Every texture format requires a unique pipeline.
  43443. *
  43444. * @type {Object<string,GPURenderPipeline>}
  43445. */
  43446. this.transferPipelines = {};
  43447. /**
  43448. * A cache for GPU render pipelines used for flipY passes.
  43449. * Every texture format requires a unique pipeline.
  43450. *
  43451. * @type {Object<string,GPURenderPipeline>}
  43452. */
  43453. this.flipYPipelines = {};
  43454. /**
  43455. * The mipmap vertex shader module.
  43456. *
  43457. * @type {GPUShaderModule}
  43458. */
  43459. this.mipmapVertexShaderModule = device.createShaderModule( {
  43460. label: 'mipmapVertex',
  43461. code: mipmapVertexSource
  43462. } );
  43463. /**
  43464. * The mipmap fragment shader module.
  43465. *
  43466. * @type {GPUShaderModule}
  43467. */
  43468. this.mipmapFragmentShaderModule = device.createShaderModule( {
  43469. label: 'mipmapFragment',
  43470. code: mipmapFragmentSource
  43471. } );
  43472. /**
  43473. * The flipY fragment shader module.
  43474. *
  43475. * @type {GPUShaderModule}
  43476. */
  43477. this.flipYFragmentShaderModule = device.createShaderModule( {
  43478. label: 'flipYFragment',
  43479. code: flipYFragmentSource
  43480. } );
  43481. }
  43482. /**
  43483. * Returns a render pipeline for the internal copy render pass. The pass
  43484. * requires a unique render pipeline for each texture format.
  43485. *
  43486. * @param {string} format - The GPU texture format
  43487. * @return {GPURenderPipeline} The GPU render pipeline.
  43488. */
  43489. getTransferPipeline( format ) {
  43490. let pipeline = this.transferPipelines[ format ];
  43491. if ( pipeline === undefined ) {
  43492. pipeline = this.device.createRenderPipeline( {
  43493. label: `mipmap-${ format }`,
  43494. vertex: {
  43495. module: this.mipmapVertexShaderModule,
  43496. entryPoint: 'main'
  43497. },
  43498. fragment: {
  43499. module: this.mipmapFragmentShaderModule,
  43500. entryPoint: 'main',
  43501. targets: [ { format } ]
  43502. },
  43503. primitive: {
  43504. topology: GPUPrimitiveTopology.TriangleStrip,
  43505. stripIndexFormat: GPUIndexFormat.Uint32
  43506. },
  43507. layout: 'auto'
  43508. } );
  43509. this.transferPipelines[ format ] = pipeline;
  43510. }
  43511. return pipeline;
  43512. }
  43513. /**
  43514. * Returns a render pipeline for the flipY render pass. The pass
  43515. * requires a unique render pipeline for each texture format.
  43516. *
  43517. * @param {string} format - The GPU texture format
  43518. * @return {GPURenderPipeline} The GPU render pipeline.
  43519. */
  43520. getFlipYPipeline( format ) {
  43521. let pipeline = this.flipYPipelines[ format ];
  43522. if ( pipeline === undefined ) {
  43523. pipeline = this.device.createRenderPipeline( {
  43524. label: `flipY-${ format }`,
  43525. vertex: {
  43526. module: this.mipmapVertexShaderModule,
  43527. entryPoint: 'main'
  43528. },
  43529. fragment: {
  43530. module: this.flipYFragmentShaderModule,
  43531. entryPoint: 'main',
  43532. targets: [ { format } ]
  43533. },
  43534. primitive: {
  43535. topology: GPUPrimitiveTopology.TriangleStrip,
  43536. stripIndexFormat: GPUIndexFormat.Uint32
  43537. },
  43538. layout: 'auto'
  43539. } );
  43540. this.flipYPipelines[ format ] = pipeline;
  43541. }
  43542. return pipeline;
  43543. }
  43544. /**
  43545. * Flip the contents of the given GPU texture along its vertical axis.
  43546. *
  43547. * @param {GPUTexture} textureGPU - The GPU texture object.
  43548. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43549. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43550. */
  43551. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43552. const format = textureGPUDescriptor.format;
  43553. const { width, height } = textureGPUDescriptor.size;
  43554. const transferPipeline = this.getTransferPipeline( format );
  43555. const flipYPipeline = this.getFlipYPipeline( format );
  43556. const tempTexture = this.device.createTexture( {
  43557. size: { width, height, depthOrArrayLayers: 1 },
  43558. format,
  43559. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  43560. } );
  43561. const srcView = textureGPU.createView( {
  43562. baseMipLevel: 0,
  43563. mipLevelCount: 1,
  43564. dimension: GPUTextureViewDimension.TwoD,
  43565. baseArrayLayer
  43566. } );
  43567. const dstView = tempTexture.createView( {
  43568. baseMipLevel: 0,
  43569. mipLevelCount: 1,
  43570. dimension: GPUTextureViewDimension.TwoD,
  43571. baseArrayLayer: 0
  43572. } );
  43573. const commandEncoder = this.device.createCommandEncoder( {} );
  43574. const pass = ( pipeline, sourceView, destinationView ) => {
  43575. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43576. const bindGroup = this.device.createBindGroup( {
  43577. layout: bindGroupLayout,
  43578. entries: [ {
  43579. binding: 0,
  43580. resource: this.flipYSampler
  43581. }, {
  43582. binding: 1,
  43583. resource: sourceView
  43584. } ]
  43585. } );
  43586. const passEncoder = commandEncoder.beginRenderPass( {
  43587. colorAttachments: [ {
  43588. view: destinationView,
  43589. loadOp: GPULoadOp.Clear,
  43590. storeOp: GPUStoreOp.Store,
  43591. clearValue: [ 0, 0, 0, 0 ]
  43592. } ]
  43593. } );
  43594. passEncoder.setPipeline( pipeline );
  43595. passEncoder.setBindGroup( 0, bindGroup );
  43596. passEncoder.draw( 4, 1, 0, 0 );
  43597. passEncoder.end();
  43598. };
  43599. pass( transferPipeline, srcView, dstView );
  43600. pass( flipYPipeline, dstView, srcView );
  43601. this.device.queue.submit( [ commandEncoder.finish() ] );
  43602. tempTexture.destroy();
  43603. }
  43604. /**
  43605. * Generates mipmaps for the given GPU texture.
  43606. *
  43607. * @param {GPUTexture} textureGPU - The GPU texture object.
  43608. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43609. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43610. */
  43611. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43612. const textureData = this.get( textureGPU );
  43613. if ( textureData.useCount === undefined ) {
  43614. textureData.useCount = 0;
  43615. textureData.layers = [];
  43616. }
  43617. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  43618. const commandEncoder = this.device.createCommandEncoder( {} );
  43619. this._mipmapRunBundles( commandEncoder, passes );
  43620. this.device.queue.submit( [ commandEncoder.finish() ] );
  43621. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  43622. textureData.useCount ++;
  43623. }
  43624. /**
  43625. * Since multiple copy render passes are required to generate mipmaps, the passes
  43626. * are managed as render bundles to improve performance.
  43627. *
  43628. * @param {GPUTexture} textureGPU - The GPU texture object.
  43629. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43630. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  43631. * @return {Array} An array of render bundles.
  43632. */
  43633. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  43634. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  43635. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43636. let srcView = textureGPU.createView( {
  43637. baseMipLevel: 0,
  43638. mipLevelCount: 1,
  43639. dimension: GPUTextureViewDimension.TwoD,
  43640. baseArrayLayer
  43641. } );
  43642. const passes = [];
  43643. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  43644. const bindGroup = this.device.createBindGroup( {
  43645. layout: bindGroupLayout,
  43646. entries: [ {
  43647. binding: 0,
  43648. resource: this.mipmapSampler
  43649. }, {
  43650. binding: 1,
  43651. resource: srcView
  43652. } ]
  43653. } );
  43654. const dstView = textureGPU.createView( {
  43655. baseMipLevel: i,
  43656. mipLevelCount: 1,
  43657. dimension: GPUTextureViewDimension.TwoD,
  43658. baseArrayLayer
  43659. } );
  43660. const passDescriptor = {
  43661. colorAttachments: [ {
  43662. view: dstView,
  43663. loadOp: GPULoadOp.Clear,
  43664. storeOp: GPUStoreOp.Store,
  43665. clearValue: [ 0, 0, 0, 0 ]
  43666. } ]
  43667. };
  43668. const passEncoder = this.device.createRenderBundleEncoder( {
  43669. colorFormats: [ textureGPUDescriptor.format ]
  43670. } );
  43671. passEncoder.setPipeline( pipeline );
  43672. passEncoder.setBindGroup( 0, bindGroup );
  43673. passEncoder.draw( 4, 1, 0, 0 );
  43674. passes.push( {
  43675. renderBundles: [ passEncoder.finish() ],
  43676. passDescriptor
  43677. } );
  43678. srcView = dstView;
  43679. }
  43680. return passes;
  43681. }
  43682. /**
  43683. * Executes the render bundles.
  43684. *
  43685. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  43686. * @param {Array} passes - An array of render bundles.
  43687. */
  43688. _mipmapRunBundles( commandEncoder, passes ) {
  43689. const levels = passes.length;
  43690. for ( let i = 0; i < levels; i ++ ) {
  43691. const pass = passes[ i ];
  43692. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  43693. passEncoder.executeBundles( pass.renderBundles );
  43694. passEncoder.end();
  43695. }
  43696. }
  43697. }
  43698. const _compareToWebGPU = {
  43699. [ NeverCompare ]: 'never',
  43700. [ LessCompare ]: 'less',
  43701. [ EqualCompare ]: 'equal',
  43702. [ LessEqualCompare ]: 'less-equal',
  43703. [ GreaterCompare ]: 'greater',
  43704. [ GreaterEqualCompare ]: 'greater-equal',
  43705. [ AlwaysCompare ]: 'always',
  43706. [ NotEqualCompare ]: 'not-equal'
  43707. };
  43708. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  43709. /**
  43710. * A WebGPU backend utility module for managing textures.
  43711. *
  43712. * @private
  43713. */
  43714. class WebGPUTextureUtils {
  43715. /**
  43716. * Constructs a new utility object.
  43717. *
  43718. * @param {WebGPUBackend} backend - The WebGPU backend.
  43719. */
  43720. constructor( backend ) {
  43721. /**
  43722. * A reference to the WebGPU backend.
  43723. *
  43724. * @type {WebGPUBackend}
  43725. */
  43726. this.backend = backend;
  43727. /**
  43728. * A reference to the pass utils.
  43729. *
  43730. * @type {?WebGPUTexturePassUtils}
  43731. * @default null
  43732. */
  43733. this._passUtils = null;
  43734. /**
  43735. * A dictionary for managing default textures. The key
  43736. * is the texture format, the value the texture object.
  43737. *
  43738. * @type {Object<string,Texture>}
  43739. */
  43740. this.defaultTexture = {};
  43741. /**
  43742. * A dictionary for managing default cube textures. The key
  43743. * is the texture format, the value the texture object.
  43744. *
  43745. * @type {Object<string,CubeTexture>}
  43746. */
  43747. this.defaultCubeTexture = {};
  43748. /**
  43749. * A default video frame.
  43750. *
  43751. * @type {?VideoFrame}
  43752. * @default null
  43753. */
  43754. this.defaultVideoFrame = null;
  43755. /**
  43756. * Represents the color attachment of the default framebuffer.
  43757. *
  43758. * @type {?GPUTexture}
  43759. * @default null
  43760. */
  43761. this.colorBuffer = null;
  43762. /**
  43763. * Represents the depth attachment of the default framebuffer.
  43764. *
  43765. * @type {DepthTexture}
  43766. */
  43767. this.depthTexture = new DepthTexture();
  43768. this.depthTexture.name = 'depthBuffer';
  43769. }
  43770. /**
  43771. * Creates a GPU sampler for the given texture.
  43772. *
  43773. * @param {Texture} texture - The texture to create the sampler for.
  43774. */
  43775. createSampler( texture ) {
  43776. const backend = this.backend;
  43777. const device = backend.device;
  43778. const textureGPU = backend.get( texture );
  43779. const samplerDescriptorGPU = {
  43780. addressModeU: this._convertAddressMode( texture.wrapS ),
  43781. addressModeV: this._convertAddressMode( texture.wrapT ),
  43782. addressModeW: this._convertAddressMode( texture.wrapR ),
  43783. magFilter: this._convertFilterMode( texture.magFilter ),
  43784. minFilter: this._convertFilterMode( texture.minFilter ),
  43785. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43786. maxAnisotropy: 1
  43787. };
  43788. // anisotropy can only be used when all filter modes are set to linear.
  43789. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  43790. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  43791. }
  43792. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43793. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43794. }
  43795. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43796. }
  43797. /**
  43798. * Creates a default texture for the given texture that can be used
  43799. * as a placeholder until the actual texture is ready for usage.
  43800. *
  43801. * @param {Texture} texture - The texture to create a default texture for.
  43802. */
  43803. createDefaultTexture( texture ) {
  43804. let textureGPU;
  43805. const format = getFormat( texture );
  43806. if ( texture.isCubeTexture ) {
  43807. textureGPU = this._getDefaultCubeTextureGPU( format );
  43808. } else if ( texture.isVideoTexture ) {
  43809. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43810. } else {
  43811. textureGPU = this._getDefaultTextureGPU( format );
  43812. }
  43813. this.backend.get( texture ).texture = textureGPU;
  43814. }
  43815. /**
  43816. * Defines a texture on the GPU for the given texture object.
  43817. *
  43818. * @param {Texture} texture - The texture.
  43819. * @param {Object} [options={}] - Optional configuration parameter.
  43820. * @return {undefined}
  43821. */
  43822. createTexture( texture, options = {} ) {
  43823. const backend = this.backend;
  43824. const textureData = backend.get( texture );
  43825. if ( textureData.initialized ) {
  43826. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43827. }
  43828. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43829. if ( options.levels === undefined ) options.levels = 1;
  43830. if ( options.depth === undefined ) options.depth = 1;
  43831. const { width, height, depth, levels } = options;
  43832. if ( texture.isFramebufferTexture ) {
  43833. if ( options.renderTarget ) {
  43834. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  43835. } else {
  43836. options.format = this.backend.utils.getPreferredCanvasFormat();
  43837. }
  43838. }
  43839. const dimension = this._getDimension( texture );
  43840. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43841. textureData.format = format;
  43842. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  43843. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43844. if ( texture.isStorageTexture === true ) {
  43845. usage |= GPUTextureUsage.STORAGE_BINDING;
  43846. }
  43847. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43848. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43849. }
  43850. const textureDescriptorGPU = {
  43851. label: texture.name,
  43852. size: {
  43853. width: width,
  43854. height: height,
  43855. depthOrArrayLayers: depth,
  43856. },
  43857. mipLevelCount: levels,
  43858. sampleCount: primarySamples,
  43859. dimension: dimension,
  43860. format: format,
  43861. usage: usage
  43862. };
  43863. // texture creation
  43864. if ( texture.isVideoTexture ) {
  43865. const video = texture.source.data;
  43866. const videoFrame = new VideoFrame( video );
  43867. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43868. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43869. videoFrame.close();
  43870. textureData.externalTexture = video;
  43871. } else {
  43872. if ( format === undefined ) {
  43873. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43874. return this.createDefaultTexture( texture );
  43875. }
  43876. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43877. }
  43878. if ( isMSAA ) {
  43879. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43880. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43881. msaaTextureDescriptorGPU.sampleCount = samples;
  43882. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43883. }
  43884. textureData.initialized = true;
  43885. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43886. }
  43887. /**
  43888. * Destroys the GPU data for the given texture object.
  43889. *
  43890. * @param {Texture} texture - The texture.
  43891. */
  43892. destroyTexture( texture ) {
  43893. const backend = this.backend;
  43894. const textureData = backend.get( texture );
  43895. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  43896. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43897. backend.delete( texture );
  43898. }
  43899. /**
  43900. * Destroys the GPU sampler for the given texture.
  43901. *
  43902. * @param {Texture} texture - The texture to destroy the sampler for.
  43903. */
  43904. destroySampler( texture ) {
  43905. const backend = this.backend;
  43906. const textureData = backend.get( texture );
  43907. delete textureData.sampler;
  43908. }
  43909. /**
  43910. * Generates mipmaps for the given texture.
  43911. *
  43912. * @param {Texture} texture - The texture.
  43913. */
  43914. generateMipmaps( texture ) {
  43915. const textureData = this.backend.get( texture );
  43916. if ( texture.isCubeTexture ) {
  43917. for ( let i = 0; i < 6; i ++ ) {
  43918. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43919. }
  43920. } else {
  43921. const depth = texture.image.depth || 1;
  43922. for ( let i = 0; i < depth; i ++ ) {
  43923. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43924. }
  43925. }
  43926. }
  43927. /**
  43928. * Returns the color buffer representing the color
  43929. * attachment of the default framebuffer.
  43930. *
  43931. * @return {GPUTexture} The color buffer.
  43932. */
  43933. getColorBuffer() {
  43934. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43935. const backend = this.backend;
  43936. const { width, height } = backend.getDrawingBufferSize();
  43937. this.colorBuffer = backend.device.createTexture( {
  43938. label: 'colorBuffer',
  43939. size: {
  43940. width: width,
  43941. height: height,
  43942. depthOrArrayLayers: 1
  43943. },
  43944. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43945. format: backend.utils.getPreferredCanvasFormat(),
  43946. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43947. } );
  43948. return this.colorBuffer;
  43949. }
  43950. /**
  43951. * Returns the depth buffer representing the depth
  43952. * attachment of the default framebuffer.
  43953. *
  43954. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  43955. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  43956. * @return {GPUTexture} The depth buffer.
  43957. */
  43958. getDepthBuffer( depth = true, stencil = false ) {
  43959. const backend = this.backend;
  43960. const { width, height } = backend.getDrawingBufferSize();
  43961. const depthTexture = this.depthTexture;
  43962. const depthTextureGPU = backend.get( depthTexture ).texture;
  43963. let format, type;
  43964. if ( stencil ) {
  43965. format = DepthStencilFormat;
  43966. type = UnsignedInt248Type;
  43967. } else if ( depth ) {
  43968. format = DepthFormat;
  43969. type = UnsignedIntType;
  43970. }
  43971. if ( depthTextureGPU !== undefined ) {
  43972. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43973. return depthTextureGPU;
  43974. }
  43975. this.destroyTexture( depthTexture );
  43976. }
  43977. depthTexture.name = 'depthBuffer';
  43978. depthTexture.format = format;
  43979. depthTexture.type = type;
  43980. depthTexture.image.width = width;
  43981. depthTexture.image.height = height;
  43982. this.createTexture( depthTexture, { width, height } );
  43983. return backend.get( depthTexture ).texture;
  43984. }
  43985. /**
  43986. * Uploads the updated texture data to the GPU.
  43987. *
  43988. * @param {Texture} texture - The texture.
  43989. * @param {Object} [options={}] - Optional configuration parameter.
  43990. */
  43991. updateTexture( texture, options ) {
  43992. const textureData = this.backend.get( texture );
  43993. const { textureDescriptorGPU } = textureData;
  43994. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43995. return;
  43996. // transfer texture data
  43997. if ( texture.isDataTexture ) {
  43998. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43999. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44000. for ( let i = 0; i < options.image.depth; i ++ ) {
  44001. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  44002. }
  44003. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  44004. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  44005. } else if ( texture.isCubeTexture ) {
  44006. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  44007. } else if ( texture.isVideoTexture ) {
  44008. const video = texture.source.data;
  44009. textureData.externalTexture = video;
  44010. } else {
  44011. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44012. }
  44013. //
  44014. textureData.version = texture.version;
  44015. if ( texture.onUpdate ) texture.onUpdate( texture );
  44016. }
  44017. /**
  44018. * Returns texture data as a typed array.
  44019. *
  44020. * @async
  44021. * @param {Texture} texture - The texture to copy.
  44022. * @param {number} x - The x coordinate of the copy origin.
  44023. * @param {number} y - The y coordinate of the copy origin.
  44024. * @param {number} width - The width of the copy.
  44025. * @param {number} height - The height of the copy.
  44026. * @param {number} faceIndex - The face index.
  44027. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44028. */
  44029. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44030. const device = this.backend.device;
  44031. const textureData = this.backend.get( texture );
  44032. const textureGPU = textureData.texture;
  44033. const format = textureData.textureDescriptorGPU.format;
  44034. const bytesPerTexel = this._getBytesPerTexel( format );
  44035. let bytesPerRow = width * bytesPerTexel;
  44036. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  44037. const readBuffer = device.createBuffer(
  44038. {
  44039. size: width * height * bytesPerTexel,
  44040. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44041. }
  44042. );
  44043. const encoder = device.createCommandEncoder();
  44044. encoder.copyTextureToBuffer(
  44045. {
  44046. texture: textureGPU,
  44047. origin: { x, y, z: faceIndex },
  44048. },
  44049. {
  44050. buffer: readBuffer,
  44051. bytesPerRow: bytesPerRow
  44052. },
  44053. {
  44054. width: width,
  44055. height: height
  44056. }
  44057. );
  44058. const typedArrayType = this._getTypedArrayType( format );
  44059. device.queue.submit( [ encoder.finish() ] );
  44060. await readBuffer.mapAsync( GPUMapMode.READ );
  44061. const buffer = readBuffer.getMappedRange();
  44062. return new typedArrayType( buffer );
  44063. }
  44064. /**
  44065. * Returns `true` if the given texture is an environment map.
  44066. *
  44067. * @private
  44068. * @param {Texture} texture - The texture.
  44069. * @return {boolean} Whether the given texture is an environment map or not.
  44070. */
  44071. _isEnvironmentTexture( texture ) {
  44072. const mapping = texture.mapping;
  44073. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44074. }
  44075. /**
  44076. * Returns the default GPU texture for the given format.
  44077. *
  44078. * @private
  44079. * @param {string} format - The GPU format.
  44080. * @return {GPUTexture} The GPU texture.
  44081. */
  44082. _getDefaultTextureGPU( format ) {
  44083. let defaultTexture = this.defaultTexture[ format ];
  44084. if ( defaultTexture === undefined ) {
  44085. const texture = new Texture();
  44086. texture.minFilter = NearestFilter;
  44087. texture.magFilter = NearestFilter;
  44088. this.createTexture( texture, { width: 1, height: 1, format } );
  44089. this.defaultTexture[ format ] = defaultTexture = texture;
  44090. }
  44091. return this.backend.get( defaultTexture ).texture;
  44092. }
  44093. /**
  44094. * Returns the default GPU cube texture for the given format.
  44095. *
  44096. * @private
  44097. * @param {string} format - The GPU format.
  44098. * @return {GPUTexture} The GPU texture.
  44099. */
  44100. _getDefaultCubeTextureGPU( format ) {
  44101. let defaultCubeTexture = this.defaultTexture[ format ];
  44102. if ( defaultCubeTexture === undefined ) {
  44103. const texture = new CubeTexture();
  44104. texture.minFilter = NearestFilter;
  44105. texture.magFilter = NearestFilter;
  44106. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  44107. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  44108. }
  44109. return this.backend.get( defaultCubeTexture ).texture;
  44110. }
  44111. /**
  44112. * Returns the default video frame used as default data in context of video textures.
  44113. *
  44114. * @private
  44115. * @return {VideoFrame} The video frame.
  44116. */
  44117. _getDefaultVideoFrame() {
  44118. let defaultVideoFrame = this.defaultVideoFrame;
  44119. if ( defaultVideoFrame === null ) {
  44120. const init = {
  44121. timestamp: 0,
  44122. codedWidth: 1,
  44123. codedHeight: 1,
  44124. format: 'RGBA',
  44125. };
  44126. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  44127. }
  44128. return defaultVideoFrame;
  44129. }
  44130. /**
  44131. * Uploads cube texture image data to the GPU memory.
  44132. *
  44133. * @private
  44134. * @param {Array} images - The cube image data.
  44135. * @param {GPUTexture} textureGPU - The GPU texture.
  44136. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44137. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44138. */
  44139. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  44140. for ( let i = 0; i < 6; i ++ ) {
  44141. const image = images[ i ];
  44142. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  44143. if ( image.isDataTexture ) {
  44144. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44145. } else {
  44146. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44147. }
  44148. }
  44149. }
  44150. /**
  44151. * Uploads texture image data to the GPU memory.
  44152. *
  44153. * @private
  44154. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  44155. * @param {GPUTexture} textureGPU - The GPU texture.
  44156. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44157. * @param {number} originDepth - The origin depth.
  44158. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44159. */
  44160. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  44161. const device = this.backend.device;
  44162. device.queue.copyExternalImageToTexture(
  44163. {
  44164. source: image,
  44165. flipY: flipY
  44166. }, {
  44167. texture: textureGPU,
  44168. mipLevel: 0,
  44169. origin: { x: 0, y: 0, z: originDepth }
  44170. }, {
  44171. width: image.width,
  44172. height: image.height,
  44173. depthOrArrayLayers: 1
  44174. }
  44175. );
  44176. }
  44177. /**
  44178. * Returns the pass utils singleton.
  44179. *
  44180. * @private
  44181. * @return {WebGPUTexturePassUtils} The utils instance.
  44182. */
  44183. _getPassUtils() {
  44184. let passUtils = this._passUtils;
  44185. if ( passUtils === null ) {
  44186. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  44187. }
  44188. return passUtils;
  44189. }
  44190. /**
  44191. * Generates mipmaps for the given GPU texture.
  44192. *
  44193. * @private
  44194. * @param {GPUTexture} textureGPU - The GPU texture object.
  44195. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44196. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44197. */
  44198. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  44199. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  44200. }
  44201. /**
  44202. * Flip the contents of the given GPU texture along its vertical axis.
  44203. *
  44204. * @private
  44205. * @param {GPUTexture} textureGPU - The GPU texture object.
  44206. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44207. * @param {number} [originDepth=0] - The origin depth.
  44208. */
  44209. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  44210. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  44211. }
  44212. /**
  44213. * Uploads texture buffer data to the GPU memory.
  44214. *
  44215. * @private
  44216. * @param {Object} image - An object defining the image buffer data.
  44217. * @param {GPUTexture} textureGPU - The GPU texture.
  44218. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44219. * @param {number} originDepth - The origin depth.
  44220. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44221. * @param {number} [depth=0] - TODO.
  44222. */
  44223. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  44224. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44225. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  44226. const device = this.backend.device;
  44227. const data = image.data;
  44228. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  44229. const bytesPerRow = image.width * bytesPerTexel;
  44230. device.queue.writeTexture(
  44231. {
  44232. texture: textureGPU,
  44233. mipLevel: 0,
  44234. origin: { x: 0, y: 0, z: originDepth }
  44235. },
  44236. data,
  44237. {
  44238. offset: image.width * image.height * bytesPerTexel * depth,
  44239. bytesPerRow
  44240. },
  44241. {
  44242. width: image.width,
  44243. height: image.height,
  44244. depthOrArrayLayers: 1
  44245. } );
  44246. if ( flipY === true ) {
  44247. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  44248. }
  44249. }
  44250. /**
  44251. * Uploads compressed texture data to the GPU memory.
  44252. *
  44253. * @private
  44254. * @param {Array<Object>} mipmaps - An array with mipmap data.
  44255. * @param {GPUTexture} textureGPU - The GPU texture.
  44256. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44257. */
  44258. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  44259. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44260. const device = this.backend.device;
  44261. const blockData = this._getBlockData( textureDescriptorGPU.format );
  44262. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  44263. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44264. const mipmap = mipmaps[ i ];
  44265. const width = mipmap.width;
  44266. const height = mipmap.height;
  44267. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  44268. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  44269. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  44270. for ( let j = 0; j < depth; j ++ ) {
  44271. device.queue.writeTexture(
  44272. {
  44273. texture: textureGPU,
  44274. mipLevel: i,
  44275. origin: { x: 0, y: 0, z: j }
  44276. },
  44277. mipmap.data,
  44278. {
  44279. offset: j * bytesPerImage,
  44280. bytesPerRow,
  44281. rowsPerImage: Math.ceil( height / blockData.height )
  44282. },
  44283. {
  44284. width: Math.ceil( width / blockData.width ) * blockData.width,
  44285. height: Math.ceil( height / blockData.height ) * blockData.height,
  44286. depthOrArrayLayers: 1
  44287. }
  44288. );
  44289. }
  44290. }
  44291. }
  44292. /**
  44293. * This method is only relevant for compressed texture formats. It returns a block
  44294. * data descriptor for the given GPU compressed texture format.
  44295. *
  44296. * @private
  44297. * @param {string} format - The GPU compressed texture format.
  44298. * @return {Object} The block data descriptor.
  44299. */
  44300. _getBlockData( format ) {
  44301. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  44302. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  44303. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  44304. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  44305. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  44306. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  44307. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  44308. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44309. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44310. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44311. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  44312. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  44313. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  44314. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  44315. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44316. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  44317. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  44318. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  44319. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  44320. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  44321. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  44322. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  44323. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  44324. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  44325. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  44326. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  44327. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  44328. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  44329. }
  44330. /**
  44331. * Converts the three.js uv wrapping constants to GPU address mode constants.
  44332. *
  44333. * @private
  44334. * @param {number} value - The three.js constant defining a uv wrapping mode.
  44335. * @return {string} The GPU address mode.
  44336. */
  44337. _convertAddressMode( value ) {
  44338. let addressMode = GPUAddressMode.ClampToEdge;
  44339. if ( value === RepeatWrapping ) {
  44340. addressMode = GPUAddressMode.Repeat;
  44341. } else if ( value === MirroredRepeatWrapping ) {
  44342. addressMode = GPUAddressMode.MirrorRepeat;
  44343. }
  44344. return addressMode;
  44345. }
  44346. /**
  44347. * Converts the three.js filter constants to GPU filter constants.
  44348. *
  44349. * @private
  44350. * @param {number} value - The three.js constant defining a filter mode.
  44351. * @return {string} The GPU filter mode.
  44352. */
  44353. _convertFilterMode( value ) {
  44354. let filterMode = GPUFilterMode.Linear;
  44355. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  44356. filterMode = GPUFilterMode.Nearest;
  44357. }
  44358. return filterMode;
  44359. }
  44360. /**
  44361. * Returns the bytes-per-texel value for the given GPU texture format.
  44362. *
  44363. * @private
  44364. * @param {string} format - The GPU texture format.
  44365. * @return {number} The bytes-per-texel.
  44366. */
  44367. _getBytesPerTexel( format ) {
  44368. // 8-bit formats
  44369. if ( format === GPUTextureFormat.R8Unorm ||
  44370. format === GPUTextureFormat.R8Snorm ||
  44371. format === GPUTextureFormat.R8Uint ||
  44372. format === GPUTextureFormat.R8Sint ) return 1;
  44373. // 16-bit formats
  44374. if ( format === GPUTextureFormat.R16Uint ||
  44375. format === GPUTextureFormat.R16Sint ||
  44376. format === GPUTextureFormat.R16Float ||
  44377. format === GPUTextureFormat.RG8Unorm ||
  44378. format === GPUTextureFormat.RG8Snorm ||
  44379. format === GPUTextureFormat.RG8Uint ||
  44380. format === GPUTextureFormat.RG8Sint ) return 2;
  44381. // 32-bit formats
  44382. if ( format === GPUTextureFormat.R32Uint ||
  44383. format === GPUTextureFormat.R32Sint ||
  44384. format === GPUTextureFormat.R32Float ||
  44385. format === GPUTextureFormat.RG16Uint ||
  44386. format === GPUTextureFormat.RG16Sint ||
  44387. format === GPUTextureFormat.RG16Float ||
  44388. format === GPUTextureFormat.RGBA8Unorm ||
  44389. format === GPUTextureFormat.RGBA8UnormSRGB ||
  44390. format === GPUTextureFormat.RGBA8Snorm ||
  44391. format === GPUTextureFormat.RGBA8Uint ||
  44392. format === GPUTextureFormat.RGBA8Sint ||
  44393. format === GPUTextureFormat.BGRA8Unorm ||
  44394. format === GPUTextureFormat.BGRA8UnormSRGB ||
  44395. // Packed 32-bit formats
  44396. format === GPUTextureFormat.RGB9E5UFloat ||
  44397. format === GPUTextureFormat.RGB10A2Unorm ||
  44398. format === GPUTextureFormat.RG11B10UFloat ||
  44399. format === GPUTextureFormat.Depth32Float ||
  44400. format === GPUTextureFormat.Depth24Plus ||
  44401. format === GPUTextureFormat.Depth24PlusStencil8 ||
  44402. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  44403. // 64-bit formats
  44404. if ( format === GPUTextureFormat.RG32Uint ||
  44405. format === GPUTextureFormat.RG32Sint ||
  44406. format === GPUTextureFormat.RG32Float ||
  44407. format === GPUTextureFormat.RGBA16Uint ||
  44408. format === GPUTextureFormat.RGBA16Sint ||
  44409. format === GPUTextureFormat.RGBA16Float ) return 8;
  44410. // 128-bit formats
  44411. if ( format === GPUTextureFormat.RGBA32Uint ||
  44412. format === GPUTextureFormat.RGBA32Sint ||
  44413. format === GPUTextureFormat.RGBA32Float ) return 16;
  44414. }
  44415. /**
  44416. * Returns the corresponding typed array type for the given GPU texture format.
  44417. *
  44418. * @private
  44419. * @param {string} format - The GPU texture format.
  44420. * @return {TypedArray.constructor} The typed array type.
  44421. */
  44422. _getTypedArrayType( format ) {
  44423. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  44424. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  44425. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  44426. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  44427. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  44428. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  44429. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  44430. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  44431. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  44432. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  44433. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  44434. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  44435. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  44436. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  44437. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  44438. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  44439. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  44440. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  44441. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  44442. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  44443. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  44444. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  44445. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  44446. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  44447. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  44448. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  44449. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  44450. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  44451. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  44452. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  44453. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  44454. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  44455. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  44456. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  44457. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  44458. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  44459. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  44460. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  44461. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  44462. }
  44463. /**
  44464. * Returns the GPU dimensions for the given texture.
  44465. *
  44466. * @private
  44467. * @param {Texture} texture - The texture.
  44468. * @return {string} The GPU dimension.
  44469. */
  44470. _getDimension( texture ) {
  44471. let dimension;
  44472. if ( texture.isData3DTexture ) {
  44473. dimension = GPUTextureDimension.ThreeD;
  44474. } else {
  44475. dimension = GPUTextureDimension.TwoD;
  44476. }
  44477. return dimension;
  44478. }
  44479. }
  44480. /**
  44481. * Returns the GPU format for the given texture.
  44482. *
  44483. * @param {Texture} texture - The texture.
  44484. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  44485. * It is not necessary to apply the device for most formats.
  44486. * @return {string} The GPU format.
  44487. */
  44488. function getFormat( texture, device = null ) {
  44489. const format = texture.format;
  44490. const type = texture.type;
  44491. const colorSpace = texture.colorSpace;
  44492. let formatGPU;
  44493. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  44494. switch ( format ) {
  44495. case RGBA_S3TC_DXT1_Format:
  44496. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  44497. break;
  44498. case RGBA_S3TC_DXT3_Format:
  44499. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  44500. break;
  44501. case RGBA_S3TC_DXT5_Format:
  44502. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  44503. break;
  44504. case RGB_ETC2_Format:
  44505. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  44506. break;
  44507. case RGBA_ETC2_EAC_Format:
  44508. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  44509. break;
  44510. case RGBA_ASTC_4x4_Format:
  44511. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  44512. break;
  44513. case RGBA_ASTC_5x4_Format:
  44514. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  44515. break;
  44516. case RGBA_ASTC_5x5_Format:
  44517. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  44518. break;
  44519. case RGBA_ASTC_6x5_Format:
  44520. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  44521. break;
  44522. case RGBA_ASTC_6x6_Format:
  44523. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  44524. break;
  44525. case RGBA_ASTC_8x5_Format:
  44526. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  44527. break;
  44528. case RGBA_ASTC_8x6_Format:
  44529. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  44530. break;
  44531. case RGBA_ASTC_8x8_Format:
  44532. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  44533. break;
  44534. case RGBA_ASTC_10x5_Format:
  44535. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  44536. break;
  44537. case RGBA_ASTC_10x6_Format:
  44538. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  44539. break;
  44540. case RGBA_ASTC_10x8_Format:
  44541. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  44542. break;
  44543. case RGBA_ASTC_10x10_Format:
  44544. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  44545. break;
  44546. case RGBA_ASTC_12x10_Format:
  44547. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  44548. break;
  44549. case RGBA_ASTC_12x12_Format:
  44550. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  44551. break;
  44552. case RGBAFormat:
  44553. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44554. break;
  44555. default:
  44556. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44557. }
  44558. } else {
  44559. switch ( format ) {
  44560. case RGBAFormat:
  44561. switch ( type ) {
  44562. case ByteType:
  44563. formatGPU = GPUTextureFormat.RGBA8Snorm;
  44564. break;
  44565. case ShortType:
  44566. formatGPU = GPUTextureFormat.RGBA16Sint;
  44567. break;
  44568. case UnsignedShortType:
  44569. formatGPU = GPUTextureFormat.RGBA16Uint;
  44570. break;
  44571. case UnsignedIntType:
  44572. formatGPU = GPUTextureFormat.RGBA32Uint;
  44573. break;
  44574. case IntType:
  44575. formatGPU = GPUTextureFormat.RGBA32Sint;
  44576. break;
  44577. case UnsignedByteType:
  44578. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44579. break;
  44580. case HalfFloatType:
  44581. formatGPU = GPUTextureFormat.RGBA16Float;
  44582. break;
  44583. case FloatType:
  44584. formatGPU = GPUTextureFormat.RGBA32Float;
  44585. break;
  44586. default:
  44587. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  44588. }
  44589. break;
  44590. case RGBFormat:
  44591. switch ( type ) {
  44592. case UnsignedInt5999Type:
  44593. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  44594. break;
  44595. default:
  44596. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  44597. }
  44598. break;
  44599. case RedFormat:
  44600. switch ( type ) {
  44601. case ByteType:
  44602. formatGPU = GPUTextureFormat.R8Snorm;
  44603. break;
  44604. case ShortType:
  44605. formatGPU = GPUTextureFormat.R16Sint;
  44606. break;
  44607. case UnsignedShortType:
  44608. formatGPU = GPUTextureFormat.R16Uint;
  44609. break;
  44610. case UnsignedIntType:
  44611. formatGPU = GPUTextureFormat.R32Uint;
  44612. break;
  44613. case IntType:
  44614. formatGPU = GPUTextureFormat.R32Sint;
  44615. break;
  44616. case UnsignedByteType:
  44617. formatGPU = GPUTextureFormat.R8Unorm;
  44618. break;
  44619. case HalfFloatType:
  44620. formatGPU = GPUTextureFormat.R16Float;
  44621. break;
  44622. case FloatType:
  44623. formatGPU = GPUTextureFormat.R32Float;
  44624. break;
  44625. default:
  44626. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  44627. }
  44628. break;
  44629. case RGFormat:
  44630. switch ( type ) {
  44631. case ByteType:
  44632. formatGPU = GPUTextureFormat.RG8Snorm;
  44633. break;
  44634. case ShortType:
  44635. formatGPU = GPUTextureFormat.RG16Sint;
  44636. break;
  44637. case UnsignedShortType:
  44638. formatGPU = GPUTextureFormat.RG16Uint;
  44639. break;
  44640. case UnsignedIntType:
  44641. formatGPU = GPUTextureFormat.RG32Uint;
  44642. break;
  44643. case IntType:
  44644. formatGPU = GPUTextureFormat.RG32Sint;
  44645. break;
  44646. case UnsignedByteType:
  44647. formatGPU = GPUTextureFormat.RG8Unorm;
  44648. break;
  44649. case HalfFloatType:
  44650. formatGPU = GPUTextureFormat.RG16Float;
  44651. break;
  44652. case FloatType:
  44653. formatGPU = GPUTextureFormat.RG32Float;
  44654. break;
  44655. default:
  44656. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  44657. }
  44658. break;
  44659. case DepthFormat:
  44660. switch ( type ) {
  44661. case UnsignedShortType:
  44662. formatGPU = GPUTextureFormat.Depth16Unorm;
  44663. break;
  44664. case UnsignedIntType:
  44665. formatGPU = GPUTextureFormat.Depth24Plus;
  44666. break;
  44667. case FloatType:
  44668. formatGPU = GPUTextureFormat.Depth32Float;
  44669. break;
  44670. default:
  44671. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  44672. }
  44673. break;
  44674. case DepthStencilFormat:
  44675. switch ( type ) {
  44676. case UnsignedInt248Type:
  44677. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  44678. break;
  44679. case FloatType:
  44680. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  44681. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  44682. }
  44683. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  44684. break;
  44685. default:
  44686. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  44687. }
  44688. break;
  44689. case RedIntegerFormat:
  44690. switch ( type ) {
  44691. case IntType:
  44692. formatGPU = GPUTextureFormat.R32Sint;
  44693. break;
  44694. case UnsignedIntType:
  44695. formatGPU = GPUTextureFormat.R32Uint;
  44696. break;
  44697. default:
  44698. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  44699. }
  44700. break;
  44701. case RGIntegerFormat:
  44702. switch ( type ) {
  44703. case IntType:
  44704. formatGPU = GPUTextureFormat.RG32Sint;
  44705. break;
  44706. case UnsignedIntType:
  44707. formatGPU = GPUTextureFormat.RG32Uint;
  44708. break;
  44709. default:
  44710. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  44711. }
  44712. break;
  44713. case RGBAIntegerFormat:
  44714. switch ( type ) {
  44715. case IntType:
  44716. formatGPU = GPUTextureFormat.RGBA32Sint;
  44717. break;
  44718. case UnsignedIntType:
  44719. formatGPU = GPUTextureFormat.RGBA32Uint;
  44720. break;
  44721. default:
  44722. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  44723. }
  44724. break;
  44725. default:
  44726. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44727. }
  44728. }
  44729. return formatGPU;
  44730. }
  44731. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  44732. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  44733. const wgslTypeLib$1 = {
  44734. 'f32': 'float',
  44735. 'i32': 'int',
  44736. 'u32': 'uint',
  44737. 'bool': 'bool',
  44738. 'vec2<f32>': 'vec2',
  44739. 'vec2<i32>': 'ivec2',
  44740. 'vec2<u32>': 'uvec2',
  44741. 'vec2<bool>': 'bvec2',
  44742. 'vec2f': 'vec2',
  44743. 'vec2i': 'ivec2',
  44744. 'vec2u': 'uvec2',
  44745. 'vec2b': 'bvec2',
  44746. 'vec3<f32>': 'vec3',
  44747. 'vec3<i32>': 'ivec3',
  44748. 'vec3<u32>': 'uvec3',
  44749. 'vec3<bool>': 'bvec3',
  44750. 'vec3f': 'vec3',
  44751. 'vec3i': 'ivec3',
  44752. 'vec3u': 'uvec3',
  44753. 'vec3b': 'bvec3',
  44754. 'vec4<f32>': 'vec4',
  44755. 'vec4<i32>': 'ivec4',
  44756. 'vec4<u32>': 'uvec4',
  44757. 'vec4<bool>': 'bvec4',
  44758. 'vec4f': 'vec4',
  44759. 'vec4i': 'ivec4',
  44760. 'vec4u': 'uvec4',
  44761. 'vec4b': 'bvec4',
  44762. 'mat2x2<f32>': 'mat2',
  44763. 'mat2x2f': 'mat2',
  44764. 'mat3x3<f32>': 'mat3',
  44765. 'mat3x3f': 'mat3',
  44766. 'mat4x4<f32>': 'mat4',
  44767. 'mat4x4f': 'mat4',
  44768. 'sampler': 'sampler',
  44769. 'texture_1d': 'texture',
  44770. 'texture_2d': 'texture',
  44771. 'texture_2d_array': 'texture',
  44772. 'texture_multisampled_2d': 'cubeTexture',
  44773. 'texture_depth_2d': 'depthTexture',
  44774. 'texture_depth_multisampled_2d': 'depthTexture',
  44775. 'texture_3d': 'texture3D',
  44776. 'texture_cube': 'cubeTexture',
  44777. 'texture_cube_array': 'cubeTexture',
  44778. 'texture_storage_1d': 'storageTexture',
  44779. 'texture_storage_2d': 'storageTexture',
  44780. 'texture_storage_2d_array': 'storageTexture',
  44781. 'texture_storage_3d': 'storageTexture'
  44782. };
  44783. const parse = ( source ) => {
  44784. source = source.trim();
  44785. const declaration = source.match( declarationRegexp );
  44786. if ( declaration !== null && declaration.length === 4 ) {
  44787. const inputsCode = declaration[ 2 ];
  44788. const propsMatches = [];
  44789. let match = null;
  44790. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  44791. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  44792. }
  44793. // Process matches to correctly pair names and types
  44794. const inputs = [];
  44795. for ( let i = 0; i < propsMatches.length; i ++ ) {
  44796. const { name, type } = propsMatches[ i ];
  44797. let resolvedType = type;
  44798. if ( resolvedType.startsWith( 'ptr' ) ) {
  44799. resolvedType = 'pointer';
  44800. } else {
  44801. if ( resolvedType.startsWith( 'texture' ) ) {
  44802. resolvedType = type.split( '<' )[ 0 ];
  44803. }
  44804. resolvedType = wgslTypeLib$1[ resolvedType ];
  44805. }
  44806. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  44807. }
  44808. const blockCode = source.substring( declaration[ 0 ].length );
  44809. const outputType = declaration[ 3 ] || 'void';
  44810. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  44811. const type = wgslTypeLib$1[ outputType ] || outputType;
  44812. return {
  44813. type,
  44814. inputs,
  44815. name,
  44816. inputsCode,
  44817. blockCode,
  44818. outputType
  44819. };
  44820. } else {
  44821. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  44822. }
  44823. };
  44824. /**
  44825. * This class represents a WSL node function.
  44826. *
  44827. * @augments NodeFunction
  44828. */
  44829. class WGSLNodeFunction extends NodeFunction {
  44830. /**
  44831. * Constructs a new WGSL node function.
  44832. *
  44833. * @param {string} source - The WGSL source.
  44834. */
  44835. constructor( source ) {
  44836. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  44837. super( type, inputs, name );
  44838. this.inputsCode = inputsCode;
  44839. this.blockCode = blockCode;
  44840. this.outputType = outputType;
  44841. }
  44842. /**
  44843. * This method returns the WGSL code of the node function.
  44844. *
  44845. * @param {string} [name=this.name] - The function's name.
  44846. * @return {string} The shader code.
  44847. */
  44848. getCode( name = this.name ) {
  44849. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  44850. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  44851. }
  44852. }
  44853. /**
  44854. * A WGSL node parser.
  44855. *
  44856. * @augments NodeParser
  44857. */
  44858. class WGSLNodeParser extends NodeParser {
  44859. /**
  44860. * The method parses the given WGSL code an returns a node function.
  44861. *
  44862. * @param {string} source - The WGSL code.
  44863. * @return {WGSLNodeFunction} A node function.
  44864. */
  44865. parseFunction( source ) {
  44866. return new WGSLNodeFunction( source );
  44867. }
  44868. }
  44869. // GPUShaderStage is not defined in browsers not supporting WebGPU
  44870. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  44871. const accessNames = {
  44872. [ NodeAccess.READ_ONLY ]: 'read',
  44873. [ NodeAccess.WRITE_ONLY ]: 'write',
  44874. [ NodeAccess.READ_WRITE ]: 'read_write'
  44875. };
  44876. const wrapNames = {
  44877. [ RepeatWrapping ]: 'repeat',
  44878. [ ClampToEdgeWrapping ]: 'clamp',
  44879. [ MirroredRepeatWrapping ]: 'mirror'
  44880. };
  44881. const gpuShaderStageLib = {
  44882. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  44883. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  44884. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  44885. };
  44886. const supports = {
  44887. instance: true,
  44888. swizzleAssign: false,
  44889. storageBuffer: true
  44890. };
  44891. const wgslFnOpLib = {
  44892. '^^': 'tsl_xor'
  44893. };
  44894. const wgslTypeLib = {
  44895. float: 'f32',
  44896. int: 'i32',
  44897. uint: 'u32',
  44898. bool: 'bool',
  44899. color: 'vec3<f32>',
  44900. vec2: 'vec2<f32>',
  44901. ivec2: 'vec2<i32>',
  44902. uvec2: 'vec2<u32>',
  44903. bvec2: 'vec2<bool>',
  44904. vec3: 'vec3<f32>',
  44905. ivec3: 'vec3<i32>',
  44906. uvec3: 'vec3<u32>',
  44907. bvec3: 'vec3<bool>',
  44908. vec4: 'vec4<f32>',
  44909. ivec4: 'vec4<i32>',
  44910. uvec4: 'vec4<u32>',
  44911. bvec4: 'vec4<bool>',
  44912. mat2: 'mat2x2<f32>',
  44913. mat3: 'mat3x3<f32>',
  44914. mat4: 'mat4x4<f32>'
  44915. };
  44916. const wgslCodeCache = {};
  44917. const wgslPolyfill = {
  44918. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44919. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44920. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44921. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44922. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44923. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44924. 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 ); }' ),
  44925. 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 ); }' ),
  44926. 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 ); }' ),
  44927. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  44928. 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 ); }' ),
  44929. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  44930. biquadraticTexture: new CodeNode( /* wgsl */`
  44931. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  44932. let res = vec2f( iRes );
  44933. let uvScaled = coord * res;
  44934. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44935. // https://www.shadertoy.com/view/WtyXRy
  44936. let uv = uvWrapping - 0.5;
  44937. let iuv = floor( uv );
  44938. let f = fract( uv );
  44939. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44940. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44941. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44942. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44943. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44944. }
  44945. ` )
  44946. };
  44947. const wgslMethods = {
  44948. dFdx: 'dpdx',
  44949. dFdy: '- dpdy',
  44950. mod_float: 'tsl_mod_float',
  44951. mod_vec2: 'tsl_mod_vec2',
  44952. mod_vec3: 'tsl_mod_vec3',
  44953. mod_vec4: 'tsl_mod_vec4',
  44954. equals_bool: 'tsl_equals_bool',
  44955. equals_bvec2: 'tsl_equals_bvec2',
  44956. equals_bvec3: 'tsl_equals_bvec3',
  44957. equals_bvec4: 'tsl_equals_bvec4',
  44958. inversesqrt: 'inverseSqrt',
  44959. bitcast: 'bitcast<f32>'
  44960. };
  44961. // WebGPU issue: does not support pow() with negative base on Windows
  44962. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  44963. 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 ); }' );
  44964. 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 ] );
  44965. 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 ] );
  44966. 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 ] );
  44967. wgslMethods.pow_float = 'tsl_pow_float';
  44968. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44969. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44970. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44971. }
  44972. //
  44973. let diagnostics = '';
  44974. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  44975. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44976. }
  44977. /**
  44978. * A node builder targeting WGSL.
  44979. *
  44980. * This module generates WGSL shader code from node materials and also
  44981. * generates the respective bindings and vertex buffer definitions. These
  44982. * data are later used by the renderer to create render and compute pipelines
  44983. * for render objects.
  44984. *
  44985. * @augments NodeBuilder
  44986. */
  44987. class WGSLNodeBuilder extends NodeBuilder {
  44988. /**
  44989. * Constructs a new WGSL node builder renderer.
  44990. *
  44991. * @param {Object3D} object - The 3D object.
  44992. * @param {Renderer} renderer - The renderer.
  44993. */
  44994. constructor( object, renderer ) {
  44995. super( object, renderer, new WGSLNodeParser() );
  44996. /**
  44997. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  44998. * another dictionary which manages UBOs per group ('render','frame','object').
  44999. *
  45000. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  45001. */
  45002. this.uniformGroups = {};
  45003. /**
  45004. * A dictionary that holds for each shader stage a Map of builtins.
  45005. *
  45006. * @type {Object<string,Map<string,Object>>}
  45007. */
  45008. this.builtins = {};
  45009. /**
  45010. * A dictionary that holds for each shader stage a Set of directives.
  45011. *
  45012. * @type {Object<string,Set<string>>}
  45013. */
  45014. this.directives = {};
  45015. /**
  45016. * A map for managing scope arrays. Only relevant for when using
  45017. * {@link WorkgroupInfoNode} in context of compute shaders.
  45018. *
  45019. * @type {Map<string,Object>}
  45020. */
  45021. this.scopedArrays = new Map();
  45022. }
  45023. /**
  45024. * Checks if the given texture requires a manual conversion to the working color space.
  45025. *
  45026. * @param {Texture} texture - The texture to check.
  45027. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  45028. */
  45029. needsToWorkingColorSpace( texture ) {
  45030. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  45031. }
  45032. /**
  45033. * Generates the WGSL snippet for sampled textures.
  45034. *
  45035. * @private
  45036. * @param {Texture} texture - The texture.
  45037. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45038. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45039. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45040. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45041. * @return {string} The WGSL snippet.
  45042. */
  45043. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45044. if ( shaderStage === 'fragment' ) {
  45045. if ( depthSnippet ) {
  45046. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  45047. } else {
  45048. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  45049. }
  45050. } else if ( this.isFilteredTexture( texture ) ) {
  45051. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  45052. } else {
  45053. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  45054. }
  45055. }
  45056. /**
  45057. * Generates the WGSL snippet when sampling video textures.
  45058. *
  45059. * @private
  45060. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45061. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45062. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45063. * @return {string} The WGSL snippet.
  45064. */
  45065. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  45066. if ( shaderStage === 'fragment' ) {
  45067. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  45068. } else {
  45069. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  45070. }
  45071. }
  45072. /**
  45073. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45074. *
  45075. * @private
  45076. * @param {Texture} texture - The texture.
  45077. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45078. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45079. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45080. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45081. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45082. * @return {string} The WGSL snippet.
  45083. */
  45084. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45085. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  45086. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  45087. } else if ( this.isFilteredTexture( texture ) ) {
  45088. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  45089. } else {
  45090. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  45091. }
  45092. }
  45093. /**
  45094. * Generates a wrap function used in context of textures.
  45095. *
  45096. * @param {Texture} texture - The texture to generate the function for.
  45097. * @return {string} The name of the generated function.
  45098. */
  45099. generateWrapFunction( texture ) {
  45100. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  45101. let nodeCode = wgslCodeCache[ functionName ];
  45102. if ( nodeCode === undefined ) {
  45103. const includes = [];
  45104. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  45105. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  45106. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  45107. const addWrapSnippet = ( wrap, axis ) => {
  45108. if ( wrap === RepeatWrapping ) {
  45109. includes.push( wgslPolyfill.repeatWrapping_float );
  45110. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  45111. } else if ( wrap === ClampToEdgeWrapping ) {
  45112. includes.push( wgslPolyfill.clampWrapping_float );
  45113. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  45114. } else if ( wrap === MirroredRepeatWrapping ) {
  45115. includes.push( wgslPolyfill.mirrorWrapping_float );
  45116. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  45117. } else {
  45118. code += `\t\tcoord.${ axis }`;
  45119. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  45120. }
  45121. };
  45122. addWrapSnippet( texture.wrapS, 'x' );
  45123. code += ',\n';
  45124. addWrapSnippet( texture.wrapT, 'y' );
  45125. if ( texture.isData3DTexture ) {
  45126. code += ',\n';
  45127. addWrapSnippet( texture.wrapR, 'z' );
  45128. }
  45129. code += '\n\t);\n\n}\n';
  45130. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  45131. }
  45132. nodeCode.build( this );
  45133. return functionName;
  45134. }
  45135. /**
  45136. * Generates the array declaration string.
  45137. *
  45138. * @param {string} type - The type.
  45139. * @param {?number} [count] - The count.
  45140. * @return {string} The generated value as a shader string.
  45141. */
  45142. generateArrayDeclaration( type, count ) {
  45143. return `array< ${ this.getType( type ) }, ${ count } >`;
  45144. }
  45145. /**
  45146. * Generates a WGSL variable that holds the texture dimension of the given texture.
  45147. * It also returns information about the the number of layers (elements) of an arrayed
  45148. * texture as well as the cube face count of cube textures.
  45149. *
  45150. * @param {Texture} texture - The texture to generate the function for.
  45151. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45152. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45153. * @return {string} The name of the dimension variable.
  45154. */
  45155. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  45156. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  45157. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  45158. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  45159. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  45160. let textureDimensionsParams;
  45161. let dimensionType;
  45162. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45163. const isMultisampled = primarySamples > 1;
  45164. if ( texture.isData3DTexture ) {
  45165. dimensionType = 'vec3<u32>';
  45166. } else {
  45167. // Regular 2D textures, depth textures, etc.
  45168. dimensionType = 'vec2<u32>';
  45169. }
  45170. // Build parameters string based on texture type and multisampling
  45171. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  45172. textureDimensionsParams = textureProperty;
  45173. } else {
  45174. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  45175. }
  45176. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  45177. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  45178. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  45179. textureData.arrayLayerCount = new VarNode(
  45180. new ExpressionNode(
  45181. `textureNumLayers(${textureProperty})`,
  45182. 'u32'
  45183. )
  45184. );
  45185. }
  45186. // For cube textures, we know it's always 6 faces
  45187. if ( texture.isTextureCube ) {
  45188. textureData.cubeFaceCount = new VarNode(
  45189. new ExpressionNode( '6u', 'u32' )
  45190. );
  45191. }
  45192. }
  45193. return textureDimensionNode.build( this );
  45194. }
  45195. /**
  45196. * Generates the WGSL snippet for a manual filtered texture.
  45197. *
  45198. * @param {Texture} texture - The texture.
  45199. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45200. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45201. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45202. * @return {string} The WGSL snippet.
  45203. */
  45204. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  45205. this._include( 'biquadraticTexture' );
  45206. const wrapFunction = this.generateWrapFunction( texture );
  45207. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45208. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  45209. }
  45210. /**
  45211. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  45212. * Since it's a lookup, no sampling or filtering is applied.
  45213. *
  45214. * @param {Texture} texture - The texture.
  45215. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45216. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45217. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45218. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45219. * @return {string} The WGSL snippet.
  45220. */
  45221. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  45222. const wrapFunction = this.generateWrapFunction( texture );
  45223. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45224. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  45225. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  45226. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  45227. }
  45228. /**
  45229. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  45230. *
  45231. * @param {Texture} texture - The texture.
  45232. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45233. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45234. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45235. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45236. * @return {string} The WGSL snippet.
  45237. */
  45238. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  45239. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  45240. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  45241. } else if ( depthSnippet ) {
  45242. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  45243. } else {
  45244. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  45245. }
  45246. }
  45247. /**
  45248. * Generates the WGSL snippet that writes a single texel to a texture.
  45249. *
  45250. * @param {Texture} texture - The texture.
  45251. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45252. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45253. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  45254. * @return {string} The WGSL snippet.
  45255. */
  45256. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  45257. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  45258. }
  45259. /**
  45260. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  45261. *
  45262. * @param {Texture} texture - The texture.
  45263. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  45264. */
  45265. isSampleCompare( texture ) {
  45266. return texture.isDepthTexture === true && texture.compareFunction !== null;
  45267. }
  45268. /**
  45269. * Returns `true` if the given texture is unfilterable.
  45270. *
  45271. * @param {Texture} texture - The texture.
  45272. * @return {boolean} Whether the given texture is unfilterable or not.
  45273. */
  45274. isUnfilterable( texture ) {
  45275. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  45276. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  45277. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  45278. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  45279. }
  45280. /**
  45281. * Generates the WGSL snippet for sampling/loading the given texture.
  45282. *
  45283. * @param {Texture} texture - The texture.
  45284. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45285. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45286. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45287. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45288. * @return {string} The WGSL snippet.
  45289. */
  45290. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45291. let snippet = null;
  45292. if ( texture.isVideoTexture === true ) {
  45293. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45294. } else if ( this.isUnfilterable( texture ) ) {
  45295. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  45296. } else {
  45297. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  45298. }
  45299. return snippet;
  45300. }
  45301. /**
  45302. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  45303. *
  45304. * @param {Texture} texture - The texture.
  45305. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45306. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45307. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  45308. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45309. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45310. * @return {string} The WGSL snippet.
  45311. */
  45312. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45313. if ( shaderStage === 'fragment' ) {
  45314. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  45315. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45316. } else {
  45317. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  45318. }
  45319. }
  45320. /**
  45321. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  45322. * against a reference value.
  45323. *
  45324. * @param {Texture} texture - The texture.
  45325. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45326. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45327. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  45328. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45329. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45330. * @return {string} The WGSL snippet.
  45331. */
  45332. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45333. if ( shaderStage === 'fragment' ) {
  45334. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  45335. } else {
  45336. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45337. }
  45338. }
  45339. /**
  45340. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45341. *
  45342. * @param {Texture} texture - The texture.
  45343. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45344. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45345. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45346. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45347. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45348. * @return {string} The WGSL snippet.
  45349. */
  45350. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45351. let snippet = null;
  45352. if ( texture.isVideoTexture === true ) {
  45353. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45354. } else {
  45355. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  45356. }
  45357. return snippet;
  45358. }
  45359. /**
  45360. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  45361. *
  45362. * @param {Texture} texture - The texture.
  45363. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45364. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45365. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  45366. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45367. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45368. * @return {string} The WGSL snippet.
  45369. */
  45370. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45371. if ( shaderStage === 'fragment' ) {
  45372. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  45373. } else {
  45374. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  45375. }
  45376. }
  45377. /**
  45378. * Returns a WGSL snippet that represents the property name of the given node.
  45379. *
  45380. * @param {Node} node - The node.
  45381. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45382. * @return {string} The property name.
  45383. */
  45384. getPropertyName( node, shaderStage = this.shaderStage ) {
  45385. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  45386. if ( shaderStage === 'vertex' ) {
  45387. return `varyings.${ node.name }`;
  45388. }
  45389. } else if ( node.isNodeUniform === true ) {
  45390. const name = node.name;
  45391. const type = node.type;
  45392. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  45393. return name;
  45394. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  45395. if ( this.isCustomStruct( node ) ) {
  45396. return name;
  45397. }
  45398. return name + '.value';
  45399. } else {
  45400. return node.groupNode.name + '.' + name;
  45401. }
  45402. }
  45403. return super.getPropertyName( node );
  45404. }
  45405. /**
  45406. * Returns the output struct name.
  45407. *
  45408. * @return {string} The name of the output struct.
  45409. */
  45410. getOutputStructName() {
  45411. return 'output';
  45412. }
  45413. /**
  45414. * Returns uniforms group count for the given shader stage.
  45415. *
  45416. * @private
  45417. * @param {string} shaderStage - The shader stage.
  45418. * @return {number} The uniforms group count for the given shader stage.
  45419. */
  45420. _getUniformGroupCount( shaderStage ) {
  45421. return Object.keys( this.uniforms[ shaderStage ] ).length;
  45422. }
  45423. /**
  45424. * Returns the native shader operator name for a given generic name.
  45425. *
  45426. * @param {string} op - The operator name to resolve.
  45427. * @return {string} The resolved operator name.
  45428. */
  45429. getFunctionOperator( op ) {
  45430. const fnOp = wgslFnOpLib[ op ];
  45431. if ( fnOp !== undefined ) {
  45432. this._include( fnOp );
  45433. return fnOp;
  45434. }
  45435. return null;
  45436. }
  45437. /**
  45438. * Returns the node access for the given node and shader stage.
  45439. *
  45440. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45441. * @param {string} shaderStage - The shader stage.
  45442. * @return {string} The node access.
  45443. */
  45444. getNodeAccess( node, shaderStage ) {
  45445. if ( shaderStage !== 'compute' )
  45446. return NodeAccess.READ_ONLY;
  45447. return node.access;
  45448. }
  45449. /**
  45450. * Returns A WGSL snippet representing the storage access.
  45451. *
  45452. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45453. * @param {string} shaderStage - The shader stage.
  45454. * @return {string} The WGSL snippet representing the storage access.
  45455. */
  45456. getStorageAccess( node, shaderStage ) {
  45457. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  45458. }
  45459. /**
  45460. * This method is one of the more important ones since it's responsible
  45461. * for generating a matching binding instance for the given uniform node.
  45462. *
  45463. * These bindings are later used in the renderer to create bind groups
  45464. * and layouts.
  45465. *
  45466. * @param {UniformNode} node - The uniform node.
  45467. * @param {string} type - The node data type.
  45468. * @param {string} shaderStage - The shader stage.
  45469. * @param {?string} [name=null] - An optional uniform name.
  45470. * @return {NodeUniform} The node uniform object.
  45471. */
  45472. getUniformFromNode( node, type, shaderStage, name = null ) {
  45473. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45474. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45475. if ( nodeData.uniformGPU === undefined ) {
  45476. let uniformGPU;
  45477. const group = node.groupNode;
  45478. const groupName = group.name;
  45479. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45480. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  45481. let texture = null;
  45482. const access = this.getNodeAccess( node, shaderStage );
  45483. if ( type === 'texture' || type === 'storageTexture' ) {
  45484. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  45485. } else if ( type === 'cubeTexture' ) {
  45486. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  45487. } else if ( type === 'texture3D' ) {
  45488. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  45489. }
  45490. texture.store = node.isStorageTextureNode === true;
  45491. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45492. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  45493. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  45494. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45495. bindings.push( sampler, texture );
  45496. uniformGPU = [ sampler, texture ];
  45497. } else {
  45498. bindings.push( texture );
  45499. uniformGPU = [ texture ];
  45500. }
  45501. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  45502. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  45503. const buffer = new bufferClass( node, group );
  45504. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45505. bindings.push( buffer );
  45506. uniformGPU = buffer;
  45507. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  45508. } else {
  45509. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45510. let uniformsGroup = uniformsStage[ groupName ];
  45511. if ( uniformsGroup === undefined ) {
  45512. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45513. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45514. uniformsStage[ groupName ] = uniformsGroup;
  45515. bindings.push( uniformsGroup );
  45516. }
  45517. uniformGPU = this.getNodeUniform( uniformNode, type );
  45518. uniformsGroup.addUniform( uniformGPU );
  45519. }
  45520. nodeData.uniformGPU = uniformGPU;
  45521. }
  45522. return uniformNode;
  45523. }
  45524. /**
  45525. * This method should be used whenever builtins are required in nodes.
  45526. * The internal builtins data structure will make sure builtins are
  45527. * defined in the WGSL source.
  45528. *
  45529. * @param {string} name - The builtin name.
  45530. * @param {string} property - The property name.
  45531. * @param {string} type - The node data type.
  45532. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45533. * @return {string} The property name.
  45534. */
  45535. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  45536. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  45537. if ( map.has( name ) === false ) {
  45538. map.set( name, {
  45539. name,
  45540. property,
  45541. type
  45542. } );
  45543. }
  45544. return property;
  45545. }
  45546. /**
  45547. * Returns `true` if the given builtin is defined in the given shader stage.
  45548. *
  45549. * @param {string} name - The builtin name.
  45550. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45551. * @return {string} Whether the given builtin is defined in the given shader stage or not.
  45552. */
  45553. hasBuiltin( name, shaderStage = this.shaderStage ) {
  45554. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  45555. }
  45556. /**
  45557. * Returns the vertex index builtin.
  45558. *
  45559. * @return {string} The vertex index.
  45560. */
  45561. getVertexIndex() {
  45562. if ( this.shaderStage === 'vertex' ) {
  45563. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  45564. }
  45565. return 'vertexIndex';
  45566. }
  45567. /**
  45568. * Builds the given shader node.
  45569. *
  45570. * @param {ShaderNodeInternal} shaderNode - The shader node.
  45571. * @return {string} The WGSL function code.
  45572. */
  45573. buildFunctionCode( shaderNode ) {
  45574. const layout = shaderNode.layout;
  45575. const flowData = this.flowShaderNode( shaderNode );
  45576. const parameters = [];
  45577. for ( const input of layout.inputs ) {
  45578. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  45579. }
  45580. //
  45581. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  45582. ${ flowData.vars }
  45583. ${ flowData.code }
  45584. `;
  45585. if ( flowData.result ) {
  45586. code += `\treturn ${ flowData.result };\n`;
  45587. }
  45588. code += '\n}\n';
  45589. //
  45590. return code;
  45591. }
  45592. /**
  45593. * Returns the instance index builtin.
  45594. *
  45595. * @return {string} The instance index.
  45596. */
  45597. getInstanceIndex() {
  45598. if ( this.shaderStage === 'vertex' ) {
  45599. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  45600. }
  45601. return 'instanceIndex';
  45602. }
  45603. /**
  45604. * Returns the invocation local index builtin.
  45605. *
  45606. * @return {string} The invocation local index.
  45607. */
  45608. getInvocationLocalIndex() {
  45609. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  45610. }
  45611. /**
  45612. * Returns the subgroup size builtin.
  45613. *
  45614. * @return {string} The subgroup size.
  45615. */
  45616. getSubgroupSize() {
  45617. this.enableSubGroups();
  45618. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45619. }
  45620. /**
  45621. * Returns the invocation subgroup index builtin.
  45622. *
  45623. * @return {string} The invocation subgroup index.
  45624. */
  45625. getInvocationSubgroupIndex() {
  45626. this.enableSubGroups();
  45627. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  45628. }
  45629. /**
  45630. * Returns the subgroup index builtin.
  45631. *
  45632. * @return {string} The subgroup index.
  45633. */
  45634. getSubgroupIndex() {
  45635. this.enableSubGroups();
  45636. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  45637. }
  45638. /**
  45639. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  45640. *
  45641. * @return {null} Null.
  45642. */
  45643. getDrawIndex() {
  45644. return null;
  45645. }
  45646. /**
  45647. * Returns the front facing builtin.
  45648. *
  45649. * @return {string} The front facing builtin.
  45650. */
  45651. getFrontFacing() {
  45652. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  45653. }
  45654. /**
  45655. * Returns the frag coord builtin.
  45656. *
  45657. * @return {string} The frag coord builtin.
  45658. */
  45659. getFragCoord() {
  45660. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  45661. }
  45662. /**
  45663. * Returns the frag depth builtin.
  45664. *
  45665. * @return {string} The frag depth builtin.
  45666. */
  45667. getFragDepth() {
  45668. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  45669. }
  45670. /**
  45671. * Returns the clip distances builtin.
  45672. *
  45673. * @return {string} The clip distances builtin.
  45674. */
  45675. getClipDistance() {
  45676. return 'varyings.hw_clip_distances';
  45677. }
  45678. /**
  45679. * Whether to flip texture data along its vertical axis or not.
  45680. *
  45681. * @return {boolean} Returns always `false` in context of WGSL.
  45682. */
  45683. isFlipY() {
  45684. return false;
  45685. }
  45686. /**
  45687. * Enables the given directive for the given shader stage.
  45688. *
  45689. * @param {string} name - The directive name.
  45690. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  45691. */
  45692. enableDirective( name, shaderStage = this.shaderStage ) {
  45693. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  45694. stage.add( name );
  45695. }
  45696. /**
  45697. * Returns the directives of the given shader stage as a WGSL string.
  45698. *
  45699. * @param {string} shaderStage - The shader stage.
  45700. * @return {string} A WGSL snippet that enables the directives of the given stage.
  45701. */
  45702. getDirectives( shaderStage ) {
  45703. const snippets = [];
  45704. const directives = this.directives[ shaderStage ];
  45705. if ( directives !== undefined ) {
  45706. for ( const directive of directives ) {
  45707. snippets.push( `enable ${directive};` );
  45708. }
  45709. }
  45710. return snippets.join( '\n' );
  45711. }
  45712. /**
  45713. * Enables the 'subgroups' directive.
  45714. */
  45715. enableSubGroups() {
  45716. this.enableDirective( 'subgroups' );
  45717. }
  45718. /**
  45719. * Enables the 'subgroups-f16' directive.
  45720. */
  45721. enableSubgroupsF16() {
  45722. this.enableDirective( 'subgroups-f16' );
  45723. }
  45724. /**
  45725. * Enables the 'clip_distances' directive.
  45726. */
  45727. enableClipDistances() {
  45728. this.enableDirective( 'clip_distances' );
  45729. }
  45730. /**
  45731. * Enables the 'f16' directive.
  45732. */
  45733. enableShaderF16() {
  45734. this.enableDirective( 'f16' );
  45735. }
  45736. /**
  45737. * Enables the 'dual_source_blending' directive.
  45738. */
  45739. enableDualSourceBlending() {
  45740. this.enableDirective( 'dual_source_blending' );
  45741. }
  45742. /**
  45743. * Enables hardware clipping.
  45744. *
  45745. * @param {string} planeCount - The clipping plane count.
  45746. */
  45747. enableHardwareClipping( planeCount ) {
  45748. this.enableClipDistances();
  45749. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  45750. }
  45751. /**
  45752. * Returns the builtins of the given shader stage as a WGSL string.
  45753. *
  45754. * @param {string} shaderStage - The shader stage.
  45755. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  45756. */
  45757. getBuiltins( shaderStage ) {
  45758. const snippets = [];
  45759. const builtins = this.builtins[ shaderStage ];
  45760. if ( builtins !== undefined ) {
  45761. for ( const { name, property, type } of builtins.values() ) {
  45762. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  45763. }
  45764. }
  45765. return snippets.join( ',\n\t' );
  45766. }
  45767. /**
  45768. * This method should be used when a new scoped buffer is used in context of
  45769. * compute shaders. It adds the array to the internal data structure which is
  45770. * later used to generate the respective WGSL.
  45771. *
  45772. * @param {string} name - The array name.
  45773. * @param {string} scope - The scope.
  45774. * @param {string} bufferType - The buffer type.
  45775. * @param {string} bufferCount - The buffer count.
  45776. * @return {string} The array name.
  45777. */
  45778. getScopedArray( name, scope, bufferType, bufferCount ) {
  45779. if ( this.scopedArrays.has( name ) === false ) {
  45780. this.scopedArrays.set( name, {
  45781. name,
  45782. scope,
  45783. bufferType,
  45784. bufferCount
  45785. } );
  45786. }
  45787. return name;
  45788. }
  45789. /**
  45790. * Returns the scoped arrays of the given shader stage as a WGSL string.
  45791. *
  45792. * @param {string} shaderStage - The shader stage.
  45793. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  45794. * Returns `undefined` when used in the vertex or fragment stage.
  45795. */
  45796. getScopedArrays( shaderStage ) {
  45797. if ( shaderStage !== 'compute' ) {
  45798. return;
  45799. }
  45800. const snippets = [];
  45801. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  45802. const type = this.getType( bufferType );
  45803. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  45804. }
  45805. return snippets.join( '\n' );
  45806. }
  45807. /**
  45808. * Returns the shader attributes of the given shader stage as a WGSL string.
  45809. *
  45810. * @param {string} shaderStage - The shader stage.
  45811. * @return {string} The WGSL snippet that defines the shader attributes.
  45812. */
  45813. getAttributes( shaderStage ) {
  45814. const snippets = [];
  45815. if ( shaderStage === 'compute' ) {
  45816. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  45817. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  45818. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  45819. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  45820. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  45821. this.enableDirective( 'subgroups', shaderStage );
  45822. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45823. }
  45824. }
  45825. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45826. const builtins = this.getBuiltins( 'attribute' );
  45827. if ( builtins ) snippets.push( builtins );
  45828. const attributes = this.getAttributesArray();
  45829. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  45830. const attribute = attributes[ index ];
  45831. const name = attribute.name;
  45832. const type = this.getType( attribute.type );
  45833. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  45834. }
  45835. }
  45836. return snippets.join( ',\n\t' );
  45837. }
  45838. /**
  45839. * Returns the members of the given struct type node as a WGSL string.
  45840. *
  45841. * @param {StructTypeNode} struct - The struct type node.
  45842. * @return {string} The WGSL snippet that defines the struct members.
  45843. */
  45844. getStructMembers( struct ) {
  45845. const snippets = [];
  45846. for ( const member of struct.members ) {
  45847. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  45848. let type = this.getType( member.type );
  45849. if ( member.atomic ) {
  45850. type = 'atomic< ' + type + ' >';
  45851. }
  45852. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  45853. }
  45854. return snippets.join( ',\n' );
  45855. }
  45856. /**
  45857. * Returns the structs of the given shader stage as a WGSL string.
  45858. *
  45859. * @param {string} shaderStage - The shader stage.
  45860. * @return {string} The WGSL snippet that defines the structs.
  45861. */
  45862. getStructs( shaderStage ) {
  45863. let result = '';
  45864. const structs = this.structs[ shaderStage ];
  45865. if ( structs.length > 0 ) {
  45866. const snippets = [];
  45867. for ( const struct of structs ) {
  45868. let snippet = `struct ${ struct.name } {\n`;
  45869. snippet += this.getStructMembers( struct );
  45870. snippet += '\n};';
  45871. snippets.push( snippet );
  45872. }
  45873. result = '\n' + snippets.join( '\n\n' ) + '\n';
  45874. }
  45875. return result;
  45876. }
  45877. /**
  45878. * Returns a WGSL string representing a variable.
  45879. *
  45880. * @param {string} type - The variable's type.
  45881. * @param {string} name - The variable's name.
  45882. * @param {?number} [count=null] - The array length.
  45883. * @return {string} The WGSL snippet that defines a variable.
  45884. */
  45885. getVar( type, name, count = null ) {
  45886. let snippet = `var ${ name } : `;
  45887. if ( count !== null ) {
  45888. snippet += this.generateArrayDeclaration( type, count );
  45889. } else {
  45890. snippet += this.getType( type );
  45891. }
  45892. return snippet;
  45893. }
  45894. /**
  45895. * Returns the variables of the given shader stage as a WGSL string.
  45896. *
  45897. * @param {string} shaderStage - The shader stage.
  45898. * @return {string} The WGSL snippet that defines the variables.
  45899. */
  45900. getVars( shaderStage ) {
  45901. const snippets = [];
  45902. const vars = this.vars[ shaderStage ];
  45903. if ( vars !== undefined ) {
  45904. for ( const variable of vars ) {
  45905. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45906. }
  45907. }
  45908. return `\n${ snippets.join( '\n' ) }\n`;
  45909. }
  45910. /**
  45911. * Returns the varyings of the given shader stage as a WGSL string.
  45912. *
  45913. * @param {string} shaderStage - The shader stage.
  45914. * @return {string} The WGSL snippet that defines the varyings.
  45915. */
  45916. getVaryings( shaderStage ) {
  45917. const snippets = [];
  45918. if ( shaderStage === 'vertex' ) {
  45919. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  45920. }
  45921. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  45922. const varyings = this.varyings;
  45923. const vars = this.vars[ shaderStage ];
  45924. for ( let index = 0; index < varyings.length; index ++ ) {
  45925. const varying = varyings[ index ];
  45926. if ( varying.needsInterpolation ) {
  45927. let attributesSnippet = `@location( ${index} )`;
  45928. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  45929. attributesSnippet += ' @interpolate( flat )';
  45930. }
  45931. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  45932. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  45933. vars.push( varying );
  45934. }
  45935. }
  45936. }
  45937. const builtins = this.getBuiltins( shaderStage );
  45938. if ( builtins ) snippets.push( builtins );
  45939. const code = snippets.join( ',\n\t' );
  45940. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  45941. }
  45942. isCustomStruct( nodeUniform ) {
  45943. return nodeUniform.value.isStorageBufferAttribute && nodeUniform.node.structTypeNode !== null;
  45944. }
  45945. /**
  45946. * Returns the uniforms of the given shader stage as a WGSL string.
  45947. *
  45948. * @param {string} shaderStage - The shader stage.
  45949. * @return {string} The WGSL snippet that defines the uniforms.
  45950. */
  45951. getUniforms( shaderStage ) {
  45952. const uniforms = this.uniforms[ shaderStage ];
  45953. const bindingSnippets = [];
  45954. const bufferSnippets = [];
  45955. const structSnippets = [];
  45956. const uniformGroups = {};
  45957. for ( const uniform of uniforms ) {
  45958. const groupName = uniform.groupNode.name;
  45959. const uniformIndexes = this.bindingsIndexes[ groupName ];
  45960. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  45961. const texture = uniform.node.value;
  45962. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  45963. if ( this.isSampleCompare( texture ) ) {
  45964. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  45965. } else {
  45966. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  45967. }
  45968. }
  45969. let textureType;
  45970. let multisampled = '';
  45971. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45972. if ( primarySamples > 1 ) {
  45973. multisampled = '_multisampled';
  45974. }
  45975. if ( texture.isCubeTexture === true ) {
  45976. textureType = 'texture_cube<f32>';
  45977. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45978. textureType = 'texture_2d_array<f32>';
  45979. } else if ( texture.isDepthTexture === true ) {
  45980. textureType = `texture_depth${multisampled}_2d`;
  45981. } else if ( texture.isVideoTexture === true ) {
  45982. textureType = 'texture_external';
  45983. } else if ( texture.isData3DTexture === true ) {
  45984. textureType = 'texture_3d<f32>';
  45985. } else if ( uniform.node.isStorageTextureNode === true ) {
  45986. const format = getFormat( texture );
  45987. const access = this.getStorageAccess( uniform.node, shaderStage );
  45988. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  45989. } else {
  45990. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  45991. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  45992. }
  45993. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  45994. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  45995. const bufferNode = uniform.node;
  45996. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  45997. const bufferCount = bufferNode.bufferCount;
  45998. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  45999. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  46000. if ( this.isCustomStruct( uniform ) ) {
  46001. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  46002. } else {
  46003. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  46004. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  46005. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  46006. }
  46007. } else {
  46008. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  46009. const groupName = uniform.groupNode.name;
  46010. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  46011. index: uniformIndexes.binding ++,
  46012. id: uniformIndexes.group,
  46013. snippets: []
  46014. } );
  46015. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  46016. }
  46017. }
  46018. for ( const name in uniformGroups ) {
  46019. const group = uniformGroups[ name ];
  46020. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  46021. }
  46022. let code = bindingSnippets.join( '\n' );
  46023. code += bufferSnippets.join( '\n' );
  46024. code += structSnippets.join( '\n' );
  46025. return code;
  46026. }
  46027. /**
  46028. * Controls the code build of the shader stages.
  46029. */
  46030. buildCode() {
  46031. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46032. this.sortBindingGroups();
  46033. for ( const shaderStage in shadersData ) {
  46034. this.shaderStage = shaderStage;
  46035. const stageData = shadersData[ shaderStage ];
  46036. stageData.uniforms = this.getUniforms( shaderStage );
  46037. stageData.attributes = this.getAttributes( shaderStage );
  46038. stageData.varyings = this.getVaryings( shaderStage );
  46039. stageData.structs = this.getStructs( shaderStage );
  46040. stageData.vars = this.getVars( shaderStage );
  46041. stageData.codes = this.getCodes( shaderStage );
  46042. stageData.directives = this.getDirectives( shaderStage );
  46043. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  46044. //
  46045. let flow = '// code\n\n';
  46046. flow += this.flowCode[ shaderStage ];
  46047. const flowNodes = this.flowNodes[ shaderStage ];
  46048. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46049. const outputNode = mainNode.outputNode;
  46050. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  46051. for ( const node of flowNodes ) {
  46052. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46053. const slotName = node.name;
  46054. if ( slotName ) {
  46055. if ( flow.length > 0 ) flow += '\n';
  46056. flow += `\t// flow -> ${ slotName }\n`;
  46057. }
  46058. flow += `${ flowSlotData.code }\n\t`;
  46059. if ( node === mainNode && shaderStage !== 'compute' ) {
  46060. flow += '// result\n\n\t';
  46061. if ( shaderStage === 'vertex' ) {
  46062. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  46063. } else if ( shaderStage === 'fragment' ) {
  46064. if ( isOutputStruct ) {
  46065. stageData.returnType = outputNode.getNodeType( this );
  46066. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  46067. flow += `return ${ flowSlotData.result };`;
  46068. } else {
  46069. let structSnippet = '\t@location(0) color: vec4<f32>';
  46070. const builtins = this.getBuiltins( 'output' );
  46071. if ( builtins ) structSnippet += ',\n\t' + builtins;
  46072. stageData.returnType = 'OutputStruct';
  46073. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  46074. stageData.structs += '\nvar<private> output : OutputStruct;';
  46075. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  46076. }
  46077. }
  46078. }
  46079. }
  46080. stageData.flow = flow;
  46081. }
  46082. this.shaderStage = null;
  46083. if ( this.material !== null ) {
  46084. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  46085. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  46086. } else {
  46087. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  46088. }
  46089. }
  46090. /**
  46091. * Returns the native shader method name for a given generic name.
  46092. *
  46093. * @param {string} method - The method name to resolve.
  46094. * @param {string} [output=null] - An optional output.
  46095. * @return {string} The resolved WGSL method name.
  46096. */
  46097. getMethod( method, output = null ) {
  46098. let wgslMethod;
  46099. if ( output !== null ) {
  46100. wgslMethod = this._getWGSLMethod( method + '_' + output );
  46101. }
  46102. if ( wgslMethod === undefined ) {
  46103. wgslMethod = this._getWGSLMethod( method );
  46104. }
  46105. return wgslMethod || method;
  46106. }
  46107. /**
  46108. * Returns the WGSL type of the given node data type.
  46109. *
  46110. * @param {string} type - The node data type.
  46111. * @return {string} The WGSL type.
  46112. */
  46113. getType( type ) {
  46114. return wgslTypeLib[ type ] || type;
  46115. }
  46116. /**
  46117. * Whether the requested feature is available or not.
  46118. *
  46119. * @param {string} name - The requested feature.
  46120. * @return {boolean} Whether the requested feature is supported or not.
  46121. */
  46122. isAvailable( name ) {
  46123. let result = supports[ name ];
  46124. if ( result === undefined ) {
  46125. if ( name === 'float32Filterable' ) {
  46126. result = this.renderer.hasFeature( 'float32-filterable' );
  46127. } else if ( name === 'clipDistance' ) {
  46128. result = this.renderer.hasFeature( 'clip-distances' );
  46129. }
  46130. supports[ name ] = result;
  46131. }
  46132. return result;
  46133. }
  46134. /**
  46135. * Returns the native shader method name for a given generic name.
  46136. *
  46137. * @private
  46138. * @param {string} method - The method name to resolve.
  46139. * @return {string} The resolved WGSL method name.
  46140. */
  46141. _getWGSLMethod( method ) {
  46142. if ( wgslPolyfill[ method ] !== undefined ) {
  46143. this._include( method );
  46144. }
  46145. return wgslMethods[ method ];
  46146. }
  46147. /**
  46148. * Includes the given method name into the current
  46149. * function node.
  46150. *
  46151. * @private
  46152. * @param {string} name - The method name to include.
  46153. * @return {CodeNode} The respective code node.
  46154. */
  46155. _include( name ) {
  46156. const codeNode = wgslPolyfill[ name ];
  46157. codeNode.build( this );
  46158. if ( this.currentFunctionNode !== null ) {
  46159. this.currentFunctionNode.includes.push( codeNode );
  46160. }
  46161. return codeNode;
  46162. }
  46163. /**
  46164. * Returns a WGSL vertex shader based on the given shader data.
  46165. *
  46166. * @private
  46167. * @param {Object} shaderData - The shader data.
  46168. * @return {string} The vertex shader.
  46169. */
  46170. _getWGSLVertexCode( shaderData ) {
  46171. return `${ this.getSignature() }
  46172. // directives
  46173. ${shaderData.directives}
  46174. // structs
  46175. ${shaderData.structs}
  46176. // uniforms
  46177. ${shaderData.uniforms}
  46178. // varyings
  46179. ${shaderData.varyings}
  46180. var<private> varyings : VaryingsStruct;
  46181. // codes
  46182. ${shaderData.codes}
  46183. @vertex
  46184. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  46185. // vars
  46186. ${shaderData.vars}
  46187. // flow
  46188. ${shaderData.flow}
  46189. return varyings;
  46190. }
  46191. `;
  46192. }
  46193. /**
  46194. * Returns a WGSL fragment shader based on the given shader data.
  46195. *
  46196. * @private
  46197. * @param {Object} shaderData - The shader data.
  46198. * @return {string} The vertex shader.
  46199. */
  46200. _getWGSLFragmentCode( shaderData ) {
  46201. return `${ this.getSignature() }
  46202. // global
  46203. ${ diagnostics }
  46204. // structs
  46205. ${shaderData.structs}
  46206. // uniforms
  46207. ${shaderData.uniforms}
  46208. // codes
  46209. ${shaderData.codes}
  46210. @fragment
  46211. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  46212. // vars
  46213. ${shaderData.vars}
  46214. // flow
  46215. ${shaderData.flow}
  46216. }
  46217. `;
  46218. }
  46219. /**
  46220. * Returns a WGSL compute shader based on the given shader data.
  46221. *
  46222. * @private
  46223. * @param {Object} shaderData - The shader data.
  46224. * @param {string} workgroupSize - The workgroup size.
  46225. * @return {string} The vertex shader.
  46226. */
  46227. _getWGSLComputeCode( shaderData, workgroupSize ) {
  46228. return `${ this.getSignature() }
  46229. // directives
  46230. ${shaderData.directives}
  46231. // system
  46232. var<private> instanceIndex : u32;
  46233. // locals
  46234. ${shaderData.scopedArrays}
  46235. // structs
  46236. ${shaderData.structs}
  46237. // uniforms
  46238. ${shaderData.uniforms}
  46239. // codes
  46240. ${shaderData.codes}
  46241. @compute @workgroup_size( ${workgroupSize} )
  46242. fn main( ${shaderData.attributes} ) {
  46243. // system
  46244. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  46245. // vars
  46246. ${shaderData.vars}
  46247. // flow
  46248. ${shaderData.flow}
  46249. }
  46250. `;
  46251. }
  46252. /**
  46253. * Returns a WGSL struct based on the given name and variables.
  46254. *
  46255. * @private
  46256. * @param {string} name - The struct name.
  46257. * @param {string} vars - The struct variables.
  46258. * @return {string} The WGSL snippet representing a struct.
  46259. */
  46260. _getWGSLStruct( name, vars ) {
  46261. return `
  46262. struct ${name} {
  46263. ${vars}
  46264. };`;
  46265. }
  46266. /**
  46267. * Returns a WGSL struct binding.
  46268. *
  46269. * @private
  46270. * @param {string} name - The struct name.
  46271. * @param {string} vars - The struct variables.
  46272. * @param {string} access - The access.
  46273. * @param {number} [binding=0] - The binding index.
  46274. * @param {number} [group=0] - The group index.
  46275. * @return {string} The WGSL snippet representing a struct binding.
  46276. */
  46277. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  46278. const structName = name + 'Struct';
  46279. const structSnippet = this._getWGSLStruct( structName, vars );
  46280. return `${structSnippet}
  46281. @binding( ${ binding } ) @group( ${ group } )
  46282. var<${access}> ${ name } : ${ structName };`;
  46283. }
  46284. }
  46285. /**
  46286. * A WebGPU backend utility module with common helpers.
  46287. *
  46288. * @private
  46289. */
  46290. class WebGPUUtils {
  46291. /**
  46292. * Constructs a new utility object.
  46293. *
  46294. * @param {WebGPUBackend} backend - The WebGPU backend.
  46295. */
  46296. constructor( backend ) {
  46297. /**
  46298. * A reference to the WebGPU backend.
  46299. *
  46300. * @type {WebGPUBackend}
  46301. */
  46302. this.backend = backend;
  46303. }
  46304. /**
  46305. * Returns the depth/stencil GPU format for the given render context.
  46306. *
  46307. * @param {RenderContext} renderContext - The render context.
  46308. * @return {string} The depth/stencil GPU texture format.
  46309. */
  46310. getCurrentDepthStencilFormat( renderContext ) {
  46311. let format;
  46312. if ( renderContext.depthTexture !== null ) {
  46313. format = this.getTextureFormatGPU( renderContext.depthTexture );
  46314. } else if ( renderContext.depth && renderContext.stencil ) {
  46315. format = GPUTextureFormat.Depth24PlusStencil8;
  46316. } else if ( renderContext.depth ) {
  46317. format = GPUTextureFormat.Depth24Plus;
  46318. }
  46319. return format;
  46320. }
  46321. /**
  46322. * Returns the GPU format for the given texture.
  46323. *
  46324. * @param {Texture} texture - The texture.
  46325. * @return {string} The GPU texture format.
  46326. */
  46327. getTextureFormatGPU( texture ) {
  46328. return this.backend.get( texture ).format;
  46329. }
  46330. /**
  46331. * Returns an object that defines the multi-sampling state of the given texture.
  46332. *
  46333. * @param {Texture} texture - The texture.
  46334. * @return {Object} The multi-sampling state.
  46335. */
  46336. getTextureSampleData( texture ) {
  46337. let samples;
  46338. if ( texture.isFramebufferTexture ) {
  46339. samples = 1;
  46340. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  46341. const renderer = this.backend.renderer;
  46342. const renderTarget = renderer.getRenderTarget();
  46343. samples = renderTarget ? renderTarget.samples : renderer.samples;
  46344. } else if ( texture.renderTarget ) {
  46345. samples = texture.renderTarget.samples;
  46346. }
  46347. samples = samples || 1;
  46348. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  46349. const primarySamples = isMSAA ? 1 : samples;
  46350. return { samples, primarySamples, isMSAA };
  46351. }
  46352. /**
  46353. * Returns the default color attachment's GPU format of the current render context.
  46354. *
  46355. * @param {RenderContext} renderContext - The render context.
  46356. * @return {string} The GPU texture format of the default color attachment.
  46357. */
  46358. getCurrentColorFormat( renderContext ) {
  46359. let format;
  46360. if ( renderContext.textures !== null ) {
  46361. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  46362. } else {
  46363. format = this.getPreferredCanvasFormat(); // default context format
  46364. }
  46365. return format;
  46366. }
  46367. /**
  46368. * Returns the output color space of the current render context.
  46369. *
  46370. * @param {RenderContext} renderContext - The render context.
  46371. * @return {string} The output color space.
  46372. */
  46373. getCurrentColorSpace( renderContext ) {
  46374. if ( renderContext.textures !== null ) {
  46375. return renderContext.textures[ 0 ].colorSpace;
  46376. }
  46377. return this.backend.renderer.outputColorSpace;
  46378. }
  46379. /**
  46380. * Returns GPU primitive topology for the given object and material.
  46381. *
  46382. * @param {Object3D} object - The 3D object.
  46383. * @param {Material} material - The material.
  46384. * @return {string} The GPU primitive topology.
  46385. */
  46386. getPrimitiveTopology( object, material ) {
  46387. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  46388. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  46389. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  46390. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  46391. }
  46392. /**
  46393. * Returns a modified sample count from the given sample count value.
  46394. *
  46395. * That is required since WebGPU does not support arbitrary sample counts.
  46396. *
  46397. * @param {number} sampleCount - The input sample count.
  46398. * @return {number} The (potentially updated) output sample count.
  46399. */
  46400. getSampleCount( sampleCount ) {
  46401. let count = 1;
  46402. if ( sampleCount > 1 ) {
  46403. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  46404. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  46405. if ( count === 2 ) {
  46406. count = 4;
  46407. }
  46408. }
  46409. return count;
  46410. }
  46411. /**
  46412. * Returns the sample count of the given render context.
  46413. *
  46414. * @param {RenderContext} renderContext - The render context.
  46415. * @return {number} The sample count.
  46416. */
  46417. getSampleCountRenderContext( renderContext ) {
  46418. if ( renderContext.textures !== null ) {
  46419. return this.getSampleCount( renderContext.sampleCount );
  46420. }
  46421. return this.getSampleCount( this.backend.renderer.samples );
  46422. }
  46423. /**
  46424. * Returns the preferred canvas format.
  46425. *
  46426. * There is a separate method for this so it's possible to
  46427. * honor edge cases for specific devices.
  46428. *
  46429. * @return {string} The GPU texture format of the canvas.
  46430. */
  46431. getPreferredCanvasFormat() {
  46432. const outputType = this.backend.parameters.outputType;
  46433. if ( outputType === undefined ) {
  46434. return navigator.gpu.getPreferredCanvasFormat();
  46435. } else if ( outputType === UnsignedByteType ) {
  46436. return GPUTextureFormat.BGRA8Unorm;
  46437. } else if ( outputType === HalfFloatType ) {
  46438. return GPUTextureFormat.RGBA16Float;
  46439. } else {
  46440. throw new Error( 'Unsupported outputType' );
  46441. }
  46442. }
  46443. }
  46444. const typedArraysToVertexFormatPrefix = new Map( [
  46445. [ Int8Array, [ 'sint8', 'snorm8' ]],
  46446. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  46447. [ Int16Array, [ 'sint16', 'snorm16' ]],
  46448. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  46449. [ Int32Array, [ 'sint32', 'snorm32' ]],
  46450. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  46451. [ Float32Array, [ 'float32', ]],
  46452. ] );
  46453. const typedAttributeToVertexFormatPrefix = new Map( [
  46454. [ Float16BufferAttribute, [ 'float16', ]],
  46455. ] );
  46456. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  46457. [ Int32Array, 'sint32' ],
  46458. [ Int16Array, 'sint32' ], // patch for INT16
  46459. [ Uint32Array, 'uint32' ],
  46460. [ Uint16Array, 'uint32' ], // patch for UINT16
  46461. [ Float32Array, 'float32' ]
  46462. ] );
  46463. /**
  46464. * A WebGPU backend utility module for managing shader attributes.
  46465. *
  46466. * @private
  46467. */
  46468. class WebGPUAttributeUtils {
  46469. /**
  46470. * Constructs a new utility object.
  46471. *
  46472. * @param {WebGPUBackend} backend - The WebGPU backend.
  46473. */
  46474. constructor( backend ) {
  46475. /**
  46476. * A reference to the WebGPU backend.
  46477. *
  46478. * @type {WebGPUBackend}
  46479. */
  46480. this.backend = backend;
  46481. }
  46482. /**
  46483. * Creates the GPU buffer for the given buffer attribute.
  46484. *
  46485. * @param {BufferAttribute} attribute - The buffer attribute.
  46486. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  46487. */
  46488. createAttribute( attribute, usage ) {
  46489. const bufferAttribute = this._getBufferAttribute( attribute );
  46490. const backend = this.backend;
  46491. const bufferData = backend.get( bufferAttribute );
  46492. let buffer = bufferData.buffer;
  46493. if ( buffer === undefined ) {
  46494. const device = backend.device;
  46495. let array = bufferAttribute.array;
  46496. // patch for INT16 and UINT16
  46497. if ( attribute.normalized === false ) {
  46498. if ( array.constructor === Int16Array ) {
  46499. array = new Int32Array( array );
  46500. } else if ( array.constructor === Uint16Array ) {
  46501. array = new Uint32Array( array );
  46502. if ( usage & GPUBufferUsage.INDEX ) {
  46503. for ( let i = 0; i < array.length; i ++ ) {
  46504. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  46505. }
  46506. }
  46507. }
  46508. }
  46509. bufferAttribute.array = array;
  46510. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  46511. array = new array.constructor( bufferAttribute.count * 4 );
  46512. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  46513. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  46514. }
  46515. // Update BufferAttribute
  46516. bufferAttribute.itemSize = 4;
  46517. bufferAttribute.array = array;
  46518. }
  46519. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  46520. buffer = device.createBuffer( {
  46521. label: bufferAttribute.name,
  46522. size: size,
  46523. usage: usage,
  46524. mappedAtCreation: true
  46525. } );
  46526. new array.constructor( buffer.getMappedRange() ).set( array );
  46527. buffer.unmap();
  46528. bufferData.buffer = buffer;
  46529. }
  46530. }
  46531. /**
  46532. * Updates the GPU buffer of the given buffer attribute.
  46533. *
  46534. * @param {BufferAttribute} attribute - The buffer attribute.
  46535. */
  46536. updateAttribute( attribute ) {
  46537. const bufferAttribute = this._getBufferAttribute( attribute );
  46538. const backend = this.backend;
  46539. const device = backend.device;
  46540. const buffer = backend.get( bufferAttribute ).buffer;
  46541. const array = bufferAttribute.array;
  46542. const isTypedArray = this._isTypedArray( array );
  46543. const updateRanges = bufferAttribute.updateRanges;
  46544. if ( updateRanges.length === 0 ) {
  46545. // Not using update ranges
  46546. device.queue.writeBuffer(
  46547. buffer,
  46548. 0,
  46549. array,
  46550. 0
  46551. );
  46552. } else {
  46553. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  46554. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46555. const range = updateRanges[ i ];
  46556. const dataOffset = range.start * byteOffsetFactor;
  46557. const size = range.count * byteOffsetFactor;
  46558. device.queue.writeBuffer(
  46559. buffer,
  46560. 0,
  46561. array,
  46562. dataOffset,
  46563. size
  46564. );
  46565. }
  46566. bufferAttribute.clearUpdateRanges();
  46567. }
  46568. }
  46569. /**
  46570. * This method creates the vertex buffer layout data which are
  46571. * require when creating a render pipeline for the given render object.
  46572. *
  46573. * @param {RenderObject} renderObject - The render object.
  46574. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  46575. */
  46576. createShaderVertexBuffers( renderObject ) {
  46577. const attributes = renderObject.getAttributes();
  46578. const vertexBuffers = new Map();
  46579. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  46580. const geometryAttribute = attributes[ slot ];
  46581. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  46582. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  46583. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  46584. if ( vertexBufferLayout === undefined ) {
  46585. let arrayStride, stepMode;
  46586. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  46587. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  46588. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46589. } else {
  46590. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  46591. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46592. }
  46593. // patch for INT16 and UINT16
  46594. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  46595. arrayStride = 4;
  46596. }
  46597. vertexBufferLayout = {
  46598. arrayStride,
  46599. attributes: [],
  46600. stepMode
  46601. };
  46602. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  46603. }
  46604. const format = this._getVertexFormat( geometryAttribute );
  46605. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  46606. vertexBufferLayout.attributes.push( {
  46607. shaderLocation: slot,
  46608. offset,
  46609. format
  46610. } );
  46611. }
  46612. return Array.from( vertexBuffers.values() );
  46613. }
  46614. /**
  46615. * Destroys the GPU buffer of the given buffer attribute.
  46616. *
  46617. * @param {BufferAttribute} attribute - The buffer attribute.
  46618. */
  46619. destroyAttribute( attribute ) {
  46620. const backend = this.backend;
  46621. const data = backend.get( this._getBufferAttribute( attribute ) );
  46622. data.buffer.destroy();
  46623. backend.delete( attribute );
  46624. }
  46625. /**
  46626. * This method performs a readback operation by moving buffer data from
  46627. * a storage buffer attribute from the GPU to the CPU.
  46628. *
  46629. * @async
  46630. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46631. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46632. */
  46633. async getArrayBufferAsync( attribute ) {
  46634. const backend = this.backend;
  46635. const device = backend.device;
  46636. const data = backend.get( this._getBufferAttribute( attribute ) );
  46637. const bufferGPU = data.buffer;
  46638. const size = bufferGPU.size;
  46639. const readBufferGPU = device.createBuffer( {
  46640. label: `${ attribute.name }_readback`,
  46641. size,
  46642. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46643. } );
  46644. const cmdEncoder = device.createCommandEncoder( {
  46645. label: `readback_encoder_${ attribute.name }`
  46646. } );
  46647. cmdEncoder.copyBufferToBuffer(
  46648. bufferGPU,
  46649. 0,
  46650. readBufferGPU,
  46651. 0,
  46652. size
  46653. );
  46654. const gpuCommands = cmdEncoder.finish();
  46655. device.queue.submit( [ gpuCommands ] );
  46656. await readBufferGPU.mapAsync( GPUMapMode.READ );
  46657. const arrayBuffer = readBufferGPU.getMappedRange();
  46658. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  46659. readBufferGPU.unmap();
  46660. return dstBuffer.buffer;
  46661. }
  46662. /**
  46663. * Returns the vertex format of the given buffer attribute.
  46664. *
  46665. * @private
  46666. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  46667. * @return {string} The vertex format (e.g. 'float32x3').
  46668. */
  46669. _getVertexFormat( geometryAttribute ) {
  46670. const { itemSize, normalized } = geometryAttribute;
  46671. const ArrayType = geometryAttribute.array.constructor;
  46672. const AttributeType = geometryAttribute.constructor;
  46673. let format;
  46674. if ( itemSize === 1 ) {
  46675. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  46676. } else {
  46677. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  46678. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  46679. if ( prefix ) {
  46680. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  46681. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  46682. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  46683. if ( paddedItemSize % 1 ) {
  46684. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  46685. }
  46686. format = `${prefix}x${paddedItemSize}`;
  46687. }
  46688. }
  46689. if ( ! format ) {
  46690. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  46691. }
  46692. return format;
  46693. }
  46694. /**
  46695. * Returns `true` if the given array is a typed array.
  46696. *
  46697. * @private
  46698. * @param {any} array - The array.
  46699. * @return {boolean} Whether the given array is a typed array or not.
  46700. */
  46701. _isTypedArray( array ) {
  46702. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  46703. }
  46704. /**
  46705. * Utility method for handling interleaved buffer attributes correctly.
  46706. * To process them, their `InterleavedBuffer` is returned.
  46707. *
  46708. * @private
  46709. * @param {BufferAttribute} attribute - The attribute.
  46710. * @return {BufferAttribute|InterleavedBuffer}
  46711. */
  46712. _getBufferAttribute( attribute ) {
  46713. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  46714. return attribute;
  46715. }
  46716. }
  46717. /**
  46718. * A WebGPU backend utility module for managing bindings.
  46719. *
  46720. * When reading the documentation it's helpful to keep in mind that
  46721. * all class definitions starting with 'GPU*' are modules from the
  46722. * WebGPU API. So for example `BindGroup` is a class from the engine
  46723. * whereas `GPUBindGroup` is a class from WebGPU.
  46724. *
  46725. * @private
  46726. */
  46727. class WebGPUBindingUtils {
  46728. /**
  46729. * Constructs a new utility object.
  46730. *
  46731. * @param {WebGPUBackend} backend - The WebGPU backend.
  46732. */
  46733. constructor( backend ) {
  46734. /**
  46735. * A reference to the WebGPU backend.
  46736. *
  46737. * @type {WebGPUBackend}
  46738. */
  46739. this.backend = backend;
  46740. /**
  46741. * A cache for managing bind group layouts.
  46742. *
  46743. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  46744. */
  46745. this.bindGroupLayoutCache = new WeakMap();
  46746. }
  46747. /**
  46748. * Creates a GPU bind group layout for the given bind group.
  46749. *
  46750. * @param {BindGroup} bindGroup - The bind group.
  46751. * @return {GPUBindGroupLayout} The GPU bind group layout.
  46752. */
  46753. createBindingsLayout( bindGroup ) {
  46754. const backend = this.backend;
  46755. const device = backend.device;
  46756. const entries = [];
  46757. let index = 0;
  46758. for ( const binding of bindGroup.bindings ) {
  46759. const bindingGPU = {
  46760. binding: index ++,
  46761. visibility: binding.visibility
  46762. };
  46763. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  46764. const buffer = {}; // GPUBufferBindingLayout
  46765. if ( binding.isStorageBuffer ) {
  46766. if ( binding.visibility & 4 ) {
  46767. // compute
  46768. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  46769. buffer.type = GPUBufferBindingType.Storage;
  46770. } else {
  46771. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46772. }
  46773. } else {
  46774. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46775. }
  46776. }
  46777. bindingGPU.buffer = buffer;
  46778. } else if ( binding.isSampler ) {
  46779. const sampler = {}; // GPUSamplerBindingLayout
  46780. if ( binding.texture.isDepthTexture ) {
  46781. if ( binding.texture.compareFunction !== null ) {
  46782. sampler.type = 'comparison';
  46783. }
  46784. }
  46785. bindingGPU.sampler = sampler;
  46786. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  46787. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  46788. } else if ( binding.isSampledTexture && binding.store ) {
  46789. const storageTexture = {}; // GPUStorageTextureBindingLayout
  46790. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  46791. const access = binding.access;
  46792. if ( access === NodeAccess.READ_WRITE ) {
  46793. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  46794. } else if ( access === NodeAccess.WRITE_ONLY ) {
  46795. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  46796. } else {
  46797. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  46798. }
  46799. bindingGPU.storageTexture = storageTexture;
  46800. } else if ( binding.isSampledTexture ) {
  46801. const texture = {}; // GPUTextureBindingLayout
  46802. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  46803. if ( primarySamples > 1 ) {
  46804. texture.multisampled = true;
  46805. if ( ! binding.texture.isDepthTexture ) {
  46806. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46807. }
  46808. }
  46809. if ( binding.texture.isDepthTexture ) {
  46810. texture.sampleType = GPUTextureSampleType.Depth;
  46811. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  46812. const type = binding.texture.type;
  46813. if ( type === IntType ) {
  46814. texture.sampleType = GPUTextureSampleType.SInt;
  46815. } else if ( type === UnsignedIntType ) {
  46816. texture.sampleType = GPUTextureSampleType.UInt;
  46817. } else if ( type === FloatType ) {
  46818. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  46819. texture.sampleType = GPUTextureSampleType.Float;
  46820. } else {
  46821. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46822. }
  46823. }
  46824. }
  46825. if ( binding.isSampledCubeTexture ) {
  46826. texture.viewDimension = GPUTextureViewDimension.Cube;
  46827. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46828. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  46829. } else if ( binding.isSampledTexture3D ) {
  46830. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  46831. }
  46832. bindingGPU.texture = texture;
  46833. } else {
  46834. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  46835. }
  46836. entries.push( bindingGPU );
  46837. }
  46838. return device.createBindGroupLayout( { entries } );
  46839. }
  46840. /**
  46841. * Creates bindings from the given bind group definition.
  46842. *
  46843. * @param {BindGroup} bindGroup - The bind group.
  46844. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46845. * @param {number} cacheIndex - The cache index.
  46846. * @param {number} version - The version.
  46847. */
  46848. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  46849. const { backend, bindGroupLayoutCache } = this;
  46850. const bindingsData = backend.get( bindGroup );
  46851. // setup (static) binding layout and (dynamic) binding group
  46852. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  46853. if ( bindLayoutGPU === undefined ) {
  46854. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  46855. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  46856. }
  46857. let bindGroupGPU;
  46858. if ( cacheIndex > 0 ) {
  46859. if ( bindingsData.groups === undefined ) {
  46860. bindingsData.groups = [];
  46861. bindingsData.versions = [];
  46862. }
  46863. if ( bindingsData.versions[ cacheIndex ] === version ) {
  46864. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  46865. }
  46866. }
  46867. if ( bindGroupGPU === undefined ) {
  46868. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  46869. if ( cacheIndex > 0 ) {
  46870. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  46871. bindingsData.versions[ cacheIndex ] = version;
  46872. }
  46873. }
  46874. bindingsData.group = bindGroupGPU;
  46875. bindingsData.layout = bindLayoutGPU;
  46876. }
  46877. /**
  46878. * Updates a buffer binding.
  46879. *
  46880. * @param {Buffer} binding - The buffer binding to update.
  46881. */
  46882. updateBinding( binding ) {
  46883. const backend = this.backend;
  46884. const device = backend.device;
  46885. const buffer = binding.buffer;
  46886. const bufferGPU = backend.get( binding ).buffer;
  46887. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  46888. }
  46889. /**
  46890. * Creates a GPU bind group for the camera index.
  46891. *
  46892. * @param {Uint32Array} data - The index data.
  46893. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  46894. * @return {GPUBindGroup} The GPU bind group.
  46895. */
  46896. createBindGroupIndex( data, layout ) {
  46897. const backend = this.backend;
  46898. const device = backend.device;
  46899. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46900. const index = data[ 0 ];
  46901. const buffer = device.createBuffer( {
  46902. label: 'bindingCameraIndex_' + index,
  46903. size: 16, // uint(4) * 4
  46904. usage: usage
  46905. } );
  46906. device.queue.writeBuffer( buffer, 0, data, 0 );
  46907. const entries = [ { binding: 0, resource: { buffer } } ];
  46908. return device.createBindGroup( {
  46909. label: 'bindGroupCameraIndex_' + index,
  46910. layout,
  46911. entries
  46912. } );
  46913. }
  46914. /**
  46915. * Creates a GPU bind group for the given bind group and GPU layout.
  46916. *
  46917. * @param {BindGroup} bindGroup - The bind group.
  46918. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  46919. * @return {GPUBindGroup} The GPU bind group.
  46920. */
  46921. createBindGroup( bindGroup, layoutGPU ) {
  46922. const backend = this.backend;
  46923. const device = backend.device;
  46924. let bindingPoint = 0;
  46925. const entriesGPU = [];
  46926. for ( const binding of bindGroup.bindings ) {
  46927. if ( binding.isUniformBuffer ) {
  46928. const bindingData = backend.get( binding );
  46929. if ( bindingData.buffer === undefined ) {
  46930. const byteLength = binding.byteLength;
  46931. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46932. const bufferGPU = device.createBuffer( {
  46933. label: 'bindingBuffer_' + binding.name,
  46934. size: byteLength,
  46935. usage: usage
  46936. } );
  46937. bindingData.buffer = bufferGPU;
  46938. }
  46939. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46940. } else if ( binding.isStorageBuffer ) {
  46941. const bindingData = backend.get( binding );
  46942. if ( bindingData.buffer === undefined ) {
  46943. const attribute = binding.attribute;
  46944. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  46945. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  46946. bindingData.buffer = backend.get( attribute ).buffer;
  46947. }
  46948. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46949. } else if ( binding.isSampler ) {
  46950. const textureGPU = backend.get( binding.texture );
  46951. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  46952. } else if ( binding.isSampledTexture ) {
  46953. const textureData = backend.get( binding.texture );
  46954. let resourceGPU;
  46955. if ( textureData.externalTexture !== undefined ) {
  46956. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  46957. } else {
  46958. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  46959. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  46960. resourceGPU = textureData[ propertyName ];
  46961. if ( resourceGPU === undefined ) {
  46962. const aspectGPU = GPUTextureAspect.All;
  46963. let dimensionViewGPU;
  46964. if ( binding.isSampledCubeTexture ) {
  46965. dimensionViewGPU = GPUTextureViewDimension.Cube;
  46966. } else if ( binding.isSampledTexture3D ) {
  46967. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  46968. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46969. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  46970. } else {
  46971. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  46972. }
  46973. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  46974. }
  46975. }
  46976. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  46977. }
  46978. bindingPoint ++;
  46979. }
  46980. return device.createBindGroup( {
  46981. label: 'bindGroup_' + bindGroup.name,
  46982. layout: layoutGPU,
  46983. entries: entriesGPU
  46984. } );
  46985. }
  46986. }
  46987. /**
  46988. * A WebGPU backend utility module for managing pipelines.
  46989. *
  46990. * @private
  46991. */
  46992. class WebGPUPipelineUtils {
  46993. /**
  46994. * Constructs a new utility object.
  46995. *
  46996. * @param {WebGPUBackend} backend - The WebGPU backend.
  46997. */
  46998. constructor( backend ) {
  46999. /**
  47000. * A reference to the WebGPU backend.
  47001. *
  47002. * @type {WebGPUBackend}
  47003. */
  47004. this.backend = backend;
  47005. }
  47006. /**
  47007. * Returns the sample count derived from the given render context.
  47008. *
  47009. * @private
  47010. * @param {RenderContext} renderContext - The render context.
  47011. * @return {number} The sample count.
  47012. */
  47013. _getSampleCount( renderContext ) {
  47014. return this.backend.utils.getSampleCountRenderContext( renderContext );
  47015. }
  47016. /**
  47017. * Creates a render pipeline for the given render object.
  47018. *
  47019. * @param {RenderObject} renderObject - The render object.
  47020. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47021. */
  47022. createRenderPipeline( renderObject, promises ) {
  47023. const { object, material, geometry, pipeline } = renderObject;
  47024. const { vertexProgram, fragmentProgram } = pipeline;
  47025. const backend = this.backend;
  47026. const device = backend.device;
  47027. const utils = backend.utils;
  47028. const pipelineData = backend.get( pipeline );
  47029. // bind group layouts
  47030. const bindGroupLayouts = [];
  47031. for ( const bindGroup of renderObject.getBindings() ) {
  47032. const bindingsData = backend.get( bindGroup );
  47033. bindGroupLayouts.push( bindingsData.layout );
  47034. }
  47035. // vertex buffers
  47036. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  47037. // blending
  47038. let blending;
  47039. if ( material.transparent === true && material.blending !== NoBlending ) {
  47040. blending = this._getBlending( material );
  47041. }
  47042. // stencil
  47043. let stencilFront = {};
  47044. if ( material.stencilWrite === true ) {
  47045. stencilFront = {
  47046. compare: this._getStencilCompare( material ),
  47047. failOp: this._getStencilOperation( material.stencilFail ),
  47048. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  47049. passOp: this._getStencilOperation( material.stencilZPass )
  47050. };
  47051. }
  47052. const colorWriteMask = this._getColorWriteMask( material );
  47053. const targets = [];
  47054. if ( renderObject.context.textures !== null ) {
  47055. const textures = renderObject.context.textures;
  47056. for ( let i = 0; i < textures.length; i ++ ) {
  47057. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  47058. targets.push( {
  47059. format: colorFormat,
  47060. blend: blending,
  47061. writeMask: colorWriteMask
  47062. } );
  47063. }
  47064. } else {
  47065. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47066. targets.push( {
  47067. format: colorFormat,
  47068. blend: blending,
  47069. writeMask: colorWriteMask
  47070. } );
  47071. }
  47072. const vertexModule = backend.get( vertexProgram ).module;
  47073. const fragmentModule = backend.get( fragmentProgram ).module;
  47074. const primitiveState = this._getPrimitiveState( object, geometry, material );
  47075. const depthCompare = this._getDepthCompare( material );
  47076. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47077. const sampleCount = this._getSampleCount( renderObject.context );
  47078. const pipelineDescriptor = {
  47079. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  47080. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  47081. fragment: Object.assign( {}, fragmentModule, { targets } ),
  47082. primitive: primitiveState,
  47083. multisample: {
  47084. count: sampleCount,
  47085. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  47086. },
  47087. layout: device.createPipelineLayout( {
  47088. bindGroupLayouts
  47089. } )
  47090. };
  47091. const depthStencil = {};
  47092. const renderDepth = renderObject.context.depth;
  47093. const renderStencil = renderObject.context.stencil;
  47094. if ( renderDepth === true || renderStencil === true ) {
  47095. if ( renderDepth === true ) {
  47096. depthStencil.format = depthStencilFormat;
  47097. depthStencil.depthWriteEnabled = material.depthWrite;
  47098. depthStencil.depthCompare = depthCompare;
  47099. }
  47100. if ( renderStencil === true ) {
  47101. depthStencil.stencilFront = stencilFront;
  47102. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  47103. depthStencil.stencilReadMask = material.stencilFuncMask;
  47104. depthStencil.stencilWriteMask = material.stencilWriteMask;
  47105. }
  47106. if ( material.polygonOffset === true ) {
  47107. depthStencil.depthBias = material.polygonOffsetUnits;
  47108. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  47109. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  47110. }
  47111. pipelineDescriptor.depthStencil = depthStencil;
  47112. }
  47113. if ( promises === null ) {
  47114. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  47115. } else {
  47116. const p = new Promise( ( resolve /*, reject*/ ) => {
  47117. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  47118. pipelineData.pipeline = pipeline;
  47119. resolve();
  47120. } );
  47121. } );
  47122. promises.push( p );
  47123. }
  47124. }
  47125. /**
  47126. * Creates GPU render bundle encoder for the given render context.
  47127. *
  47128. * @param {RenderContext} renderContext - The render context.
  47129. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  47130. */
  47131. createBundleEncoder( renderContext ) {
  47132. const backend = this.backend;
  47133. const { utils, device } = backend;
  47134. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  47135. const colorFormat = utils.getCurrentColorFormat( renderContext );
  47136. const sampleCount = this._getSampleCount( renderContext );
  47137. const descriptor = {
  47138. label: 'renderBundleEncoder',
  47139. colorFormats: [ colorFormat ],
  47140. depthStencilFormat,
  47141. sampleCount
  47142. };
  47143. return device.createRenderBundleEncoder( descriptor );
  47144. }
  47145. /**
  47146. * Creates a compute pipeline for the given compute node.
  47147. *
  47148. * @param {ComputePipeline} pipeline - The compute pipeline.
  47149. * @param {Array<BindGroup>} bindings - The bindings.
  47150. */
  47151. createComputePipeline( pipeline, bindings ) {
  47152. const backend = this.backend;
  47153. const device = backend.device;
  47154. const computeProgram = backend.get( pipeline.computeProgram ).module;
  47155. const pipelineGPU = backend.get( pipeline );
  47156. // bind group layouts
  47157. const bindGroupLayouts = [];
  47158. for ( const bindingsGroup of bindings ) {
  47159. const bindingsData = backend.get( bindingsGroup );
  47160. bindGroupLayouts.push( bindingsData.layout );
  47161. }
  47162. pipelineGPU.pipeline = device.createComputePipeline( {
  47163. compute: computeProgram,
  47164. layout: device.createPipelineLayout( {
  47165. bindGroupLayouts
  47166. } )
  47167. } );
  47168. }
  47169. /**
  47170. * Returns the blending state as a descriptor object required
  47171. * for the pipeline creation.
  47172. *
  47173. * @private
  47174. * @param {Material} material - The material.
  47175. * @return {Object} The blending state.
  47176. */
  47177. _getBlending( material ) {
  47178. let color, alpha;
  47179. const blending = material.blending;
  47180. const blendSrc = material.blendSrc;
  47181. const blendDst = material.blendDst;
  47182. const blendEquation = material.blendEquation;
  47183. if ( blending === CustomBlending ) {
  47184. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  47185. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  47186. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  47187. color = {
  47188. srcFactor: this._getBlendFactor( blendSrc ),
  47189. dstFactor: this._getBlendFactor( blendDst ),
  47190. operation: this._getBlendOperation( blendEquation )
  47191. };
  47192. alpha = {
  47193. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  47194. dstFactor: this._getBlendFactor( blendDstAlpha ),
  47195. operation: this._getBlendOperation( blendEquationAlpha )
  47196. };
  47197. } else {
  47198. const premultipliedAlpha = material.premultipliedAlpha;
  47199. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  47200. color = {
  47201. srcFactor: srcRGB,
  47202. dstFactor: dstRGB,
  47203. operation: GPUBlendOperation.Add
  47204. };
  47205. alpha = {
  47206. srcFactor: srcAlpha,
  47207. dstFactor: dstAlpha,
  47208. operation: GPUBlendOperation.Add
  47209. };
  47210. };
  47211. if ( premultipliedAlpha ) {
  47212. switch ( blending ) {
  47213. case NormalBlending:
  47214. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47215. break;
  47216. case AdditiveBlending:
  47217. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  47218. break;
  47219. case SubtractiveBlending:
  47220. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47221. break;
  47222. case MultiplyBlending:
  47223. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  47224. break;
  47225. }
  47226. } else {
  47227. switch ( blending ) {
  47228. case NormalBlending:
  47229. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47230. break;
  47231. case AdditiveBlending:
  47232. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  47233. break;
  47234. case SubtractiveBlending:
  47235. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47236. break;
  47237. case MultiplyBlending:
  47238. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  47239. break;
  47240. }
  47241. }
  47242. }
  47243. if ( color !== undefined && alpha !== undefined ) {
  47244. return { color, alpha };
  47245. } else {
  47246. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  47247. }
  47248. }
  47249. /**
  47250. * Returns the GPU blend factor which is required for the pipeline creation.
  47251. *
  47252. * @private
  47253. * @param {number} blend - The blend factor as a three.js constant.
  47254. * @return {string} The GPU blend factor.
  47255. */
  47256. _getBlendFactor( blend ) {
  47257. let blendFactor;
  47258. switch ( blend ) {
  47259. case ZeroFactor:
  47260. blendFactor = GPUBlendFactor.Zero;
  47261. break;
  47262. case OneFactor:
  47263. blendFactor = GPUBlendFactor.One;
  47264. break;
  47265. case SrcColorFactor:
  47266. blendFactor = GPUBlendFactor.Src;
  47267. break;
  47268. case OneMinusSrcColorFactor:
  47269. blendFactor = GPUBlendFactor.OneMinusSrc;
  47270. break;
  47271. case SrcAlphaFactor:
  47272. blendFactor = GPUBlendFactor.SrcAlpha;
  47273. break;
  47274. case OneMinusSrcAlphaFactor:
  47275. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  47276. break;
  47277. case DstColorFactor:
  47278. blendFactor = GPUBlendFactor.Dst;
  47279. break;
  47280. case OneMinusDstColorFactor:
  47281. blendFactor = GPUBlendFactor.OneMinusDstColor;
  47282. break;
  47283. case DstAlphaFactor:
  47284. blendFactor = GPUBlendFactor.DstAlpha;
  47285. break;
  47286. case OneMinusDstAlphaFactor:
  47287. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  47288. break;
  47289. case SrcAlphaSaturateFactor:
  47290. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  47291. break;
  47292. case BlendColorFactor:
  47293. blendFactor = GPUBlendFactor.Constant;
  47294. break;
  47295. case OneMinusBlendColorFactor:
  47296. blendFactor = GPUBlendFactor.OneMinusConstant;
  47297. break;
  47298. default:
  47299. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  47300. }
  47301. return blendFactor;
  47302. }
  47303. /**
  47304. * Returns the GPU stencil compare function which is required for the pipeline creation.
  47305. *
  47306. * @private
  47307. * @param {Material} material - The material.
  47308. * @return {string} The GPU stencil compare function.
  47309. */
  47310. _getStencilCompare( material ) {
  47311. let stencilCompare;
  47312. const stencilFunc = material.stencilFunc;
  47313. switch ( stencilFunc ) {
  47314. case NeverStencilFunc:
  47315. stencilCompare = GPUCompareFunction.Never;
  47316. break;
  47317. case AlwaysStencilFunc:
  47318. stencilCompare = GPUCompareFunction.Always;
  47319. break;
  47320. case LessStencilFunc:
  47321. stencilCompare = GPUCompareFunction.Less;
  47322. break;
  47323. case LessEqualStencilFunc:
  47324. stencilCompare = GPUCompareFunction.LessEqual;
  47325. break;
  47326. case EqualStencilFunc:
  47327. stencilCompare = GPUCompareFunction.Equal;
  47328. break;
  47329. case GreaterEqualStencilFunc:
  47330. stencilCompare = GPUCompareFunction.GreaterEqual;
  47331. break;
  47332. case GreaterStencilFunc:
  47333. stencilCompare = GPUCompareFunction.Greater;
  47334. break;
  47335. case NotEqualStencilFunc:
  47336. stencilCompare = GPUCompareFunction.NotEqual;
  47337. break;
  47338. default:
  47339. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  47340. }
  47341. return stencilCompare;
  47342. }
  47343. /**
  47344. * Returns the GPU stencil operation which is required for the pipeline creation.
  47345. *
  47346. * @private
  47347. * @param {number} op - A three.js constant defining the stencil operation.
  47348. * @return {string} The GPU stencil operation.
  47349. */
  47350. _getStencilOperation( op ) {
  47351. let stencilOperation;
  47352. switch ( op ) {
  47353. case KeepStencilOp:
  47354. stencilOperation = GPUStencilOperation.Keep;
  47355. break;
  47356. case ZeroStencilOp:
  47357. stencilOperation = GPUStencilOperation.Zero;
  47358. break;
  47359. case ReplaceStencilOp:
  47360. stencilOperation = GPUStencilOperation.Replace;
  47361. break;
  47362. case InvertStencilOp:
  47363. stencilOperation = GPUStencilOperation.Invert;
  47364. break;
  47365. case IncrementStencilOp:
  47366. stencilOperation = GPUStencilOperation.IncrementClamp;
  47367. break;
  47368. case DecrementStencilOp:
  47369. stencilOperation = GPUStencilOperation.DecrementClamp;
  47370. break;
  47371. case IncrementWrapStencilOp:
  47372. stencilOperation = GPUStencilOperation.IncrementWrap;
  47373. break;
  47374. case DecrementWrapStencilOp:
  47375. stencilOperation = GPUStencilOperation.DecrementWrap;
  47376. break;
  47377. default:
  47378. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  47379. }
  47380. return stencilOperation;
  47381. }
  47382. /**
  47383. * Returns the GPU blend operation which is required for the pipeline creation.
  47384. *
  47385. * @private
  47386. * @param {number} blendEquation - A three.js constant defining the blend equation.
  47387. * @return {string} The GPU blend operation.
  47388. */
  47389. _getBlendOperation( blendEquation ) {
  47390. let blendOperation;
  47391. switch ( blendEquation ) {
  47392. case AddEquation:
  47393. blendOperation = GPUBlendOperation.Add;
  47394. break;
  47395. case SubtractEquation:
  47396. blendOperation = GPUBlendOperation.Subtract;
  47397. break;
  47398. case ReverseSubtractEquation:
  47399. blendOperation = GPUBlendOperation.ReverseSubtract;
  47400. break;
  47401. case MinEquation:
  47402. blendOperation = GPUBlendOperation.Min;
  47403. break;
  47404. case MaxEquation:
  47405. blendOperation = GPUBlendOperation.Max;
  47406. break;
  47407. default:
  47408. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  47409. }
  47410. return blendOperation;
  47411. }
  47412. /**
  47413. * Returns the primitive state as a descriptor object required
  47414. * for the pipeline creation.
  47415. *
  47416. * @private
  47417. * @param {Object3D} object - The 3D object.
  47418. * @param {BufferGeometry} geometry - The geometry.
  47419. * @param {Material} material - The material.
  47420. * @return {Object} The primitive state.
  47421. */
  47422. _getPrimitiveState( object, geometry, material ) {
  47423. const descriptor = {};
  47424. const utils = this.backend.utils;
  47425. descriptor.topology = utils.getPrimitiveTopology( object, material );
  47426. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  47427. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  47428. }
  47429. switch ( material.side ) {
  47430. case FrontSide:
  47431. descriptor.frontFace = GPUFrontFace.CCW;
  47432. descriptor.cullMode = GPUCullMode.Back;
  47433. break;
  47434. case BackSide:
  47435. descriptor.frontFace = GPUFrontFace.CCW;
  47436. descriptor.cullMode = GPUCullMode.Front;
  47437. break;
  47438. case DoubleSide:
  47439. descriptor.frontFace = GPUFrontFace.CCW;
  47440. descriptor.cullMode = GPUCullMode.None;
  47441. break;
  47442. default:
  47443. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  47444. break;
  47445. }
  47446. return descriptor;
  47447. }
  47448. /**
  47449. * Returns the GPU color write mask which is required for the pipeline creation.
  47450. *
  47451. * @private
  47452. * @param {Material} material - The material.
  47453. * @return {string} The GPU color write mask.
  47454. */
  47455. _getColorWriteMask( material ) {
  47456. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  47457. }
  47458. /**
  47459. * Returns the GPU depth compare function which is required for the pipeline creation.
  47460. *
  47461. * @private
  47462. * @param {Material} material - The material.
  47463. * @return {string} The GPU depth compare function.
  47464. */
  47465. _getDepthCompare( material ) {
  47466. let depthCompare;
  47467. if ( material.depthTest === false ) {
  47468. depthCompare = GPUCompareFunction.Always;
  47469. } else {
  47470. const depthFunc = material.depthFunc;
  47471. switch ( depthFunc ) {
  47472. case NeverDepth:
  47473. depthCompare = GPUCompareFunction.Never;
  47474. break;
  47475. case AlwaysDepth:
  47476. depthCompare = GPUCompareFunction.Always;
  47477. break;
  47478. case LessDepth:
  47479. depthCompare = GPUCompareFunction.Less;
  47480. break;
  47481. case LessEqualDepth:
  47482. depthCompare = GPUCompareFunction.LessEqual;
  47483. break;
  47484. case EqualDepth:
  47485. depthCompare = GPUCompareFunction.Equal;
  47486. break;
  47487. case GreaterEqualDepth:
  47488. depthCompare = GPUCompareFunction.GreaterEqual;
  47489. break;
  47490. case GreaterDepth:
  47491. depthCompare = GPUCompareFunction.Greater;
  47492. break;
  47493. case NotEqualDepth:
  47494. depthCompare = GPUCompareFunction.NotEqual;
  47495. break;
  47496. default:
  47497. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  47498. }
  47499. }
  47500. return depthCompare;
  47501. }
  47502. }
  47503. /**
  47504. * Manages a pool of WebGPU timestamp queries for performance measurement.
  47505. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  47506. *
  47507. * @augments TimestampQueryPool
  47508. */
  47509. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  47510. /**
  47511. * Creates a new WebGPU timestamp query pool.
  47512. *
  47513. * @param {GPUDevice} device - The WebGPU device to create queries on.
  47514. * @param {string} type - The type identifier for this query pool.
  47515. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  47516. */
  47517. constructor( device, type, maxQueries = 2048 ) {
  47518. super( maxQueries );
  47519. this.device = device;
  47520. this.type = type;
  47521. this.querySet = this.device.createQuerySet( {
  47522. type: 'timestamp',
  47523. count: this.maxQueries,
  47524. label: `queryset_global_timestamp_${type}`
  47525. } );
  47526. const bufferSize = this.maxQueries * 8;
  47527. this.resolveBuffer = this.device.createBuffer( {
  47528. label: `buffer_timestamp_resolve_${type}`,
  47529. size: bufferSize,
  47530. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47531. } );
  47532. this.resultBuffer = this.device.createBuffer( {
  47533. label: `buffer_timestamp_result_${type}`,
  47534. size: bufferSize,
  47535. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47536. } );
  47537. }
  47538. /**
  47539. * Allocates a pair of queries for a given render context.
  47540. *
  47541. * @param {Object} renderContext - The render context to allocate queries for.
  47542. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  47543. */
  47544. allocateQueriesForContext( renderContext ) {
  47545. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  47546. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  47547. 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() } ).` );
  47548. return null;
  47549. }
  47550. const baseOffset = this.currentQueryIndex;
  47551. this.currentQueryIndex += 2;
  47552. this.queryOffsets.set( renderContext.id, baseOffset );
  47553. return baseOffset;
  47554. }
  47555. /**
  47556. * Asynchronously resolves all pending queries and returns the total duration.
  47557. * If there's already a pending resolve operation, returns that promise instead.
  47558. *
  47559. * @async
  47560. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  47561. */
  47562. async resolveQueriesAsync() {
  47563. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  47564. return this.lastValue;
  47565. }
  47566. if ( this.pendingResolve ) {
  47567. return this.pendingResolve;
  47568. }
  47569. this.pendingResolve = this._resolveQueries();
  47570. try {
  47571. const result = await this.pendingResolve;
  47572. return result;
  47573. } finally {
  47574. this.pendingResolve = null;
  47575. }
  47576. }
  47577. /**
  47578. * Internal method to resolve queries and calculate total duration.
  47579. *
  47580. * @async
  47581. * @private
  47582. * @returns {Promise<number>} The total duration in milliseconds.
  47583. */
  47584. async _resolveQueries() {
  47585. if ( this.isDisposed ) {
  47586. return this.lastValue;
  47587. }
  47588. try {
  47589. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47590. return this.lastValue;
  47591. }
  47592. const currentOffsets = new Map( this.queryOffsets );
  47593. const queryCount = this.currentQueryIndex;
  47594. const bytesUsed = queryCount * 8;
  47595. // Reset state before GPU work
  47596. this.currentQueryIndex = 0;
  47597. this.queryOffsets.clear();
  47598. const commandEncoder = this.device.createCommandEncoder();
  47599. commandEncoder.resolveQuerySet(
  47600. this.querySet,
  47601. 0,
  47602. queryCount,
  47603. this.resolveBuffer,
  47604. 0
  47605. );
  47606. commandEncoder.copyBufferToBuffer(
  47607. this.resolveBuffer,
  47608. 0,
  47609. this.resultBuffer,
  47610. 0,
  47611. bytesUsed
  47612. );
  47613. const commandBuffer = commandEncoder.finish();
  47614. this.device.queue.submit( [ commandBuffer ] );
  47615. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47616. return this.lastValue;
  47617. }
  47618. // Create and track the mapping operation
  47619. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  47620. if ( this.isDisposed ) {
  47621. if ( this.resultBuffer.mapState === 'mapped' ) {
  47622. this.resultBuffer.unmap();
  47623. }
  47624. return this.lastValue;
  47625. }
  47626. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  47627. let totalDuration = 0;
  47628. for ( const [ , baseOffset ] of currentOffsets ) {
  47629. const startTime = times[ baseOffset ];
  47630. const endTime = times[ baseOffset + 1 ];
  47631. const duration = Number( endTime - startTime ) / 1e6;
  47632. totalDuration += duration;
  47633. }
  47634. this.resultBuffer.unmap();
  47635. this.lastValue = totalDuration;
  47636. return totalDuration;
  47637. } catch ( error ) {
  47638. console.error( 'Error resolving queries:', error );
  47639. if ( this.resultBuffer.mapState === 'mapped' ) {
  47640. this.resultBuffer.unmap();
  47641. }
  47642. return this.lastValue;
  47643. }
  47644. }
  47645. /**
  47646. * Dispose of the query pool.
  47647. *
  47648. * @async
  47649. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  47650. */
  47651. async dispose() {
  47652. if ( this.isDisposed ) {
  47653. return;
  47654. }
  47655. this.isDisposed = true;
  47656. // Wait for pending resolve operation
  47657. if ( this.pendingResolve ) {
  47658. try {
  47659. await this.pendingResolve;
  47660. } catch ( error ) {
  47661. console.error( 'Error waiting for pending resolve:', error );
  47662. }
  47663. }
  47664. // Ensure buffer is unmapped before destroying
  47665. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  47666. try {
  47667. this.resultBuffer.unmap();
  47668. } catch ( error ) {
  47669. console.error( 'Error unmapping buffer:', error );
  47670. }
  47671. }
  47672. // Destroy resources
  47673. if ( this.querySet ) {
  47674. this.querySet.destroy();
  47675. this.querySet = null;
  47676. }
  47677. if ( this.resolveBuffer ) {
  47678. this.resolveBuffer.destroy();
  47679. this.resolveBuffer = null;
  47680. }
  47681. if ( this.resultBuffer ) {
  47682. this.resultBuffer.destroy();
  47683. this.resultBuffer = null;
  47684. }
  47685. this.queryOffsets.clear();
  47686. this.pendingResolve = null;
  47687. }
  47688. }
  47689. /*// debugger tools
  47690. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  47691. //*/
  47692. /**
  47693. * A backend implementation targeting WebGPU.
  47694. *
  47695. * @private
  47696. * @augments Backend
  47697. */
  47698. class WebGPUBackend extends Backend {
  47699. /**
  47700. * Constructs a new WebGPU backend.
  47701. *
  47702. * @param {Object} parameters - The configuration parameter.
  47703. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47704. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47705. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47706. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47707. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47708. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  47709. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47710. * @param {boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  47711. * @param {string} [parameters.powerPreference=undefined] - The power preference.
  47712. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  47713. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  47714. * @param {number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  47715. */
  47716. constructor( parameters = {} ) {
  47717. super( parameters );
  47718. /**
  47719. * This flag can be used for type testing.
  47720. *
  47721. * @type {boolean}
  47722. * @readonly
  47723. * @default true
  47724. */
  47725. this.isWebGPUBackend = true;
  47726. // some parameters require default values other than "undefined"
  47727. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  47728. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  47729. /**
  47730. * Whether to track timestamps with a Timestamp Query API or not.
  47731. *
  47732. * @type {boolean}
  47733. * @default false
  47734. */
  47735. this.trackTimestamp = ( parameters.trackTimestamp === true );
  47736. /**
  47737. * A reference to the device.
  47738. *
  47739. * @type {?GPUDevice}
  47740. * @default null
  47741. */
  47742. this.device = null;
  47743. /**
  47744. * A reference to the context.
  47745. *
  47746. * @type {?GPUCanvasContext}
  47747. * @default null
  47748. */
  47749. this.context = null;
  47750. /**
  47751. * A reference to the color attachment of the default framebuffer.
  47752. *
  47753. * @type {?GPUTexture}
  47754. * @default null
  47755. */
  47756. this.colorBuffer = null;
  47757. /**
  47758. * A reference to the default render pass descriptor.
  47759. *
  47760. * @type {?Object}
  47761. * @default null
  47762. */
  47763. this.defaultRenderPassdescriptor = null;
  47764. /**
  47765. * A reference to a backend module holding common utility functions.
  47766. *
  47767. * @type {WebGPUUtils}
  47768. */
  47769. this.utils = new WebGPUUtils( this );
  47770. /**
  47771. * A reference to a backend module holding shader attribute-related
  47772. * utility functions.
  47773. *
  47774. * @type {WebGPUAttributeUtils}
  47775. */
  47776. this.attributeUtils = new WebGPUAttributeUtils( this );
  47777. /**
  47778. * A reference to a backend module holding shader binding-related
  47779. * utility functions.
  47780. *
  47781. * @type {WebGPUBindingUtils}
  47782. */
  47783. this.bindingUtils = new WebGPUBindingUtils( this );
  47784. /**
  47785. * A reference to a backend module holding shader pipeline-related
  47786. * utility functions.
  47787. *
  47788. * @type {WebGPUPipelineUtils}
  47789. */
  47790. this.pipelineUtils = new WebGPUPipelineUtils( this );
  47791. /**
  47792. * A reference to a backend module holding shader texture-related
  47793. * utility functions.
  47794. *
  47795. * @type {WebGPUTextureUtils}
  47796. */
  47797. this.textureUtils = new WebGPUTextureUtils( this );
  47798. /**
  47799. * A map that manages the resolve buffers for occlusion queries.
  47800. *
  47801. * @type {Map<number,GPUBuffer>}
  47802. */
  47803. this.occludedResolveCache = new Map();
  47804. }
  47805. /**
  47806. * Initializes the backend so it is ready for usage.
  47807. *
  47808. * @async
  47809. * @param {Renderer} renderer - The renderer.
  47810. * @return {Promise} A Promise that resolves when the backend has been initialized.
  47811. */
  47812. async init( renderer ) {
  47813. await super.init( renderer );
  47814. //
  47815. const parameters = this.parameters;
  47816. // create the device if it is not passed with parameters
  47817. let device;
  47818. if ( parameters.device === undefined ) {
  47819. const adapterOptions = {
  47820. powerPreference: parameters.powerPreference
  47821. };
  47822. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  47823. if ( adapter === null ) {
  47824. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  47825. }
  47826. // feature support
  47827. const features = Object.values( GPUFeatureName );
  47828. const supportedFeatures = [];
  47829. for ( const name of features ) {
  47830. if ( adapter.features.has( name ) ) {
  47831. supportedFeatures.push( name );
  47832. }
  47833. }
  47834. const deviceDescriptor = {
  47835. requiredFeatures: supportedFeatures,
  47836. requiredLimits: parameters.requiredLimits
  47837. };
  47838. device = await adapter.requestDevice( deviceDescriptor );
  47839. } else {
  47840. device = parameters.device;
  47841. }
  47842. device.lost.then( ( info ) => {
  47843. const deviceLossInfo = {
  47844. api: 'WebGPU',
  47845. message: info.message || 'Unknown reason',
  47846. reason: info.reason || null,
  47847. originalEvent: info
  47848. };
  47849. renderer.onDeviceLost( deviceLossInfo );
  47850. } );
  47851. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  47852. this.device = device;
  47853. this.context = context;
  47854. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  47855. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  47856. this.context.configure( {
  47857. device: this.device,
  47858. format: this.utils.getPreferredCanvasFormat(),
  47859. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  47860. alphaMode: alphaMode
  47861. } );
  47862. this.updateSize();
  47863. }
  47864. /**
  47865. * The coordinate system of the backend.
  47866. *
  47867. * @type {number}
  47868. * @readonly
  47869. */
  47870. get coordinateSystem() {
  47871. return WebGPUCoordinateSystem;
  47872. }
  47873. /**
  47874. * This method performs a readback operation by moving buffer data from
  47875. * a storage buffer attribute from the GPU to the CPU.
  47876. *
  47877. * @async
  47878. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47879. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47880. */
  47881. async getArrayBufferAsync( attribute ) {
  47882. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47883. }
  47884. /**
  47885. * Returns the backend's rendering context.
  47886. *
  47887. * @return {GPUCanvasContext} The rendering context.
  47888. */
  47889. getContext() {
  47890. return this.context;
  47891. }
  47892. /**
  47893. * Returns the default render pass descriptor.
  47894. *
  47895. * In WebGPU, the default framebuffer must be configured
  47896. * like custom framebuffers so the backend needs a render
  47897. * pass descriptor even when rendering directly to screen.
  47898. *
  47899. * @private
  47900. * @return {Object} The render pass descriptor.
  47901. */
  47902. _getDefaultRenderPassDescriptor() {
  47903. let descriptor = this.defaultRenderPassdescriptor;
  47904. if ( descriptor === null ) {
  47905. const renderer = this.renderer;
  47906. descriptor = {
  47907. colorAttachments: [ {
  47908. view: null
  47909. } ],
  47910. };
  47911. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  47912. descriptor.depthStencilAttachment = {
  47913. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  47914. };
  47915. }
  47916. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47917. if ( this.renderer.samples > 0 ) {
  47918. colorAttachment.view = this.colorBuffer.createView();
  47919. } else {
  47920. colorAttachment.resolveTarget = undefined;
  47921. }
  47922. this.defaultRenderPassdescriptor = descriptor;
  47923. }
  47924. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47925. if ( this.renderer.samples > 0 ) {
  47926. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  47927. } else {
  47928. colorAttachment.view = this.context.getCurrentTexture().createView();
  47929. }
  47930. return descriptor;
  47931. }
  47932. /**
  47933. * Returns the render pass descriptor for the given render context.
  47934. *
  47935. * @private
  47936. * @param {RenderContext} renderContext - The render context.
  47937. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  47938. * @return {Object} The render pass descriptor.
  47939. */
  47940. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  47941. const renderTarget = renderContext.renderTarget;
  47942. const renderTargetData = this.get( renderTarget );
  47943. let descriptors = renderTargetData.descriptors;
  47944. if ( descriptors === undefined ||
  47945. renderTargetData.width !== renderTarget.width ||
  47946. renderTargetData.height !== renderTarget.height ||
  47947. renderTargetData.dimensions !== renderTarget.dimensions ||
  47948. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  47949. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  47950. renderTargetData.samples !== renderTarget.samples ||
  47951. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  47952. ) {
  47953. descriptors = {};
  47954. renderTargetData.descriptors = descriptors;
  47955. // dispose
  47956. const onDispose = () => {
  47957. renderTarget.removeEventListener( 'dispose', onDispose );
  47958. this.delete( renderTarget );
  47959. };
  47960. renderTarget.addEventListener( 'dispose', onDispose );
  47961. }
  47962. const cacheKey = renderContext.getCacheKey();
  47963. let descriptor = descriptors[ cacheKey ];
  47964. if ( descriptor === undefined ) {
  47965. const textures = renderContext.textures;
  47966. const colorAttachments = [];
  47967. let sliceIndex;
  47968. for ( let i = 0; i < textures.length; i ++ ) {
  47969. const textureData = this.get( textures[ i ] );
  47970. const viewDescriptor = {
  47971. label: `colorAttachment_${ i }`,
  47972. baseMipLevel: renderContext.activeMipmapLevel,
  47973. mipLevelCount: 1,
  47974. baseArrayLayer: renderContext.activeCubeFace,
  47975. arrayLayerCount: 1,
  47976. dimension: GPUTextureViewDimension.TwoD
  47977. };
  47978. if ( renderTarget.isRenderTarget3D ) {
  47979. sliceIndex = renderContext.activeCubeFace;
  47980. viewDescriptor.baseArrayLayer = 0;
  47981. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  47982. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47983. } else if ( renderTarget.isRenderTargetArray ) {
  47984. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  47985. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47986. }
  47987. const textureView = textureData.texture.createView( viewDescriptor );
  47988. let view, resolveTarget;
  47989. if ( textureData.msaaTexture !== undefined ) {
  47990. view = textureData.msaaTexture.createView();
  47991. resolveTarget = textureView;
  47992. } else {
  47993. view = textureView;
  47994. resolveTarget = undefined;
  47995. }
  47996. colorAttachments.push( {
  47997. view,
  47998. depthSlice: sliceIndex,
  47999. resolveTarget,
  48000. loadOp: GPULoadOp.Load,
  48001. storeOp: GPUStoreOp.Store,
  48002. ...colorAttachmentsConfig
  48003. } );
  48004. }
  48005. descriptor = {
  48006. colorAttachments,
  48007. };
  48008. if ( renderContext.depth ) {
  48009. const depthTextureData = this.get( renderContext.depthTexture );
  48010. const depthStencilAttachment = {
  48011. view: depthTextureData.texture.createView()
  48012. };
  48013. descriptor.depthStencilAttachment = depthStencilAttachment;
  48014. }
  48015. descriptors[ cacheKey ] = descriptor;
  48016. renderTargetData.width = renderTarget.width;
  48017. renderTargetData.height = renderTarget.height;
  48018. renderTargetData.samples = renderTarget.samples;
  48019. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  48020. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  48021. renderTargetData.dimensions = renderTarget.dimensions;
  48022. renderTargetData.depthSlice = sliceIndex;
  48023. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  48024. }
  48025. return descriptor;
  48026. }
  48027. /**
  48028. * This method is executed at the beginning of a render call and prepares
  48029. * the WebGPU state for upcoming render calls
  48030. *
  48031. * @param {RenderContext} renderContext - The render context.
  48032. */
  48033. beginRender( renderContext ) {
  48034. const renderContextData = this.get( renderContext );
  48035. const device = this.device;
  48036. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48037. let occlusionQuerySet;
  48038. if ( occlusionQueryCount > 0 ) {
  48039. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  48040. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  48041. // Get a reference to the array of objects with queries. The renderContextData property
  48042. // can be changed by another render pass before the buffer.mapAsyc() completes.
  48043. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  48044. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  48045. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48046. //
  48047. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  48048. renderContextData.occlusionQuerySet = occlusionQuerySet;
  48049. renderContextData.occlusionQueryIndex = 0;
  48050. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48051. renderContextData.lastOcclusionObject = null;
  48052. }
  48053. let descriptor;
  48054. if ( renderContext.textures === null ) {
  48055. descriptor = this._getDefaultRenderPassDescriptor();
  48056. } else {
  48057. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  48058. }
  48059. this.initTimestampQuery( renderContext, descriptor );
  48060. descriptor.occlusionQuerySet = occlusionQuerySet;
  48061. const depthStencilAttachment = descriptor.depthStencilAttachment;
  48062. if ( renderContext.textures !== null ) {
  48063. const colorAttachments = descriptor.colorAttachments;
  48064. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  48065. const colorAttachment = colorAttachments[ i ];
  48066. if ( renderContext.clearColor ) {
  48067. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  48068. colorAttachment.loadOp = GPULoadOp.Clear;
  48069. colorAttachment.storeOp = GPUStoreOp.Store;
  48070. } else {
  48071. colorAttachment.loadOp = GPULoadOp.Load;
  48072. colorAttachment.storeOp = GPUStoreOp.Store;
  48073. }
  48074. }
  48075. } else {
  48076. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48077. if ( renderContext.clearColor ) {
  48078. colorAttachment.clearValue = renderContext.clearColorValue;
  48079. colorAttachment.loadOp = GPULoadOp.Clear;
  48080. colorAttachment.storeOp = GPUStoreOp.Store;
  48081. } else {
  48082. colorAttachment.loadOp = GPULoadOp.Load;
  48083. colorAttachment.storeOp = GPUStoreOp.Store;
  48084. }
  48085. }
  48086. //
  48087. if ( renderContext.depth ) {
  48088. if ( renderContext.clearDepth ) {
  48089. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  48090. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48091. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48092. } else {
  48093. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48094. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48095. }
  48096. }
  48097. if ( renderContext.stencil ) {
  48098. if ( renderContext.clearStencil ) {
  48099. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  48100. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48101. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48102. } else {
  48103. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48104. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48105. }
  48106. }
  48107. //
  48108. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  48109. const currentPass = encoder.beginRenderPass( descriptor );
  48110. //
  48111. renderContextData.descriptor = descriptor;
  48112. renderContextData.encoder = encoder;
  48113. renderContextData.currentPass = currentPass;
  48114. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48115. renderContextData.renderBundles = [];
  48116. //
  48117. if ( renderContext.viewport ) {
  48118. this.updateViewport( renderContext );
  48119. }
  48120. if ( renderContext.scissor ) {
  48121. const { x, y, width, height } = renderContext.scissorValue;
  48122. currentPass.setScissorRect( x, y, width, height );
  48123. }
  48124. }
  48125. /**
  48126. * This method is executed at the end of a render call and finalizes work
  48127. * after draw calls.
  48128. *
  48129. * @param {RenderContext} renderContext - The render context.
  48130. */
  48131. finishRender( renderContext ) {
  48132. const renderContextData = this.get( renderContext );
  48133. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48134. if ( renderContextData.renderBundles.length > 0 ) {
  48135. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  48136. }
  48137. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48138. renderContextData.currentPass.endOcclusionQuery();
  48139. }
  48140. renderContextData.currentPass.end();
  48141. if ( occlusionQueryCount > 0 ) {
  48142. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  48143. //
  48144. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  48145. if ( queryResolveBuffer === undefined ) {
  48146. queryResolveBuffer = this.device.createBuffer(
  48147. {
  48148. size: bufferSize,
  48149. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48150. }
  48151. );
  48152. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  48153. }
  48154. //
  48155. const readBuffer = this.device.createBuffer(
  48156. {
  48157. size: bufferSize,
  48158. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48159. }
  48160. );
  48161. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  48162. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  48163. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  48164. renderContextData.occlusionQueryBuffer = readBuffer;
  48165. //
  48166. this.resolveOccludedAsync( renderContext );
  48167. }
  48168. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  48169. //
  48170. if ( renderContext.textures !== null ) {
  48171. const textures = renderContext.textures;
  48172. for ( let i = 0; i < textures.length; i ++ ) {
  48173. const texture = textures[ i ];
  48174. if ( texture.generateMipmaps === true ) {
  48175. this.textureUtils.generateMipmaps( texture );
  48176. }
  48177. }
  48178. }
  48179. }
  48180. /**
  48181. * Returns `true` if the given 3D object is fully occluded by other
  48182. * 3D objects in the scene.
  48183. *
  48184. * @param {RenderContext} renderContext - The render context.
  48185. * @param {Object3D} object - The 3D object to test.
  48186. * @return {boolean} Whether the 3D object is fully occluded or not.
  48187. */
  48188. isOccluded( renderContext, object ) {
  48189. const renderContextData = this.get( renderContext );
  48190. return renderContextData.occluded && renderContextData.occluded.has( object );
  48191. }
  48192. /**
  48193. * This method processes the result of occlusion queries and writes it
  48194. * into render context data.
  48195. *
  48196. * @async
  48197. * @param {RenderContext} renderContext - The render context.
  48198. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  48199. */
  48200. async resolveOccludedAsync( renderContext ) {
  48201. const renderContextData = this.get( renderContext );
  48202. // handle occlusion query results
  48203. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  48204. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  48205. const occluded = new WeakSet();
  48206. renderContextData.currentOcclusionQueryObjects = null;
  48207. renderContextData.currentOcclusionQueryBuffer = null;
  48208. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  48209. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  48210. const results = new BigUint64Array( buffer );
  48211. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  48212. if ( results[ i ] === BigInt( 0 ) ) {
  48213. occluded.add( currentOcclusionQueryObjects[ i ] );
  48214. }
  48215. }
  48216. currentOcclusionQueryBuffer.destroy();
  48217. renderContextData.occluded = occluded;
  48218. }
  48219. }
  48220. /**
  48221. * Updates the viewport with the values from the given render context.
  48222. *
  48223. * @param {RenderContext} renderContext - The render context.
  48224. */
  48225. updateViewport( renderContext ) {
  48226. const { currentPass } = this.get( renderContext );
  48227. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  48228. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  48229. }
  48230. /**
  48231. * Returns the clear color and alpha into a single
  48232. * color object.
  48233. *
  48234. * @return {Color4} The clear color.
  48235. */
  48236. getClearColor() {
  48237. const clearColor = super.getClearColor();
  48238. // only premultiply alpha when alphaMode is "premultiplied"
  48239. if ( this.renderer.alpha === true ) {
  48240. clearColor.r *= clearColor.a;
  48241. clearColor.g *= clearColor.a;
  48242. clearColor.b *= clearColor.a;
  48243. }
  48244. return clearColor;
  48245. }
  48246. /**
  48247. * Performs a clear operation.
  48248. *
  48249. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48250. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48251. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48252. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  48253. */
  48254. clear( color, depth, stencil, renderTargetContext = null ) {
  48255. const device = this.device;
  48256. const renderer = this.renderer;
  48257. let colorAttachments = [];
  48258. let depthStencilAttachment;
  48259. let clearValue;
  48260. let supportsDepth;
  48261. let supportsStencil;
  48262. if ( color ) {
  48263. const clearColor = this.getClearColor();
  48264. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  48265. }
  48266. if ( renderTargetContext === null ) {
  48267. supportsDepth = renderer.depth;
  48268. supportsStencil = renderer.stencil;
  48269. const descriptor = this._getDefaultRenderPassDescriptor();
  48270. if ( color ) {
  48271. colorAttachments = descriptor.colorAttachments;
  48272. const colorAttachment = colorAttachments[ 0 ];
  48273. colorAttachment.clearValue = clearValue;
  48274. colorAttachment.loadOp = GPULoadOp.Clear;
  48275. colorAttachment.storeOp = GPUStoreOp.Store;
  48276. }
  48277. if ( supportsDepth || supportsStencil ) {
  48278. depthStencilAttachment = descriptor.depthStencilAttachment;
  48279. }
  48280. } else {
  48281. supportsDepth = renderTargetContext.depth;
  48282. supportsStencil = renderTargetContext.stencil;
  48283. if ( color ) {
  48284. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  48285. colorAttachments = descriptor.colorAttachments;
  48286. }
  48287. if ( supportsDepth || supportsStencil ) {
  48288. const depthTextureData = this.get( renderTargetContext.depthTexture );
  48289. depthStencilAttachment = {
  48290. view: depthTextureData.texture.createView()
  48291. };
  48292. }
  48293. }
  48294. //
  48295. if ( supportsDepth ) {
  48296. if ( depth ) {
  48297. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48298. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  48299. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48300. } else {
  48301. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48302. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48303. }
  48304. }
  48305. //
  48306. if ( supportsStencil ) {
  48307. if ( stencil ) {
  48308. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48309. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  48310. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48311. } else {
  48312. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48313. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48314. }
  48315. }
  48316. //
  48317. const encoder = device.createCommandEncoder( { label: 'clear' } );
  48318. const currentPass = encoder.beginRenderPass( {
  48319. colorAttachments,
  48320. depthStencilAttachment
  48321. } );
  48322. currentPass.end();
  48323. device.queue.submit( [ encoder.finish() ] );
  48324. }
  48325. // compute
  48326. /**
  48327. * This method is executed at the beginning of a compute call and
  48328. * prepares the state for upcoming compute tasks.
  48329. *
  48330. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48331. */
  48332. beginCompute( computeGroup ) {
  48333. const groupGPU = this.get( computeGroup );
  48334. const descriptor = {
  48335. label: 'computeGroup_' + computeGroup.id
  48336. };
  48337. this.initTimestampQuery( computeGroup, descriptor );
  48338. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  48339. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  48340. }
  48341. /**
  48342. * Executes a compute command for the given compute node.
  48343. *
  48344. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48345. * @param {Node} computeNode - The compute node.
  48346. * @param {Array<BindGroup>} bindings - The bindings.
  48347. * @param {ComputePipeline} pipeline - The compute pipeline.
  48348. */
  48349. compute( computeGroup, computeNode, bindings, pipeline ) {
  48350. const { passEncoderGPU } = this.get( computeGroup );
  48351. // pipeline
  48352. const pipelineGPU = this.get( pipeline ).pipeline;
  48353. passEncoderGPU.setPipeline( pipelineGPU );
  48354. // bind groups
  48355. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  48356. const bindGroup = bindings[ i ];
  48357. const bindingsData = this.get( bindGroup );
  48358. passEncoderGPU.setBindGroup( i, bindingsData.group );
  48359. }
  48360. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  48361. const computeNodeData = this.get( computeNode );
  48362. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  48363. const { dispatchSize } = computeNodeData;
  48364. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  48365. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  48366. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  48367. } else {
  48368. dispatchSize.x = computeNode.dispatchCount;
  48369. }
  48370. passEncoderGPU.dispatchWorkgroups(
  48371. dispatchSize.x,
  48372. dispatchSize.y,
  48373. dispatchSize.z
  48374. );
  48375. }
  48376. /**
  48377. * This method is executed at the end of a compute call and
  48378. * finalizes work after compute tasks.
  48379. *
  48380. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48381. */
  48382. finishCompute( computeGroup ) {
  48383. const groupData = this.get( computeGroup );
  48384. groupData.passEncoderGPU.end();
  48385. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  48386. }
  48387. /**
  48388. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  48389. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  48390. *
  48391. * @async
  48392. * @return {Promise} A Promise that resolves when synchronization has been finished.
  48393. */
  48394. async waitForGPU() {
  48395. await this.device.queue.onSubmittedWorkDone();
  48396. }
  48397. // render object
  48398. /**
  48399. * Executes a draw command for the given render object.
  48400. *
  48401. * @param {RenderObject} renderObject - The render object to draw.
  48402. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48403. */
  48404. draw( renderObject, info ) {
  48405. const { object, material, context, pipeline } = renderObject;
  48406. const bindings = renderObject.getBindings();
  48407. const renderContextData = this.get( context );
  48408. const pipelineGPU = this.get( pipeline ).pipeline;
  48409. const currentSets = renderContextData.currentSets;
  48410. const passEncoderGPU = renderContextData.currentPass;
  48411. const drawParams = renderObject.getDrawParameters();
  48412. if ( drawParams === null ) return;
  48413. // pipeline
  48414. if ( currentSets.pipeline !== pipelineGPU ) {
  48415. passEncoderGPU.setPipeline( pipelineGPU );
  48416. currentSets.pipeline = pipelineGPU;
  48417. }
  48418. // bind groups
  48419. const currentBindingGroups = currentSets.bindingGroups;
  48420. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  48421. const bindGroup = bindings[ i ];
  48422. const bindingsData = this.get( bindGroup );
  48423. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  48424. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  48425. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  48426. }
  48427. }
  48428. // attributes
  48429. const index = renderObject.getIndex();
  48430. const hasIndex = ( index !== null );
  48431. // index
  48432. if ( hasIndex === true ) {
  48433. if ( currentSets.index !== index ) {
  48434. const buffer = this.get( index ).buffer;
  48435. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  48436. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  48437. currentSets.index = index;
  48438. }
  48439. }
  48440. // vertex buffers
  48441. const vertexBuffers = renderObject.getVertexBuffers();
  48442. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  48443. const vertexBuffer = vertexBuffers[ i ];
  48444. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  48445. const buffer = this.get( vertexBuffer ).buffer;
  48446. passEncoderGPU.setVertexBuffer( i, buffer );
  48447. currentSets.attributes[ i ] = vertexBuffer;
  48448. }
  48449. }
  48450. // occlusion queries - handle multiple consecutive draw calls for an object
  48451. if ( renderContextData.occlusionQuerySet !== undefined ) {
  48452. const lastObject = renderContextData.lastOcclusionObject;
  48453. if ( lastObject !== object ) {
  48454. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  48455. passEncoderGPU.endOcclusionQuery();
  48456. renderContextData.occlusionQueryIndex ++;
  48457. }
  48458. if ( object.occlusionTest === true ) {
  48459. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  48460. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  48461. }
  48462. renderContextData.lastOcclusionObject = object;
  48463. }
  48464. }
  48465. // stencil
  48466. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  48467. passEncoderGPU.setStencilReference( material.stencilRef );
  48468. renderContextData.currentStencilRef = material.stencilRef;
  48469. }
  48470. // draw
  48471. const draw = () => {
  48472. if ( object.isBatchedMesh === true ) {
  48473. const starts = object._multiDrawStarts;
  48474. const counts = object._multiDrawCounts;
  48475. const drawCount = object._multiDrawCount;
  48476. const drawInstances = object._multiDrawInstances;
  48477. for ( let i = 0; i < drawCount; i ++ ) {
  48478. const count = drawInstances ? drawInstances[ i ] : 1;
  48479. const firstInstance = count > 1 ? 0 : i;
  48480. if ( hasIndex === true ) {
  48481. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  48482. } else {
  48483. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  48484. }
  48485. info.update( object, counts[ i ], count );
  48486. }
  48487. } else if ( hasIndex === true ) {
  48488. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  48489. const indirect = renderObject.getIndirect();
  48490. if ( indirect !== null ) {
  48491. const buffer = this.get( indirect ).buffer;
  48492. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  48493. } else {
  48494. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  48495. }
  48496. info.update( object, indexCount, instanceCount );
  48497. } else {
  48498. const { vertexCount, instanceCount, firstVertex } = drawParams;
  48499. const indirect = renderObject.getIndirect();
  48500. if ( indirect !== null ) {
  48501. const buffer = this.get( indirect ).buffer;
  48502. passEncoderGPU.drawIndirect( buffer, 0 );
  48503. } else {
  48504. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  48505. }
  48506. info.update( object, vertexCount, instanceCount );
  48507. }
  48508. };
  48509. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  48510. const cameraData = this.get( renderObject.camera );
  48511. const cameras = renderObject.camera.cameras;
  48512. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  48513. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48514. const bindingsData = this.get( cameraIndex );
  48515. const indexesGPU = [];
  48516. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48517. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48518. data[ 0 ] = i;
  48519. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  48520. indexesGPU.push( bindGroupIndex );
  48521. }
  48522. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48523. }
  48524. const pixelRatio = this.renderer.getPixelRatio();
  48525. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48526. const subCamera = cameras[ i ];
  48527. if ( object.layers.test( subCamera.layers ) ) {
  48528. const vp = subCamera.viewport;
  48529. passEncoderGPU.setViewport(
  48530. Math.floor( vp.x * pixelRatio ),
  48531. Math.floor( vp.y * pixelRatio ),
  48532. Math.floor( vp.width * pixelRatio ),
  48533. Math.floor( vp.height * pixelRatio ),
  48534. context.viewportValue.minDepth,
  48535. context.viewportValue.maxDepth
  48536. );
  48537. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  48538. draw();
  48539. }
  48540. }
  48541. } else {
  48542. draw();
  48543. }
  48544. }
  48545. // cache key
  48546. /**
  48547. * Returns `true` if the render pipeline requires an update.
  48548. *
  48549. * @param {RenderObject} renderObject - The render object.
  48550. * @return {boolean} Whether the render pipeline requires an update or not.
  48551. */
  48552. needsRenderUpdate( renderObject ) {
  48553. const data = this.get( renderObject );
  48554. const { object, material } = renderObject;
  48555. const utils = this.utils;
  48556. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  48557. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  48558. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  48559. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  48560. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  48561. let needsUpdate = false;
  48562. if ( data.material !== material || data.materialVersion !== material.version ||
  48563. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  48564. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  48565. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  48566. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  48567. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  48568. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  48569. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  48570. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  48571. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  48572. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  48573. data.primitiveTopology !== primitiveTopology ||
  48574. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  48575. ) {
  48576. data.material = material; data.materialVersion = material.version;
  48577. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  48578. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  48579. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  48580. data.colorWrite = material.colorWrite;
  48581. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  48582. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  48583. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  48584. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  48585. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  48586. data.sampleCount = sampleCount;
  48587. data.colorSpace = colorSpace;
  48588. data.colorFormat = colorFormat;
  48589. data.depthStencilFormat = depthStencilFormat;
  48590. data.primitiveTopology = primitiveTopology;
  48591. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  48592. needsUpdate = true;
  48593. }
  48594. return needsUpdate;
  48595. }
  48596. /**
  48597. * Returns a cache key that is used to identify render pipelines.
  48598. *
  48599. * @param {RenderObject} renderObject - The render object.
  48600. * @return {string} The cache key.
  48601. */
  48602. getRenderCacheKey( renderObject ) {
  48603. const { object, material } = renderObject;
  48604. const utils = this.utils;
  48605. const renderContext = renderObject.context;
  48606. return [
  48607. material.transparent, material.blending, material.premultipliedAlpha,
  48608. material.blendSrc, material.blendDst, material.blendEquation,
  48609. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  48610. material.colorWrite,
  48611. material.depthWrite, material.depthTest, material.depthFunc,
  48612. material.stencilWrite, material.stencilFunc,
  48613. material.stencilFail, material.stencilZFail, material.stencilZPass,
  48614. material.stencilFuncMask, material.stencilWriteMask,
  48615. material.side,
  48616. utils.getSampleCountRenderContext( renderContext ),
  48617. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  48618. utils.getPrimitiveTopology( object, material ),
  48619. renderObject.getGeometryCacheKey(),
  48620. renderObject.clippingContextCacheKey
  48621. ].join();
  48622. }
  48623. // textures
  48624. /**
  48625. * Creates a GPU sampler for the given texture.
  48626. *
  48627. * @param {Texture} texture - The texture to create the sampler for.
  48628. */
  48629. createSampler( texture ) {
  48630. this.textureUtils.createSampler( texture );
  48631. }
  48632. /**
  48633. * Destroys the GPU sampler for the given texture.
  48634. *
  48635. * @param {Texture} texture - The texture to destroy the sampler for.
  48636. */
  48637. destroySampler( texture ) {
  48638. this.textureUtils.destroySampler( texture );
  48639. }
  48640. /**
  48641. * Creates a default texture for the given texture that can be used
  48642. * as a placeholder until the actual texture is ready for usage.
  48643. *
  48644. * @param {Texture} texture - The texture to create a default texture for.
  48645. */
  48646. createDefaultTexture( texture ) {
  48647. this.textureUtils.createDefaultTexture( texture );
  48648. }
  48649. /**
  48650. * Defines a texture on the GPU for the given texture object.
  48651. *
  48652. * @param {Texture} texture - The texture.
  48653. * @param {Object} [options={}] - Optional configuration parameter.
  48654. */
  48655. createTexture( texture, options ) {
  48656. this.textureUtils.createTexture( texture, options );
  48657. }
  48658. /**
  48659. * Uploads the updated texture data to the GPU.
  48660. *
  48661. * @param {Texture} texture - The texture.
  48662. * @param {Object} [options={}] - Optional configuration parameter.
  48663. */
  48664. updateTexture( texture, options ) {
  48665. this.textureUtils.updateTexture( texture, options );
  48666. }
  48667. /**
  48668. * Generates mipmaps for the given texture.
  48669. *
  48670. * @param {Texture} texture - The texture.
  48671. */
  48672. generateMipmaps( texture ) {
  48673. this.textureUtils.generateMipmaps( texture );
  48674. }
  48675. /**
  48676. * Destroys the GPU data for the given texture object.
  48677. *
  48678. * @param {Texture} texture - The texture.
  48679. */
  48680. destroyTexture( texture ) {
  48681. this.textureUtils.destroyTexture( texture );
  48682. }
  48683. /**
  48684. * Returns texture data as a typed array.
  48685. *
  48686. * @async
  48687. * @param {Texture} texture - The texture to copy.
  48688. * @param {number} x - The x coordinate of the copy origin.
  48689. * @param {number} y - The y coordinate of the copy origin.
  48690. * @param {number} width - The width of the copy.
  48691. * @param {number} height - The height of the copy.
  48692. * @param {number} faceIndex - The face index.
  48693. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48694. */
  48695. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48696. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  48697. }
  48698. /**
  48699. * Inits a time stamp query for the given render context.
  48700. *
  48701. * @param {RenderContext} renderContext - The render context.
  48702. * @param {Object} descriptor - The query descriptor.
  48703. */
  48704. initTimestampQuery( renderContext, descriptor ) {
  48705. if ( ! this.trackTimestamp ) return;
  48706. const type = renderContext.isComputeNode ? 'compute' : 'render';
  48707. if ( ! this.timestampQueryPool[ type ] ) {
  48708. // TODO: Variable maxQueries?
  48709. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  48710. }
  48711. const timestampQueryPool = this.timestampQueryPool[ type ];
  48712. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  48713. descriptor.timestampWrites = {
  48714. querySet: timestampQueryPool.querySet,
  48715. beginningOfPassWriteIndex: baseOffset,
  48716. endOfPassWriteIndex: baseOffset + 1,
  48717. };
  48718. }
  48719. // node builder
  48720. /**
  48721. * Returns a node builder for the given render object.
  48722. *
  48723. * @param {RenderObject} object - The render object.
  48724. * @param {Renderer} renderer - The renderer.
  48725. * @return {WGSLNodeBuilder} The node builder.
  48726. */
  48727. createNodeBuilder( object, renderer ) {
  48728. return new WGSLNodeBuilder( object, renderer );
  48729. }
  48730. // program
  48731. /**
  48732. * Creates a shader program from the given programmable stage.
  48733. *
  48734. * @param {ProgrammableStage} program - The programmable stage.
  48735. */
  48736. createProgram( program ) {
  48737. const programGPU = this.get( program );
  48738. programGPU.module = {
  48739. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  48740. entryPoint: 'main'
  48741. };
  48742. }
  48743. /**
  48744. * Destroys the shader program of the given programmable stage.
  48745. *
  48746. * @param {ProgrammableStage} program - The programmable stage.
  48747. */
  48748. destroyProgram( program ) {
  48749. this.delete( program );
  48750. }
  48751. // pipelines
  48752. /**
  48753. * Creates a render pipeline for the given render object.
  48754. *
  48755. * @param {RenderObject} renderObject - The render object.
  48756. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48757. */
  48758. createRenderPipeline( renderObject, promises ) {
  48759. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  48760. }
  48761. /**
  48762. * Creates a compute pipeline for the given compute node.
  48763. *
  48764. * @param {ComputePipeline} computePipeline - The compute pipeline.
  48765. * @param {Array<BindGroup>} bindings - The bindings.
  48766. */
  48767. createComputePipeline( computePipeline, bindings ) {
  48768. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  48769. }
  48770. /**
  48771. * Prepares the state for encoding render bundles.
  48772. *
  48773. * @param {RenderContext} renderContext - The render context.
  48774. */
  48775. beginBundle( renderContext ) {
  48776. const renderContextData = this.get( renderContext );
  48777. renderContextData._currentPass = renderContextData.currentPass;
  48778. renderContextData._currentSets = renderContextData.currentSets;
  48779. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48780. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  48781. }
  48782. /**
  48783. * After processing render bundles this method finalizes related work.
  48784. *
  48785. * @param {RenderContext} renderContext - The render context.
  48786. * @param {RenderBundle} bundle - The render bundle.
  48787. */
  48788. finishBundle( renderContext, bundle ) {
  48789. const renderContextData = this.get( renderContext );
  48790. const bundleEncoder = renderContextData.currentPass;
  48791. const bundleGPU = bundleEncoder.finish();
  48792. this.get( bundle ).bundleGPU = bundleGPU;
  48793. // restore render pass state
  48794. renderContextData.currentSets = renderContextData._currentSets;
  48795. renderContextData.currentPass = renderContextData._currentPass;
  48796. }
  48797. /**
  48798. * Adds a render bundle to the render context data.
  48799. *
  48800. * @param {RenderContext} renderContext - The render context.
  48801. * @param {RenderBundle} bundle - The render bundle to add.
  48802. */
  48803. addBundle( renderContext, bundle ) {
  48804. const renderContextData = this.get( renderContext );
  48805. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  48806. }
  48807. // bindings
  48808. /**
  48809. * Creates bindings from the given bind group definition.
  48810. *
  48811. * @param {BindGroup} bindGroup - The bind group.
  48812. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48813. * @param {number} cacheIndex - The cache index.
  48814. * @param {number} version - The version.
  48815. */
  48816. createBindings( bindGroup, bindings, cacheIndex, version ) {
  48817. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48818. }
  48819. /**
  48820. * Updates the given bind group definition.
  48821. *
  48822. * @param {BindGroup} bindGroup - The bind group.
  48823. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48824. * @param {number} cacheIndex - The cache index.
  48825. * @param {number} version - The version.
  48826. */
  48827. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  48828. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48829. }
  48830. /**
  48831. * Updates a buffer binding.
  48832. *
  48833. * @param {Buffer} binding - The buffer binding to update.
  48834. */
  48835. updateBinding( binding ) {
  48836. this.bindingUtils.updateBinding( binding );
  48837. }
  48838. // attributes
  48839. /**
  48840. * Creates the buffer of an indexed shader attribute.
  48841. *
  48842. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48843. */
  48844. createIndexAttribute( attribute ) {
  48845. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48846. }
  48847. /**
  48848. * Creates the GPU buffer of a shader attribute.
  48849. *
  48850. * @param {BufferAttribute} attribute - The buffer attribute.
  48851. */
  48852. createAttribute( attribute ) {
  48853. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48854. }
  48855. /**
  48856. * Creates the GPU buffer of a storage attribute.
  48857. *
  48858. * @param {BufferAttribute} attribute - The buffer attribute.
  48859. */
  48860. createStorageAttribute( attribute ) {
  48861. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48862. }
  48863. /**
  48864. * Creates the GPU buffer of an indirect storage attribute.
  48865. *
  48866. * @param {BufferAttribute} attribute - The buffer attribute.
  48867. */
  48868. createIndirectStorageAttribute( attribute ) {
  48869. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48870. }
  48871. /**
  48872. * Updates the GPU buffer of a shader attribute.
  48873. *
  48874. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48875. */
  48876. updateAttribute( attribute ) {
  48877. this.attributeUtils.updateAttribute( attribute );
  48878. }
  48879. /**
  48880. * Destroys the GPU buffer of a shader attribute.
  48881. *
  48882. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48883. */
  48884. destroyAttribute( attribute ) {
  48885. this.attributeUtils.destroyAttribute( attribute );
  48886. }
  48887. // canvas
  48888. /**
  48889. * Triggers an update of the default render pass descriptor.
  48890. */
  48891. updateSize() {
  48892. this.colorBuffer = this.textureUtils.getColorBuffer();
  48893. this.defaultRenderPassdescriptor = null;
  48894. }
  48895. // utils public
  48896. /**
  48897. * Returns the maximum anisotropy texture filtering value.
  48898. *
  48899. * @return {number} The maximum anisotropy texture filtering value.
  48900. */
  48901. getMaxAnisotropy() {
  48902. return 16;
  48903. }
  48904. /**
  48905. * Checks if the given feature is supported by the backend.
  48906. *
  48907. * @param {string} name - The feature's name.
  48908. * @return {boolean} Whether the feature is supported or not.
  48909. */
  48910. hasFeature( name ) {
  48911. return this.device.features.has( name );
  48912. }
  48913. /**
  48914. * Copies data of the given source texture to the given destination texture.
  48915. *
  48916. * @param {Texture} srcTexture - The source texture.
  48917. * @param {Texture} dstTexture - The destination texture.
  48918. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  48919. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48920. * @param {number} [level=0] - The mip level to copy.
  48921. */
  48922. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  48923. let dstX = 0;
  48924. let dstY = 0;
  48925. let dstLayer = 0;
  48926. let srcX = 0;
  48927. let srcY = 0;
  48928. let srcLayer = 0;
  48929. let srcWidth = srcTexture.image.width;
  48930. let srcHeight = srcTexture.image.height;
  48931. if ( srcRegion !== null ) {
  48932. srcX = srcRegion.x;
  48933. srcY = srcRegion.y;
  48934. srcLayer = srcRegion.z || 0;
  48935. srcWidth = srcRegion.width;
  48936. srcHeight = srcRegion.height;
  48937. }
  48938. if ( dstPosition !== null ) {
  48939. dstX = dstPosition.x;
  48940. dstY = dstPosition.y;
  48941. dstLayer = dstPosition.z || 0;
  48942. }
  48943. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  48944. const sourceGPU = this.get( srcTexture ).texture;
  48945. const destinationGPU = this.get( dstTexture ).texture;
  48946. encoder.copyTextureToTexture(
  48947. {
  48948. texture: sourceGPU,
  48949. mipLevel: level,
  48950. origin: { x: srcX, y: srcY, z: srcLayer }
  48951. },
  48952. {
  48953. texture: destinationGPU,
  48954. mipLevel: level,
  48955. origin: { x: dstX, y: dstY, z: dstLayer }
  48956. },
  48957. [
  48958. srcWidth,
  48959. srcHeight,
  48960. 1
  48961. ]
  48962. );
  48963. this.device.queue.submit( [ encoder.finish() ] );
  48964. }
  48965. /**
  48966. * Copies the current bound framebuffer to the given texture.
  48967. *
  48968. * @param {Texture} texture - The destination texture.
  48969. * @param {RenderContext} renderContext - The render context.
  48970. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48971. */
  48972. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48973. const renderContextData = this.get( renderContext );
  48974. let sourceGPU = null;
  48975. if ( renderContext.renderTarget ) {
  48976. if ( texture.isDepthTexture ) {
  48977. sourceGPU = this.get( renderContext.depthTexture ).texture;
  48978. } else {
  48979. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  48980. }
  48981. } else {
  48982. if ( texture.isDepthTexture ) {
  48983. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  48984. } else {
  48985. sourceGPU = this.context.getCurrentTexture();
  48986. }
  48987. }
  48988. const destinationGPU = this.get( texture ).texture;
  48989. if ( sourceGPU.format !== destinationGPU.format ) {
  48990. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  48991. return;
  48992. }
  48993. let encoder;
  48994. if ( renderContextData.currentPass ) {
  48995. renderContextData.currentPass.end();
  48996. encoder = renderContextData.encoder;
  48997. } else {
  48998. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  48999. }
  49000. encoder.copyTextureToTexture(
  49001. {
  49002. texture: sourceGPU,
  49003. origin: [ rectangle.x, rectangle.y, 0 ],
  49004. },
  49005. {
  49006. texture: destinationGPU
  49007. },
  49008. [
  49009. rectangle.z,
  49010. rectangle.w
  49011. ]
  49012. );
  49013. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  49014. if ( renderContextData.currentPass ) {
  49015. const { descriptor } = renderContextData;
  49016. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  49017. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  49018. }
  49019. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49020. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49021. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  49022. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49023. if ( renderContext.viewport ) {
  49024. this.updateViewport( renderContext );
  49025. }
  49026. if ( renderContext.scissor ) {
  49027. const { x, y, width, height } = renderContext.scissorValue;
  49028. renderContextData.currentPass.setScissorRect( x, y, width, height );
  49029. }
  49030. } else {
  49031. this.device.queue.submit( [ encoder.finish() ] );
  49032. }
  49033. }
  49034. }
  49035. class IESSpotLight extends SpotLight {
  49036. constructor( color, intensity, distance, angle, penumbra, decay ) {
  49037. super( color, intensity, distance, angle, penumbra, decay );
  49038. this.iesMap = null;
  49039. }
  49040. copy( source, recursive ) {
  49041. super.copy( source, recursive );
  49042. this.iesMap = source.iesMap;
  49043. return this;
  49044. }
  49045. }
  49046. /**
  49047. * This version of a node library represents a basic version
  49048. * just focusing on lights and tone mapping techniques.
  49049. *
  49050. * @private
  49051. * @augments NodeLibrary
  49052. */
  49053. class BasicNodeLibrary extends NodeLibrary {
  49054. /**
  49055. * Constructs a new basic node library.
  49056. */
  49057. constructor() {
  49058. super();
  49059. this.addLight( PointLightNode, PointLight );
  49060. this.addLight( DirectionalLightNode, DirectionalLight );
  49061. this.addLight( RectAreaLightNode, RectAreaLight );
  49062. this.addLight( SpotLightNode, SpotLight );
  49063. this.addLight( AmbientLightNode, AmbientLight );
  49064. this.addLight( HemisphereLightNode, HemisphereLight );
  49065. this.addLight( LightProbeNode, LightProbe );
  49066. this.addLight( IESSpotLightNode, IESSpotLight );
  49067. this.addToneMapping( linearToneMapping, LinearToneMapping );
  49068. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  49069. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  49070. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  49071. this.addToneMapping( agxToneMapping, AgXToneMapping );
  49072. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  49073. }
  49074. }
  49075. /**
  49076. * This alternative version of {@link WebGPURenderer} only supports node materials.
  49077. * So classes like `MeshBasicMaterial` are not compatible.
  49078. *
  49079. * @private
  49080. * @augments Renderer
  49081. */
  49082. class WebGPURenderer extends Renderer {
  49083. /**
  49084. * Constructs a new WebGPU renderer.
  49085. *
  49086. * @param {Object} parameters - The configuration parameter.
  49087. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49088. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49089. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49090. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49091. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49092. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  49093. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  49094. * @param {number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49095. * @param {number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  49096. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  49097. */
  49098. constructor( parameters = {} ) {
  49099. let BackendClass;
  49100. if ( parameters.forceWebGL ) {
  49101. BackendClass = WebGLBackend;
  49102. } else {
  49103. BackendClass = WebGPUBackend;
  49104. parameters.getFallback = () => {
  49105. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  49106. return new WebGLBackend( parameters );
  49107. };
  49108. }
  49109. const backend = new BackendClass( parameters );
  49110. super( backend, parameters );
  49111. /**
  49112. * The generic default value is overwritten with the
  49113. * standard node library for type mapping. Material
  49114. * mapping is not supported with this version.
  49115. *
  49116. * @type {BasicNodeLibrary}
  49117. */
  49118. this.library = new BasicNodeLibrary();
  49119. /**
  49120. * This flag can be used for type testing.
  49121. *
  49122. * @type {boolean}
  49123. * @readonly
  49124. * @default true
  49125. */
  49126. this.isWebGPURenderer = true;
  49127. }
  49128. }
  49129. /**
  49130. * A specialized group which enables applications access to the
  49131. * Render Bundle API of WebGPU. The group with all its descendant nodes
  49132. * are considered as one render bundle and processed as such by
  49133. * the renderer.
  49134. *
  49135. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  49136. * With a WebGL backend, the group can technically be rendered but without
  49137. * any performance improvements.
  49138. *
  49139. * @augments Group
  49140. */
  49141. class BundleGroup extends Group {
  49142. /**
  49143. * Constructs a new bundle group.
  49144. */
  49145. constructor() {
  49146. super();
  49147. /**
  49148. * This flag can be used for type testing.
  49149. *
  49150. * @type {boolean}
  49151. * @readonly
  49152. * @default true
  49153. */
  49154. this.isBundleGroup = true;
  49155. /**
  49156. * This property is only relevant for detecting types
  49157. * during serialization/deserialization. It should always
  49158. * match the class name.
  49159. *
  49160. * @type {string}
  49161. * @readonly
  49162. * @default 'BundleGroup'
  49163. */
  49164. this.type = 'BundleGroup';
  49165. /**
  49166. * Whether the bundle is static or not. When set to `true`, the structure
  49167. * is assumed to be static and does not change. E.g. no new objects are
  49168. * added to the group
  49169. *
  49170. * If a change is required, an update can still be forced by setting the
  49171. * `needsUpdate` flag to `true`.
  49172. *
  49173. * @type {boolean}
  49174. * @default true
  49175. */
  49176. this.static = true;
  49177. /**
  49178. * The bundle group's version.
  49179. *
  49180. * @type {number}
  49181. * @readonly
  49182. * @default 0
  49183. */
  49184. this.version = 0;
  49185. }
  49186. /**
  49187. * Set this property to `true` when the bundle group has changed.
  49188. *
  49189. * @type {boolean}
  49190. * @default false
  49191. * @param {boolean} value
  49192. */
  49193. set needsUpdate( value ) {
  49194. if ( value === true ) this.version ++;
  49195. }
  49196. }
  49197. /**
  49198. * This module is responsible to manage the post processing setups in apps.
  49199. * You usually create a single instance of this class and use it to define
  49200. * the output of your post processing effect chain.
  49201. * ```js
  49202. * const postProcessing = new PostProcessing( renderer );
  49203. *
  49204. * const scenePass = pass( scene, camera );
  49205. *
  49206. * postProcessing.outputNode = scenePass;
  49207. * ```
  49208. */
  49209. class PostProcessing {
  49210. /**
  49211. * Constructs a new post processing management module.
  49212. *
  49213. * @param {Renderer} renderer - A reference to the renderer.
  49214. * @param {Node<vec4>} outputNode - An optional output node.
  49215. */
  49216. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  49217. /**
  49218. * A reference to the renderer.
  49219. *
  49220. * @type {Renderer}
  49221. */
  49222. this.renderer = renderer;
  49223. /**
  49224. * A node which defines the final output of the post
  49225. * processing. This is usually the last node in a chain
  49226. * of effect nodes.
  49227. *
  49228. * @type {Node<vec4>}
  49229. */
  49230. this.outputNode = outputNode;
  49231. /**
  49232. * Whether the default output tone mapping and color
  49233. * space transformation should be enabled or not.
  49234. *
  49235. * It is enabled by default by it must be disabled when
  49236. * effects must be executed after tone mapping and color
  49237. * space conversion. A typical example is FXAA which
  49238. * requires sRGB input.
  49239. *
  49240. * When set to `false`, the app must control the output
  49241. * transformation with `RenderOutputNode`.
  49242. *
  49243. * ```js
  49244. * const outputPass = renderOutput( scenePass );
  49245. * ```
  49246. *
  49247. * @type {boolean}
  49248. */
  49249. this.outputColorTransform = true;
  49250. /**
  49251. * Must be set to `true` when the output node changes.
  49252. *
  49253. * @type {Node<vec4>}
  49254. */
  49255. this.needsUpdate = true;
  49256. const material = new NodeMaterial();
  49257. material.name = 'PostProcessing';
  49258. /**
  49259. * The full screen quad that is used to render
  49260. * the effects.
  49261. *
  49262. * @private
  49263. * @type {QuadMesh}
  49264. */
  49265. this._quadMesh = new QuadMesh( material );
  49266. }
  49267. /**
  49268. * When `PostProcessing` is used to apply post processing effects,
  49269. * the application must use this version of `render()` inside
  49270. * its animation loop (not the one from the renderer).
  49271. */
  49272. render() {
  49273. this._update();
  49274. const renderer = this.renderer;
  49275. const toneMapping = renderer.toneMapping;
  49276. const outputColorSpace = renderer.outputColorSpace;
  49277. renderer.toneMapping = NoToneMapping;
  49278. renderer.outputColorSpace = LinearSRGBColorSpace;
  49279. //
  49280. const currentXR = renderer.xr.enabled;
  49281. renderer.xr.enabled = false;
  49282. this._quadMesh.render( renderer );
  49283. renderer.xr.enabled = currentXR;
  49284. //
  49285. renderer.toneMapping = toneMapping;
  49286. renderer.outputColorSpace = outputColorSpace;
  49287. }
  49288. /**
  49289. * Frees internal resources.
  49290. */
  49291. dispose() {
  49292. this._quadMesh.material.dispose();
  49293. }
  49294. /**
  49295. * Updates the state of the module.
  49296. *
  49297. * @private
  49298. */
  49299. _update() {
  49300. if ( this.needsUpdate === true ) {
  49301. const renderer = this.renderer;
  49302. const toneMapping = renderer.toneMapping;
  49303. const outputColorSpace = renderer.outputColorSpace;
  49304. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  49305. this._quadMesh.material.needsUpdate = true;
  49306. this.needsUpdate = false;
  49307. }
  49308. }
  49309. /**
  49310. * When `PostProcessing` is used to apply post processing effects,
  49311. * the application must use this version of `renderAsync()` inside
  49312. * its animation loop (not the one from the renderer).
  49313. *
  49314. * @async
  49315. * @return {Promise} A Promise that resolves when the render has been finished.
  49316. */
  49317. async renderAsync() {
  49318. this._update();
  49319. const renderer = this.renderer;
  49320. const toneMapping = renderer.toneMapping;
  49321. const outputColorSpace = renderer.outputColorSpace;
  49322. renderer.toneMapping = NoToneMapping;
  49323. renderer.outputColorSpace = LinearSRGBColorSpace;
  49324. //
  49325. const currentXR = renderer.xr.enabled;
  49326. renderer.xr.enabled = false;
  49327. await this._quadMesh.renderAsync( renderer );
  49328. renderer.xr.enabled = currentXR;
  49329. //
  49330. renderer.toneMapping = toneMapping;
  49331. renderer.outputColorSpace = outputColorSpace;
  49332. }
  49333. }
  49334. /**
  49335. * This special type of texture is intended for compute shaders.
  49336. * It can be used to compute the data of a texture with a compute shader.
  49337. *
  49338. * Note: This type of texture can only be used with `WebGPURenderer`
  49339. * and a WebGPU backend.
  49340. *
  49341. * @augments Texture
  49342. */
  49343. class StorageTexture extends Texture {
  49344. /**
  49345. * Constructs a new storage texture.
  49346. *
  49347. * @param {number} [width=1] - The storage texture's width.
  49348. * @param {number} [height=1] - The storage texture's height.
  49349. */
  49350. constructor( width = 1, height = 1 ) {
  49351. super();
  49352. /**
  49353. * The image object which just represents the texture's dimension.
  49354. *
  49355. * @type {{width: number, height: number}}
  49356. */
  49357. this.image = { width, height };
  49358. /**
  49359. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  49360. *
  49361. * @type {number}
  49362. */
  49363. this.magFilter = LinearFilter;
  49364. /**
  49365. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  49366. *
  49367. * @type {number}
  49368. */
  49369. this.minFilter = LinearFilter;
  49370. /**
  49371. * This flag can be used for type testing.
  49372. *
  49373. * @type {boolean}
  49374. * @readonly
  49375. * @default true
  49376. */
  49377. this.isStorageTexture = true;
  49378. }
  49379. }
  49380. /**
  49381. * This special type of buffer attribute is intended for compute shaders.
  49382. * It can be used to encode draw parameters for indirect draw calls.
  49383. *
  49384. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  49385. * and a WebGPU backend.
  49386. *
  49387. * @augments StorageBufferAttribute
  49388. */
  49389. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  49390. /**
  49391. * Constructs a new storage buffer attribute.
  49392. *
  49393. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  49394. * The subsequent parameter is then obsolete.
  49395. * @param {number} itemSize - The item size.
  49396. */
  49397. constructor( count, itemSize ) {
  49398. super( count, itemSize, Uint32Array );
  49399. /**
  49400. * This flag can be used for type testing.
  49401. *
  49402. * @type {boolean}
  49403. * @readonly
  49404. * @default true
  49405. */
  49406. this.isIndirectStorageBufferAttribute = true;
  49407. }
  49408. }
  49409. /**
  49410. * A loader for loading node objects in the three.js JSON Object/Scene format.
  49411. *
  49412. * @augments Loader
  49413. */
  49414. class NodeLoader extends Loader {
  49415. /**
  49416. * Constructs a new node loader.
  49417. *
  49418. * @param {?LoadingManager} manager - A reference to a loading manager.
  49419. */
  49420. constructor( manager ) {
  49421. super( manager );
  49422. /**
  49423. * Represents a dictionary of textures.
  49424. *
  49425. * @type {Object<string,Texture>}
  49426. */
  49427. this.textures = {};
  49428. /**
  49429. * Represents a dictionary of node types.
  49430. *
  49431. * @type {Object<string,Node.constructor>}
  49432. */
  49433. this.nodes = {};
  49434. }
  49435. /**
  49436. * Loads the node definitions from the given URL.
  49437. *
  49438. * @param {string} url - The path/URL of the file to be loaded.
  49439. * @param {Function} onLoad - Will be called when load completes.
  49440. * @param {Function} onProgress - Will be called while load progresses.
  49441. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  49442. */
  49443. load( url, onLoad, onProgress, onError ) {
  49444. const loader = new FileLoader( this.manager );
  49445. loader.setPath( this.path );
  49446. loader.setRequestHeader( this.requestHeader );
  49447. loader.setWithCredentials( this.withCredentials );
  49448. loader.load( url, ( text ) => {
  49449. try {
  49450. onLoad( this.parse( JSON.parse( text ) ) );
  49451. } catch ( e ) {
  49452. if ( onError ) {
  49453. onError( e );
  49454. } else {
  49455. console.error( e );
  49456. }
  49457. this.manager.itemError( url );
  49458. }
  49459. }, onProgress, onError );
  49460. }
  49461. /**
  49462. * Parse the node dependencies for the loaded node.
  49463. *
  49464. * @param {Object} json - The JSON definition
  49465. * @return {Object<string,Node>} A dictionary with node dependencies.
  49466. */
  49467. parseNodes( json ) {
  49468. const nodes = {};
  49469. if ( json !== undefined ) {
  49470. for ( const nodeJSON of json ) {
  49471. const { uuid, type } = nodeJSON;
  49472. nodes[ uuid ] = this.createNodeFromType( type );
  49473. nodes[ uuid ].uuid = uuid;
  49474. }
  49475. const meta = { nodes, textures: this.textures };
  49476. for ( const nodeJSON of json ) {
  49477. nodeJSON.meta = meta;
  49478. const node = nodes[ nodeJSON.uuid ];
  49479. node.deserialize( nodeJSON );
  49480. delete nodeJSON.meta;
  49481. }
  49482. }
  49483. return nodes;
  49484. }
  49485. /**
  49486. * Parses the node from the given JSON.
  49487. *
  49488. * @param {Object} json - The JSON definition
  49489. * @return {Node} The parsed node.
  49490. */
  49491. parse( json ) {
  49492. const node = this.createNodeFromType( json.type );
  49493. node.uuid = json.uuid;
  49494. const nodes = this.parseNodes( json.nodes );
  49495. const meta = { nodes, textures: this.textures };
  49496. json.meta = meta;
  49497. node.deserialize( json );
  49498. delete json.meta;
  49499. return node;
  49500. }
  49501. /**
  49502. * Defines the dictionary of textures.
  49503. *
  49504. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  49505. * @return {NodeLoader} A reference to this loader.
  49506. */
  49507. setTextures( value ) {
  49508. this.textures = value;
  49509. return this;
  49510. }
  49511. /**
  49512. * Defines the dictionary of node types.
  49513. *
  49514. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49515. * @return {NodeLoader} A reference to this loader.
  49516. */
  49517. setNodes( value ) {
  49518. this.nodes = value;
  49519. return this;
  49520. }
  49521. /**
  49522. * Creates a node object from the given type.
  49523. *
  49524. * @param {string} type - The node type.
  49525. * @return {Node} The created node instance.
  49526. */
  49527. createNodeFromType( type ) {
  49528. if ( this.nodes[ type ] === undefined ) {
  49529. console.error( 'THREE.NodeLoader: Node type not found:', type );
  49530. return float();
  49531. }
  49532. return nodeObject( new this.nodes[ type ]() );
  49533. }
  49534. }
  49535. /**
  49536. * A special type of material loader for loading node materials.
  49537. *
  49538. * @augments MaterialLoader
  49539. */
  49540. class NodeMaterialLoader extends MaterialLoader {
  49541. /**
  49542. * Constructs a new node material loader.
  49543. *
  49544. * @param {?LoadingManager} manager - A reference to a loading manager.
  49545. */
  49546. constructor( manager ) {
  49547. super( manager );
  49548. /**
  49549. * Represents a dictionary of node types.
  49550. *
  49551. * @type {Object<string,Node.constructor>}
  49552. */
  49553. this.nodes = {};
  49554. /**
  49555. * Represents a dictionary of node material types.
  49556. *
  49557. * @type {Object<string,NodeMaterial.constructor>}
  49558. */
  49559. this.nodeMaterials = {};
  49560. }
  49561. /**
  49562. * Parses the node material from the given JSON.
  49563. *
  49564. * @param {Object} json - The JSON definition
  49565. * @return {NodeMaterial}. The parsed material.
  49566. */
  49567. parse( json ) {
  49568. const material = super.parse( json );
  49569. const nodes = this.nodes;
  49570. const inputNodes = json.inputNodes;
  49571. for ( const property in inputNodes ) {
  49572. const uuid = inputNodes[ property ];
  49573. material[ property ] = nodes[ uuid ];
  49574. }
  49575. return material;
  49576. }
  49577. /**
  49578. * Defines the dictionary of node types.
  49579. *
  49580. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49581. * @return {NodeLoader} A reference to this loader.
  49582. */
  49583. setNodes( value ) {
  49584. this.nodes = value;
  49585. return this;
  49586. }
  49587. /**
  49588. * Defines the dictionary of node material types.
  49589. *
  49590. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49591. * @return {NodeLoader} A reference to this loader.
  49592. */
  49593. setNodeMaterials( value ) {
  49594. this.nodeMaterials = value;
  49595. return this;
  49596. }
  49597. /**
  49598. * Creates a node material from the given type.
  49599. *
  49600. * @param {string} type - The node material type.
  49601. * @return {Node} The created node material instance.
  49602. */
  49603. createMaterialFromType( type ) {
  49604. const materialClass = this.nodeMaterials[ type ];
  49605. if ( materialClass !== undefined ) {
  49606. return new materialClass();
  49607. }
  49608. return super.createMaterialFromType( type );
  49609. }
  49610. }
  49611. /**
  49612. * A special type of object loader for loading 3D objects using
  49613. * node materials.
  49614. *
  49615. * @augments ObjectLoader
  49616. */
  49617. class NodeObjectLoader extends ObjectLoader {
  49618. /**
  49619. * Constructs a new node object loader.
  49620. *
  49621. * @param {?LoadingManager} manager - A reference to a loading manager.
  49622. */
  49623. constructor( manager ) {
  49624. super( manager );
  49625. /**
  49626. * Represents a dictionary of node types.
  49627. *
  49628. * @type {Object<string,Node.constructor>}
  49629. */
  49630. this.nodes = {};
  49631. /**
  49632. * Represents a dictionary of node material types.
  49633. *
  49634. * @type {Object<string,NodeMaterial.constructor>}
  49635. */
  49636. this.nodeMaterials = {};
  49637. /**
  49638. * A reference to hold the `nodes` JSON property.
  49639. *
  49640. * @private
  49641. * @type {?Object}
  49642. */
  49643. this._nodesJSON = null;
  49644. }
  49645. /**
  49646. * Defines the dictionary of node types.
  49647. *
  49648. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49649. * @return {NodeLoader} A reference to this loader.
  49650. */
  49651. setNodes( value ) {
  49652. this.nodes = value;
  49653. return this;
  49654. }
  49655. /**
  49656. * Defines the dictionary of node material types.
  49657. *
  49658. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49659. * @return {NodeLoader} A reference to this loader.
  49660. */
  49661. setNodeMaterials( value ) {
  49662. this.nodeMaterials = value;
  49663. return this;
  49664. }
  49665. /**
  49666. * Parses the node objects from the given JSON.
  49667. *
  49668. * @param {Object} json - The JSON definition
  49669. * @param {Function} onLoad - The onLoad callback function.
  49670. * @return {Object3D}. The parsed 3D object.
  49671. */
  49672. parse( json, onLoad ) {
  49673. this._nodesJSON = json.nodes;
  49674. const data = super.parse( json, onLoad );
  49675. this._nodesJSON = null; // dispose
  49676. return data;
  49677. }
  49678. /**
  49679. * Parses the node objects from the given JSON and textures.
  49680. *
  49681. * @param {Object} json - The JSON definition
  49682. * @param {Object<string,Texture>} textures - The texture library.
  49683. * @return {Object<string,Node>}. The parsed nodes.
  49684. */
  49685. parseNodes( json, textures ) {
  49686. if ( json !== undefined ) {
  49687. const loader = new NodeLoader();
  49688. loader.setNodes( this.nodes );
  49689. loader.setTextures( textures );
  49690. return loader.parseNodes( json );
  49691. }
  49692. return {};
  49693. }
  49694. /**
  49695. * Parses the node objects from the given JSON and textures.
  49696. *
  49697. * @param {Object} json - The JSON definition
  49698. * @param {Object<string,Texture>} textures - The texture library.
  49699. * @return {Object<string,NodeMaterial>}. The parsed materials.
  49700. */
  49701. parseMaterials( json, textures ) {
  49702. const materials = {};
  49703. if ( json !== undefined ) {
  49704. const nodes = this.parseNodes( this._nodesJSON, textures );
  49705. const loader = new NodeMaterialLoader();
  49706. loader.setTextures( textures );
  49707. loader.setNodes( nodes );
  49708. loader.setNodeMaterials( this.nodeMaterials );
  49709. for ( let i = 0, l = json.length; i < l; i ++ ) {
  49710. const data = json[ i ];
  49711. materials[ data.uuid ] = loader.parse( data );
  49712. }
  49713. }
  49714. return materials;
  49715. }
  49716. }
  49717. /**
  49718. * In earlier three.js versions, clipping was defined globally
  49719. * on the renderer or on material level. This special version of
  49720. * `THREE.Group` allows to encode the clipping state into the scene
  49721. * graph. Meaning if you create an instance of this group, all
  49722. * descendant 3D objects will be affected by the respective clipping
  49723. * planes.
  49724. *
  49725. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  49726. *
  49727. * @augments Group
  49728. */
  49729. class ClippingGroup extends Group {
  49730. /**
  49731. * Constructs a new clipping group.
  49732. */
  49733. constructor() {
  49734. super();
  49735. /**
  49736. * This flag can be used for type testing.
  49737. *
  49738. * @type {boolean}
  49739. * @readonly
  49740. * @default true
  49741. */
  49742. this.isClippingGroup = true;
  49743. /**
  49744. * An array with clipping planes.
  49745. *
  49746. * @type {Array<Plane>}
  49747. */
  49748. this.clippingPlanes = [];
  49749. /**
  49750. * Whether clipping should be enabled or not.
  49751. *
  49752. * @type {boolean}
  49753. * @default true
  49754. */
  49755. this.enabled = true;
  49756. /**
  49757. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  49758. *
  49759. * @type {boolean}
  49760. * @default false
  49761. */
  49762. this.clipIntersection = false;
  49763. /**
  49764. * Whether shadows should be clipped or not.
  49765. *
  49766. * @type {boolean}
  49767. * @default false
  49768. */
  49769. this.clipShadows = false;
  49770. }
  49771. }
  49772. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号