three.webgpu.nodes.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, 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, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, 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, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, 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, Matrix2, 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, 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, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, 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. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the length for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {Number} The length.
  469. */
  470. function getLengthFromType( type ) {
  471. if ( /float|int|uint/.test( type ) ) return 1;
  472. if ( /vec2/.test( type ) ) return 2;
  473. if ( /vec3/.test( type ) ) return 3;
  474. if ( /vec4/.test( type ) ) return 4;
  475. if ( /mat3/.test( type ) ) return 9;
  476. if ( /mat4/.test( type ) ) return 16;
  477. console.error( 'THREE.TSL: Unsupported type:', type );
  478. }
  479. /**
  480. * Returns the data type for the given value.
  481. *
  482. * @method
  483. * @param {Any} value - The value.
  484. * @return {String?} The data type.
  485. */
  486. function getValueType( value ) {
  487. if ( value === undefined || value === null ) return null;
  488. const typeOf = typeof value;
  489. if ( value.isNode === true ) {
  490. return 'node';
  491. } else if ( typeOf === 'number' ) {
  492. return 'float';
  493. } else if ( typeOf === 'boolean' ) {
  494. return 'bool';
  495. } else if ( typeOf === 'string' ) {
  496. return 'string';
  497. } else if ( typeOf === 'function' ) {
  498. return 'shader';
  499. } else if ( value.isVector2 === true ) {
  500. return 'vec2';
  501. } else if ( value.isVector3 === true ) {
  502. return 'vec3';
  503. } else if ( value.isVector4 === true ) {
  504. return 'vec4';
  505. } else if ( value.isMatrix3 === true ) {
  506. return 'mat3';
  507. } else if ( value.isMatrix4 === true ) {
  508. return 'mat4';
  509. } else if ( value.isColor === true ) {
  510. return 'color';
  511. } else if ( value instanceof ArrayBuffer ) {
  512. return 'ArrayBuffer';
  513. }
  514. return null;
  515. }
  516. /**
  517. * Returns the value/object for the given data type and parameters.
  518. *
  519. * @method
  520. * @param {String} type - The given type.
  521. * @param {...Any} params - A parameter list.
  522. * @return {Any} The value/object.
  523. */
  524. function getValueFromType( type, ...params ) {
  525. const last4 = type ? type.slice( - 4 ) : undefined;
  526. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  527. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  528. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  529. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  530. }
  531. if ( type === 'color' ) {
  532. return new Color( ...params );
  533. } else if ( last4 === 'vec2' ) {
  534. return new Vector2( ...params );
  535. } else if ( last4 === 'vec3' ) {
  536. return new Vector3( ...params );
  537. } else if ( last4 === 'vec4' ) {
  538. return new Vector4( ...params );
  539. } else if ( last4 === 'mat3' ) {
  540. return new Matrix3( ...params );
  541. } else if ( last4 === 'mat4' ) {
  542. return new Matrix4( ...params );
  543. } else if ( type === 'bool' ) {
  544. return params[ 0 ] || false;
  545. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  546. return params[ 0 ] || 0;
  547. } else if ( type === 'string' ) {
  548. return params[ 0 ] || '';
  549. } else if ( type === 'ArrayBuffer' ) {
  550. return base64ToArrayBuffer( params[ 0 ] );
  551. }
  552. return null;
  553. }
  554. /**
  555. * Gets the object data that can be shared between different rendering steps.
  556. *
  557. * @param {Object} object - The object to get the data for.
  558. * @return {Object} The object data.
  559. */
  560. function getDataFromObject( object ) {
  561. let data = dataFromObject.get( object );
  562. if ( data === undefined ) {
  563. data = {};
  564. dataFromObject.set( object, data );
  565. }
  566. return data;
  567. }
  568. /**
  569. * Converts the given array buffer to a Base64 string.
  570. *
  571. * @method
  572. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  573. * @return {String} The Base64 string.
  574. */
  575. function arrayBufferToBase64( arrayBuffer ) {
  576. let chars = '';
  577. const array = new Uint8Array( arrayBuffer );
  578. for ( let i = 0; i < array.length; i ++ ) {
  579. chars += String.fromCharCode( array[ i ] );
  580. }
  581. return btoa( chars );
  582. }
  583. /**
  584. * Converts the given Base64 string to an array buffer.
  585. *
  586. * @method
  587. * @param {String} base64 - The Base64 string.
  588. * @return {ArrayBuffer} The array buffer.
  589. */
  590. function base64ToArrayBuffer( base64 ) {
  591. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  592. }
  593. var NodeUtils = /*#__PURE__*/Object.freeze({
  594. __proto__: null,
  595. arrayBufferToBase64: arrayBufferToBase64,
  596. base64ToArrayBuffer: base64ToArrayBuffer,
  597. getCacheKey: getCacheKey$1,
  598. getDataFromObject: getDataFromObject,
  599. getLengthFromType: getLengthFromType,
  600. getNodeChildren: getNodeChildren,
  601. getTypeFromLength: getTypeFromLength,
  602. getValueFromType: getValueFromType,
  603. getValueType: getValueType,
  604. hash: hash$1,
  605. hashArray: hashArray,
  606. hashString: hashString
  607. });
  608. /** @module NodeConstants **/
  609. /**
  610. * Possible shader stages.
  611. *
  612. * @property {string} VERTEX The vertex shader stage.
  613. * @property {string} FRAGMENT The fragment shader stage.
  614. */
  615. const NodeShaderStage = {
  616. VERTEX: 'vertex',
  617. FRAGMENT: 'fragment'
  618. };
  619. /**
  620. * Update types of a node.
  621. *
  622. * @property {string} NONE The update method is not executed.
  623. * @property {string} FRAME The update method is executed per frame.
  624. * @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.
  625. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  626. */
  627. const NodeUpdateType = {
  628. NONE: 'none',
  629. FRAME: 'frame',
  630. RENDER: 'render',
  631. OBJECT: 'object'
  632. };
  633. /**
  634. * Data types of a node.
  635. *
  636. * @property {string} BOOLEAN Boolean type.
  637. * @property {string} INTEGER Integer type.
  638. * @property {string} FLOAT Float type.
  639. * @property {string} VECTOR2 Two-dimensional vector type.
  640. * @property {string} VECTOR3 Three-dimensional vector type.
  641. * @property {string} VECTOR4 Four-dimensional vector type.
  642. * @property {string} MATRIX2 2x2 matrix type.
  643. * @property {string} MATRIX3 3x3 matrix type.
  644. * @property {string} MATRIX4 4x4 matrix type.
  645. */
  646. const NodeType = {
  647. BOOLEAN: 'bool',
  648. INTEGER: 'int',
  649. FLOAT: 'float',
  650. VECTOR2: 'vec2',
  651. VECTOR3: 'vec3',
  652. VECTOR4: 'vec4',
  653. MATRIX2: 'mat2',
  654. MATRIX3: 'mat3',
  655. MATRIX4: 'mat4'
  656. };
  657. /**
  658. * Access types of a node. These are relevant for compute and storage usage.
  659. *
  660. * @property {string} READ_ONLY Read-only access
  661. * @property {string} WRITE_ONLY Write-only access.
  662. * @property {string} READ_WRITE Read and write access.
  663. */
  664. const NodeAccess = {
  665. READ_ONLY: 'readOnly',
  666. WRITE_ONLY: 'writeOnly',
  667. READ_WRITE: 'readWrite',
  668. };
  669. const defaultShaderStages = [ 'fragment', 'vertex' ];
  670. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  671. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  672. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  673. let _nodeId = 0;
  674. /**
  675. * Base class for all nodes.
  676. *
  677. * @augments EventDispatcher
  678. */
  679. class Node extends EventDispatcher {
  680. static get type() {
  681. return 'Node';
  682. }
  683. /**
  684. * Constructs a new node.
  685. *
  686. * @param {String?} nodeType - The node type.
  687. */
  688. constructor( nodeType = null ) {
  689. super();
  690. /**
  691. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  692. *
  693. * @type {String?}
  694. * @default null
  695. */
  696. this.nodeType = nodeType;
  697. /**
  698. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  699. *
  700. * @type {String}
  701. * @default 'none'
  702. */
  703. this.updateType = NodeUpdateType.NONE;
  704. /**
  705. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  706. *
  707. * @type {String}
  708. * @default 'none'
  709. */
  710. this.updateBeforeType = NodeUpdateType.NONE;
  711. /**
  712. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  713. *
  714. * @type {String}
  715. * @default 'none'
  716. */
  717. this.updateAfterType = NodeUpdateType.NONE;
  718. /**
  719. * The UUID of the node.
  720. *
  721. * @type {String}
  722. * @readonly
  723. */
  724. this.uuid = MathUtils.generateUUID();
  725. /**
  726. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  727. *
  728. * @type {Number}
  729. * @readonly
  730. * @default 0
  731. */
  732. this.version = 0;
  733. /**
  734. * Whether this node is global or not. This property is relevant for the internal
  735. * node caching system. All nodes which should be declared just once should
  736. * set this flag to `true` (a typical example is {@link AttributeNode}).
  737. *
  738. * @type {Boolean}
  739. * @default false
  740. */
  741. this.global = false;
  742. /**
  743. * This flag can be used for type testing.
  744. *
  745. * @type {Boolean}
  746. * @readonly
  747. * @default true
  748. */
  749. this.isNode = true;
  750. // private
  751. /**
  752. * The cache key of this node.
  753. *
  754. * @private
  755. * @type {Number?}
  756. * @default null
  757. */
  758. this._cacheKey = null;
  759. /**
  760. * The cache key 's version.
  761. *
  762. * @private
  763. * @type {Number}
  764. * @default 0
  765. */
  766. this._cacheKeyVersion = 0;
  767. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  768. }
  769. /**
  770. * Set this property to `true` when the node should be regenerated.
  771. *
  772. * @type {Boolean}
  773. * @default false
  774. * @param {boolean} value
  775. */
  776. set needsUpdate( value ) {
  777. if ( value === true ) {
  778. this.version ++;
  779. }
  780. }
  781. /**
  782. * The type of the class. The value is usually the constructor name.
  783. *
  784. * @type {String}
  785. * @readonly
  786. */
  787. get type() {
  788. return this.constructor.type;
  789. }
  790. /**
  791. * Convenient method for defining {@link Node#update}.
  792. *
  793. * @param {Function} callback - The update method.
  794. * @param {String} updateType - The update type.
  795. * @return {Node} A reference to this node.
  796. */
  797. onUpdate( callback, updateType ) {
  798. this.updateType = updateType;
  799. this.update = callback.bind( this.getSelf() );
  800. return this;
  801. }
  802. /**
  803. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  804. * this method automatically sets the update type to `FRAME`.
  805. *
  806. * @param {Function} callback - The update method.
  807. * @return {Node} A reference to this node.
  808. */
  809. onFrameUpdate( callback ) {
  810. return this.onUpdate( callback, NodeUpdateType.FRAME );
  811. }
  812. /**
  813. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  814. * this method automatically sets the update type to `RENDER`.
  815. *
  816. * @param {Function} callback - The update method.
  817. * @return {Node} A reference to this node.
  818. */
  819. onRenderUpdate( callback ) {
  820. return this.onUpdate( callback, NodeUpdateType.RENDER );
  821. }
  822. /**
  823. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  824. * this method automatically sets the update type to `OBJECT`.
  825. *
  826. * @param {Function} callback - The update method.
  827. * @return {Node} A reference to this node.
  828. */
  829. onObjectUpdate( callback ) {
  830. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  831. }
  832. /**
  833. * Convenient method for defining {@link Node#updateReference}.
  834. *
  835. * @param {Function} callback - The update method.
  836. * @return {Node} A reference to this node.
  837. */
  838. onReference( callback ) {
  839. this.updateReference = callback.bind( this.getSelf() );
  840. return this;
  841. }
  842. /**
  843. * The `this` reference might point to a Proxy so this method can be used
  844. * to get the reference to the actual node instance.
  845. *
  846. * @return {Node} A reference to the node.
  847. */
  848. getSelf() {
  849. // Returns non-node object.
  850. return this.self || this;
  851. }
  852. /**
  853. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  854. * to such objects based on a given state (e.g. the current node frame or builder).
  855. *
  856. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  857. * @return {Any} The updated reference.
  858. */
  859. updateReference( /*state*/ ) {
  860. return this;
  861. }
  862. /**
  863. * By default this method returns the value of the {@link Node#global} flag. This method
  864. * can be overwritten in derived classes if an analytical way is required to determine the
  865. * global status.
  866. *
  867. * @param {NodeBuilder} builder - The current node builder.
  868. * @return {Boolean} Whether this node is global or not.
  869. */
  870. isGlobal( /*builder*/ ) {
  871. return this.global;
  872. }
  873. /**
  874. * Generator function that can be used to iterate over the child nodes.
  875. *
  876. * @generator
  877. * @yields {Node} A child node.
  878. */
  879. * getChildren() {
  880. for ( const { childNode } of getNodeChildren( this ) ) {
  881. yield childNode;
  882. }
  883. }
  884. /**
  885. * Calling this method dispatches the `dispose` event. This event can be used
  886. * to register event listeners for clean up tasks.
  887. */
  888. dispose() {
  889. this.dispatchEvent( { type: 'dispose' } );
  890. }
  891. /**
  892. * Callback for {@link Node#traverse}.
  893. *
  894. * @callback traverseCallback
  895. * @param {Node} node - The current node.
  896. */
  897. /**
  898. * Can be used to traverse through the node's hierarchy.
  899. *
  900. * @param {traverseCallback} callback - A callback that is executed per node.
  901. */
  902. traverse( callback ) {
  903. callback( this );
  904. for ( const childNode of this.getChildren() ) {
  905. childNode.traverse( callback );
  906. }
  907. }
  908. /**
  909. * Returns the cache key for this node.
  910. *
  911. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  912. * @return {Number} The cache key of the node.
  913. */
  914. getCacheKey( force = false ) {
  915. force = force || this.version !== this._cacheKeyVersion;
  916. if ( force === true || this._cacheKey === null ) {
  917. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  918. this._cacheKeyVersion = this.version;
  919. }
  920. return this._cacheKey;
  921. }
  922. /**
  923. * Generate a custom cache key for this node.
  924. *
  925. * @return {Number} The cache key of the node.
  926. */
  927. customCacheKey() {
  928. return 0;
  929. }
  930. /**
  931. * Returns the references to this node which is by default `this`.
  932. *
  933. * @return {Node} A reference to this node.
  934. */
  935. getScope() {
  936. return this;
  937. }
  938. /**
  939. * Returns the hash of the node which is used to identify the node. By default it's
  940. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  941. * depending on their implementation.
  942. *
  943. * @param {NodeBuilder} builder - The current node builder.
  944. * @return {String} The hash.
  945. */
  946. getHash( /*builder*/ ) {
  947. return this.uuid;
  948. }
  949. /**
  950. * Returns the update type of {@link Node#update}.
  951. *
  952. * @return {NodeUpdateType} The update type.
  953. */
  954. getUpdateType() {
  955. return this.updateType;
  956. }
  957. /**
  958. * Returns the update type of {@link Node#updateBefore}.
  959. *
  960. * @return {NodeUpdateType} The update type.
  961. */
  962. getUpdateBeforeType() {
  963. return this.updateBeforeType;
  964. }
  965. /**
  966. * Returns the update type of {@link Node#updateAfter}.
  967. *
  968. * @return {NodeUpdateType} The update type.
  969. */
  970. getUpdateAfterType() {
  971. return this.updateAfterType;
  972. }
  973. /**
  974. * Certain types are composed of multiple elements. For example a `vec3`
  975. * is composed of three `float` values. This method returns the type of
  976. * these elements.
  977. *
  978. * @param {NodeBuilder} builder - The current node builder.
  979. * @return {String} The type of the node.
  980. */
  981. getElementType( builder ) {
  982. const type = this.getNodeType( builder );
  983. const elementType = builder.getElementType( type );
  984. return elementType;
  985. }
  986. /**
  987. * Returns the node's type.
  988. *
  989. * @param {NodeBuilder} builder - The current node builder.
  990. * @return {String} The type of the node.
  991. */
  992. getNodeType( builder ) {
  993. const nodeProperties = builder.getNodeProperties( this );
  994. if ( nodeProperties.outputNode ) {
  995. return nodeProperties.outputNode.getNodeType( builder );
  996. }
  997. return this.nodeType;
  998. }
  999. /**
  1000. * This method is used during the build process of a node and ensures
  1001. * equal nodes are not built multiple times but just once. For example if
  1002. * `attribute( 'uv' )` is used multiple times by the user, the build
  1003. * process makes sure to process just the first node.
  1004. *
  1005. * @param {NodeBuilder} builder - The current node builder.
  1006. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1007. */
  1008. getShared( builder ) {
  1009. const hash = this.getHash( builder );
  1010. const nodeFromHash = builder.getNodeFromHash( hash );
  1011. return nodeFromHash || this;
  1012. }
  1013. /**
  1014. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1015. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1016. * The output node must be returned in the `return` statement.
  1017. *
  1018. * @param {NodeBuilder} builder - The current node builder.
  1019. * @return {Node?} The output node.
  1020. */
  1021. setup( builder ) {
  1022. const nodeProperties = builder.getNodeProperties( this );
  1023. let index = 0;
  1024. for ( const childNode of this.getChildren() ) {
  1025. nodeProperties[ 'node' + index ++ ] = childNode;
  1026. }
  1027. // return a outputNode if exists
  1028. return null;
  1029. }
  1030. /**
  1031. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1032. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1033. *
  1034. * @param {NodeBuilder} builder - The current node builder.
  1035. */
  1036. analyze( builder ) {
  1037. const usageCount = builder.increaseUsage( this );
  1038. if ( usageCount === 1 ) {
  1039. // node flow children
  1040. const nodeProperties = builder.getNodeProperties( this );
  1041. for ( const childNode of Object.values( nodeProperties ) ) {
  1042. if ( childNode && childNode.isNode === true ) {
  1043. childNode.build( builder );
  1044. }
  1045. }
  1046. }
  1047. }
  1048. /**
  1049. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1050. * This state builds the output node and returns the resulting shader string.
  1051. *
  1052. * @param {NodeBuilder} builder - The current node builder.
  1053. * @param {String?} output - Can be used to define the output type.
  1054. * @return {String?} The generated shader string.
  1055. */
  1056. generate( builder, output ) {
  1057. const { outputNode } = builder.getNodeProperties( this );
  1058. if ( outputNode && outputNode.isNode === true ) {
  1059. return outputNode.build( builder, output );
  1060. }
  1061. }
  1062. /**
  1063. * The method can be implemented to update the node's internal state before it is used to render an object.
  1064. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1065. *
  1066. * @abstract
  1067. * @param {NodeFrame} frame - A reference to the current node frame.
  1068. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1069. */
  1070. updateBefore( /*frame*/ ) {
  1071. console.warn( 'Abstract function.' );
  1072. }
  1073. /**
  1074. * The method can be implemented to update the node's internal state after it was used to render an object.
  1075. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1076. *
  1077. * @abstract
  1078. * @param {NodeFrame} frame - A reference to the current node frame.
  1079. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1080. */
  1081. updateAfter( /*frame*/ ) {
  1082. console.warn( 'Abstract function.' );
  1083. }
  1084. /**
  1085. * The method can be implemented to update the node's internal state when it is used to render an object.
  1086. * The {@link Node#updateType} property defines how often the update is executed.
  1087. *
  1088. * @abstract
  1089. * @param {NodeFrame} frame - A reference to the current node frame.
  1090. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1091. */
  1092. update( /*frame*/ ) {
  1093. console.warn( 'Abstract function.' );
  1094. }
  1095. /**
  1096. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1097. * on the current build stage (setup, analyze or generate).
  1098. *
  1099. * @param {NodeBuilder} builder - The current node builder.
  1100. * @param {String?} output - Can be used to define the output type.
  1101. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1102. */
  1103. build( builder, output = null ) {
  1104. const refNode = this.getShared( builder );
  1105. if ( this !== refNode ) {
  1106. return refNode.build( builder, output );
  1107. }
  1108. builder.addNode( this );
  1109. builder.addChain( this );
  1110. /* Build stages expected results:
  1111. - "setup" -> Node
  1112. - "analyze" -> null
  1113. - "generate" -> String
  1114. */
  1115. let result = null;
  1116. const buildStage = builder.getBuildStage();
  1117. if ( buildStage === 'setup' ) {
  1118. this.updateReference( builder );
  1119. const properties = builder.getNodeProperties( this );
  1120. if ( properties.initialized !== true ) {
  1121. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1122. properties.initialized = true;
  1123. properties.outputNode = this.setup( builder );
  1124. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1125. for ( const childNode of Object.values( properties ) ) {
  1126. if ( childNode && childNode.isNode === true ) {
  1127. childNode.build( builder );
  1128. }
  1129. }
  1130. }
  1131. } else if ( buildStage === 'analyze' ) {
  1132. this.analyze( builder );
  1133. } else if ( buildStage === 'generate' ) {
  1134. const isGenerateOnce = this.generate.length === 1;
  1135. if ( isGenerateOnce ) {
  1136. const type = this.getNodeType( builder );
  1137. const nodeData = builder.getDataFromNode( this );
  1138. result = nodeData.snippet;
  1139. if ( result === undefined ) {
  1140. result = this.generate( builder ) || '';
  1141. nodeData.snippet = result;
  1142. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1143. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1144. }
  1145. result = builder.format( result, type, output );
  1146. } else {
  1147. result = this.generate( builder, output ) || '';
  1148. }
  1149. }
  1150. builder.removeChain( this );
  1151. builder.addSequentialNode( this );
  1152. return result;
  1153. }
  1154. /**
  1155. * Returns the child nodes as a JSON object.
  1156. *
  1157. * @return {Object} The serialized child objects as JSON.
  1158. */
  1159. getSerializeChildren() {
  1160. return getNodeChildren( this );
  1161. }
  1162. /**
  1163. * Serializes the node to JSON.
  1164. *
  1165. * @param {Object} json - The output JSON object.
  1166. */
  1167. serialize( json ) {
  1168. const nodeChildren = this.getSerializeChildren();
  1169. const inputNodes = {};
  1170. for ( const { property, index, childNode } of nodeChildren ) {
  1171. if ( index !== undefined ) {
  1172. if ( inputNodes[ property ] === undefined ) {
  1173. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1174. }
  1175. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1176. } else {
  1177. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1178. }
  1179. }
  1180. if ( Object.keys( inputNodes ).length > 0 ) {
  1181. json.inputNodes = inputNodes;
  1182. }
  1183. }
  1184. /**
  1185. * Deserializes the node from the given JSON.
  1186. *
  1187. * @param {Object} json - The JSON object.
  1188. */
  1189. deserialize( json ) {
  1190. if ( json.inputNodes !== undefined ) {
  1191. const nodes = json.meta.nodes;
  1192. for ( const property in json.inputNodes ) {
  1193. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1194. const inputArray = [];
  1195. for ( const uuid of json.inputNodes[ property ] ) {
  1196. inputArray.push( nodes[ uuid ] );
  1197. }
  1198. this[ property ] = inputArray;
  1199. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1200. const inputObject = {};
  1201. for ( const subProperty in json.inputNodes[ property ] ) {
  1202. const uuid = json.inputNodes[ property ][ subProperty ];
  1203. inputObject[ subProperty ] = nodes[ uuid ];
  1204. }
  1205. this[ property ] = inputObject;
  1206. } else {
  1207. const uuid = json.inputNodes[ property ];
  1208. this[ property ] = nodes[ uuid ];
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /**
  1214. * Serializes the node into the three.js JSON Object/Scene format.
  1215. *
  1216. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1217. * @return {Object} The serialized node.
  1218. */
  1219. toJSON( meta ) {
  1220. const { uuid, type } = this;
  1221. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1222. if ( isRoot ) {
  1223. meta = {
  1224. textures: {},
  1225. images: {},
  1226. nodes: {}
  1227. };
  1228. }
  1229. // serialize
  1230. let data = meta.nodes[ uuid ];
  1231. if ( data === undefined ) {
  1232. data = {
  1233. uuid,
  1234. type,
  1235. meta,
  1236. metadata: {
  1237. version: 4.6,
  1238. type: 'Node',
  1239. generator: 'Node.toJSON'
  1240. }
  1241. };
  1242. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1243. this.serialize( data );
  1244. delete data.meta;
  1245. }
  1246. // TODO: Copied from Object3D.toJSON
  1247. function extractFromCache( cache ) {
  1248. const values = [];
  1249. for ( const key in cache ) {
  1250. const data = cache[ key ];
  1251. delete data.metadata;
  1252. values.push( data );
  1253. }
  1254. return values;
  1255. }
  1256. if ( isRoot ) {
  1257. const textures = extractFromCache( meta.textures );
  1258. const images = extractFromCache( meta.images );
  1259. const nodes = extractFromCache( meta.nodes );
  1260. if ( textures.length > 0 ) data.textures = textures;
  1261. if ( images.length > 0 ) data.images = images;
  1262. if ( nodes.length > 0 ) data.nodes = nodes;
  1263. }
  1264. return data;
  1265. }
  1266. }
  1267. /**
  1268. * Base class for representing element access on an array-like
  1269. * node data structures.
  1270. *
  1271. * @augments Node
  1272. */
  1273. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1274. static get type() {
  1275. return 'ArrayElementNode';
  1276. }
  1277. /**
  1278. * Constructs an array element node.
  1279. *
  1280. * @param {Node} node - The array-like node.
  1281. * @param {Node} indexNode - The index node that defines the element access.
  1282. */
  1283. constructor( node, indexNode ) {
  1284. super();
  1285. /**
  1286. * The array-like node.
  1287. *
  1288. * @type {Node}
  1289. */
  1290. this.node = node;
  1291. /**
  1292. * The index node that defines the element access.
  1293. *
  1294. * @type {Node}
  1295. */
  1296. this.indexNode = indexNode;
  1297. /**
  1298. * This flag can be used for type testing.
  1299. *
  1300. * @type {Boolean}
  1301. * @readonly
  1302. * @default true
  1303. */
  1304. this.isArrayElementNode = true;
  1305. }
  1306. /**
  1307. * This method is overwritten since the node type is inferred from the array-like node.
  1308. *
  1309. * @param {NodeBuilder} builder - The current node builder.
  1310. * @return {String} The node type.
  1311. */
  1312. getNodeType( builder ) {
  1313. return this.node.getElementType( builder );
  1314. }
  1315. generate( builder ) {
  1316. const nodeSnippet = this.node.build( builder );
  1317. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1318. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1319. }
  1320. }
  1321. /**
  1322. * This module is part of the TSL core and usually not used in app level code.
  1323. * It represents a convert operation during the shader generation process
  1324. * meaning it converts the data type of a node to a target data type.
  1325. *
  1326. * @augments Node
  1327. */
  1328. class ConvertNode extends Node {
  1329. static get type() {
  1330. return 'ConvertNode';
  1331. }
  1332. /**
  1333. * Constructs a new convert node.
  1334. *
  1335. * @param {Node} node - The node which type should be converted.
  1336. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1337. */
  1338. constructor( node, convertTo ) {
  1339. super();
  1340. /**
  1341. * The node which type should be converted.
  1342. *
  1343. * @type {Node}
  1344. */
  1345. this.node = node;
  1346. /**
  1347. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1348. *
  1349. * @type {String}
  1350. */
  1351. this.convertTo = convertTo;
  1352. }
  1353. /**
  1354. * This method is overwritten since the implementation tries to infer the best
  1355. * matching type from the {@link ConvertNode#convertTo} property.
  1356. *
  1357. * @param {NodeBuilder} builder - The current node builder.
  1358. * @return {String} The node type.
  1359. */
  1360. getNodeType( builder ) {
  1361. const requestType = this.node.getNodeType( builder );
  1362. let convertTo = null;
  1363. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1364. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1365. convertTo = overloadingType;
  1366. }
  1367. }
  1368. return convertTo;
  1369. }
  1370. serialize( data ) {
  1371. super.serialize( data );
  1372. data.convertTo = this.convertTo;
  1373. }
  1374. deserialize( data ) {
  1375. super.deserialize( data );
  1376. this.convertTo = data.convertTo;
  1377. }
  1378. generate( builder, output ) {
  1379. const node = this.node;
  1380. const type = this.getNodeType( builder );
  1381. const snippet = node.build( builder, type );
  1382. return builder.format( snippet, type, output );
  1383. }
  1384. }
  1385. /**
  1386. * This module uses cache management to create temporary variables
  1387. * if the node is used more than once to prevent duplicate calculations.
  1388. *
  1389. * The class acts as a base class for many other nodes types.
  1390. *
  1391. * @augments Node
  1392. */
  1393. class TempNode extends Node {
  1394. static get type() {
  1395. return 'TempNode';
  1396. }
  1397. /**
  1398. * Constructs a temp node.
  1399. *
  1400. * @param {String?} nodeType - The node type.
  1401. */
  1402. constructor( nodeType = null ) {
  1403. super( nodeType );
  1404. /**
  1405. * This flag can be used for type testing.
  1406. *
  1407. * @type {Boolean}
  1408. * @readonly
  1409. * @default true
  1410. */
  1411. this.isTempNode = true;
  1412. }
  1413. /**
  1414. * Whether this node is used more than once in context of other nodes.
  1415. *
  1416. * @param {NodeBuilder} builder - The node builder.
  1417. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1418. */
  1419. hasDependencies( builder ) {
  1420. return builder.getDataFromNode( this ).usageCount > 1;
  1421. }
  1422. build( builder, output ) {
  1423. const buildStage = builder.getBuildStage();
  1424. if ( buildStage === 'generate' ) {
  1425. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1426. const nodeData = builder.getDataFromNode( this );
  1427. if ( nodeData.propertyName !== undefined ) {
  1428. return builder.format( nodeData.propertyName, type, output );
  1429. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1430. const snippet = super.build( builder, type );
  1431. const nodeVar = builder.getVarFromNode( this, null, type );
  1432. const propertyName = builder.getPropertyName( nodeVar );
  1433. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1434. nodeData.snippet = snippet;
  1435. nodeData.propertyName = propertyName;
  1436. return builder.format( nodeData.propertyName, type, output );
  1437. }
  1438. }
  1439. return super.build( builder, output );
  1440. }
  1441. }
  1442. /**
  1443. * This module is part of the TSL core and usually not used in app level code.
  1444. * It represents a join operation during the shader generation process.
  1445. * For example in can compose/join two single floats into a `vec2` type.
  1446. *
  1447. * @augments TempNode
  1448. */
  1449. class JoinNode extends TempNode {
  1450. static get type() {
  1451. return 'JoinNode';
  1452. }
  1453. /**
  1454. * Constructs a new join node.
  1455. *
  1456. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1457. * @param {String?} [nodeType=null] - The node type.
  1458. */
  1459. constructor( nodes = [], nodeType = null ) {
  1460. super( nodeType );
  1461. /**
  1462. * An array of nodes that should be joined.
  1463. *
  1464. * @type {Array<Node>}
  1465. */
  1466. this.nodes = nodes;
  1467. }
  1468. /**
  1469. * This method is overwritten since the node type must be inferred from the
  1470. * joined data length if not explicitly defined.
  1471. *
  1472. * @param {NodeBuilder} builder - The current node builder.
  1473. * @return {String} The node type.
  1474. */
  1475. getNodeType( builder ) {
  1476. if ( this.nodeType !== null ) {
  1477. return builder.getVectorType( this.nodeType );
  1478. }
  1479. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1480. }
  1481. generate( builder, output ) {
  1482. const type = this.getNodeType( builder );
  1483. const nodes = this.nodes;
  1484. const primitiveType = builder.getComponentType( type );
  1485. const snippetValues = [];
  1486. for ( const input of nodes ) {
  1487. let inputSnippet = input.build( builder );
  1488. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1489. if ( inputPrimitiveType !== primitiveType ) {
  1490. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1491. }
  1492. snippetValues.push( inputSnippet );
  1493. }
  1494. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1495. return builder.format( snippet, type, output );
  1496. }
  1497. }
  1498. const _stringVectorComponents = vectorComponents.join( '' );
  1499. /**
  1500. * This module is part of the TSL core and usually not used in app level code.
  1501. * `SplitNode` represents a property access operation which means it is
  1502. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1503. * For example:
  1504. * ```js
  1505. * const redValue = color.r;
  1506. * ```
  1507. *
  1508. * @augments Node
  1509. */
  1510. class SplitNode extends Node {
  1511. static get type() {
  1512. return 'SplitNode';
  1513. }
  1514. /**
  1515. * Constructs a new split node.
  1516. *
  1517. * @param {Node} node - The node that should be accessed.
  1518. * @param {String} [components='x'] - The components that should be accessed.
  1519. */
  1520. constructor( node, components = 'x' ) {
  1521. super();
  1522. /**
  1523. * The node that should be accessed.
  1524. *
  1525. * @type {Node}
  1526. */
  1527. this.node = node;
  1528. /**
  1529. * The components that should be accessed.
  1530. *
  1531. * @type {string}
  1532. */
  1533. this.components = components;
  1534. /**
  1535. * This flag can be used for type testing.
  1536. *
  1537. * @type {Boolean}
  1538. * @readonly
  1539. * @default true
  1540. */
  1541. this.isSplitNode = true;
  1542. }
  1543. /**
  1544. * Returns the vector length which is computed based on the requested components.
  1545. *
  1546. * @return {Number} The vector length.
  1547. */
  1548. getVectorLength() {
  1549. let vectorLength = this.components.length;
  1550. for ( const c of this.components ) {
  1551. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1552. }
  1553. return vectorLength;
  1554. }
  1555. /**
  1556. * Returns the component type of the node's type.
  1557. *
  1558. * @param {NodeBuilder} builder - The current node builder.
  1559. * @return {String} The component type.
  1560. */
  1561. getComponentType( builder ) {
  1562. return builder.getComponentType( this.node.getNodeType( builder ) );
  1563. }
  1564. /**
  1565. * This method is overwritten since the node type is inferred from requested components.
  1566. *
  1567. * @param {NodeBuilder} builder - The current node builder.
  1568. * @return {String} The node type.
  1569. */
  1570. getNodeType( builder ) {
  1571. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1572. }
  1573. generate( builder, output ) {
  1574. const node = this.node;
  1575. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1576. let snippet = null;
  1577. if ( nodeTypeLength > 1 ) {
  1578. let type = null;
  1579. const componentsLength = this.getVectorLength();
  1580. if ( componentsLength >= nodeTypeLength ) {
  1581. // needed expand the input node
  1582. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1583. }
  1584. const nodeSnippet = node.build( builder, type );
  1585. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1586. // unnecessary swizzle
  1587. snippet = builder.format( nodeSnippet, type, output );
  1588. } else {
  1589. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1590. }
  1591. } else {
  1592. // ignore .components if .node returns float/integer
  1593. snippet = node.build( builder, output );
  1594. }
  1595. return snippet;
  1596. }
  1597. serialize( data ) {
  1598. super.serialize( data );
  1599. data.components = this.components;
  1600. }
  1601. deserialize( data ) {
  1602. super.deserialize( data );
  1603. this.components = data.components;
  1604. }
  1605. }
  1606. /**
  1607. * This module is part of the TSL core and usually not used in app level code.
  1608. * `SetNode` represents a set operation which means it is used to implement any
  1609. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1610. * For example:
  1611. * ```js
  1612. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1613. * ```
  1614. *
  1615. * @augments TempNode
  1616. */
  1617. class SetNode extends TempNode {
  1618. static get type() {
  1619. return 'SetNode';
  1620. }
  1621. /**
  1622. * Constructs a new set node.
  1623. *
  1624. * @param {Node} sourceNode - The node that should be updated.
  1625. * @param {String} components - The components that should be updated.
  1626. * @param {Node} targetNode - The value node.
  1627. */
  1628. constructor( sourceNode, components, targetNode ) {
  1629. super();
  1630. /**
  1631. * The node that should be updated.
  1632. *
  1633. * @type {Node}
  1634. */
  1635. this.sourceNode = sourceNode;
  1636. /**
  1637. * The components that should be updated.
  1638. *
  1639. * @type {String}
  1640. */
  1641. this.components = components;
  1642. /**
  1643. * The value node.
  1644. *
  1645. * @type {Node}
  1646. */
  1647. this.targetNode = targetNode;
  1648. }
  1649. /**
  1650. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1651. *
  1652. * @param {NodeBuilder} builder - The current node builder.
  1653. * @return {String} The node type.
  1654. */
  1655. getNodeType( builder ) {
  1656. return this.sourceNode.getNodeType( builder );
  1657. }
  1658. generate( builder ) {
  1659. const { sourceNode, components, targetNode } = this;
  1660. const sourceType = this.getNodeType( builder );
  1661. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1662. const targetType = builder.getTypeFromLength( components.length, componentType );
  1663. const targetSnippet = targetNode.build( builder, targetType );
  1664. const sourceSnippet = sourceNode.build( builder, sourceType );
  1665. const length = builder.getTypeLength( sourceType );
  1666. const snippetValues = [];
  1667. for ( let i = 0; i < length; i ++ ) {
  1668. const component = vectorComponents[ i ];
  1669. if ( component === components[ 0 ] ) {
  1670. snippetValues.push( targetSnippet );
  1671. i += components.length - 1;
  1672. } else {
  1673. snippetValues.push( sourceSnippet + '.' + component );
  1674. }
  1675. }
  1676. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1677. }
  1678. }
  1679. /**
  1680. * This module is part of the TSL core and usually not used in app level code.
  1681. * It represents a flip operation during the shader generation process
  1682. * meaning it flips normalized values with the following formula:
  1683. * ```
  1684. * x = 1 - x;
  1685. * ```
  1686. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1687. * `flipSTPQ()` method invocations on node objects. For example:
  1688. * ```js
  1689. * uvNode = uvNode.flipY();
  1690. * ```
  1691. *
  1692. * @augments TempNode
  1693. */
  1694. class FlipNode extends TempNode {
  1695. static get type() {
  1696. return 'FlipNode';
  1697. }
  1698. /**
  1699. * Constructs a new flip node.
  1700. *
  1701. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1702. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1703. */
  1704. constructor( sourceNode, components ) {
  1705. super();
  1706. /**
  1707. * The node which component(s) should be flipped.
  1708. *
  1709. * @type {Node}
  1710. */
  1711. this.sourceNode = sourceNode;
  1712. /**
  1713. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1714. *
  1715. * @type {String}
  1716. */
  1717. this.components = components;
  1718. }
  1719. /**
  1720. * This method is overwritten since the node type is inferred from the source node.
  1721. *
  1722. * @param {NodeBuilder} builder - The current node builder.
  1723. * @return {String} The node type.
  1724. */
  1725. getNodeType( builder ) {
  1726. return this.sourceNode.getNodeType( builder );
  1727. }
  1728. generate( builder ) {
  1729. const { components, sourceNode } = this;
  1730. const sourceType = this.getNodeType( builder );
  1731. const sourceSnippet = sourceNode.build( builder );
  1732. const sourceCache = builder.getVarFromNode( this );
  1733. const sourceProperty = builder.getPropertyName( sourceCache );
  1734. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1735. const length = builder.getTypeLength( sourceType );
  1736. const snippetValues = [];
  1737. let componentIndex = 0;
  1738. for ( let i = 0; i < length; i ++ ) {
  1739. const component = vectorComponents[ i ];
  1740. if ( component === components[ componentIndex ] ) {
  1741. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1742. componentIndex ++;
  1743. } else {
  1744. snippetValues.push( sourceProperty + '.' + component );
  1745. }
  1746. }
  1747. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1748. }
  1749. }
  1750. /**
  1751. * Base class for representing data input nodes.
  1752. *
  1753. * @augments Node
  1754. */
  1755. class InputNode extends Node {
  1756. static get type() {
  1757. return 'InputNode';
  1758. }
  1759. /**
  1760. * Constructs a new input node.
  1761. *
  1762. * @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).
  1763. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1764. */
  1765. constructor( value, nodeType = null ) {
  1766. super( nodeType );
  1767. /**
  1768. * This flag can be used for type testing.
  1769. *
  1770. * @type {Boolean}
  1771. * @readonly
  1772. * @default true
  1773. */
  1774. this.isInputNode = true;
  1775. /**
  1776. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1777. *
  1778. * @type {Any}
  1779. */
  1780. this.value = value;
  1781. /**
  1782. * The precision of the value in the shader.
  1783. *
  1784. * @type {('low'|'medium'|'high')?}
  1785. * @default null
  1786. */
  1787. this.precision = null;
  1788. }
  1789. getNodeType( /*builder*/ ) {
  1790. if ( this.nodeType === null ) {
  1791. return getValueType( this.value );
  1792. }
  1793. return this.nodeType;
  1794. }
  1795. /**
  1796. * Returns the input type of the node which is by default the node type. Derived modules
  1797. * might overwrite this method and use a fixed type or compute one analytically.
  1798. *
  1799. * A typical example for different input and node types are textures. The input type of a
  1800. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1801. *
  1802. * @param {NodeBuilder} builder - The current node builder.
  1803. * @return {String} The input type.
  1804. */
  1805. getInputType( builder ) {
  1806. return this.getNodeType( builder );
  1807. }
  1808. /**
  1809. * Sets the precision to the given value. The method can be
  1810. * overwritten in derived classes if the final precision must be computed
  1811. * analytically.
  1812. *
  1813. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1814. * @return {InputNode} A reference to this node.
  1815. */
  1816. setPrecision( precision ) {
  1817. this.precision = precision;
  1818. return this;
  1819. }
  1820. serialize( data ) {
  1821. super.serialize( data );
  1822. data.value = this.value;
  1823. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1824. data.valueType = getValueType( this.value );
  1825. data.nodeType = this.nodeType;
  1826. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1827. data.precision = this.precision;
  1828. }
  1829. deserialize( data ) {
  1830. super.deserialize( data );
  1831. this.nodeType = data.nodeType;
  1832. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1833. this.precision = data.precision || null;
  1834. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1835. }
  1836. generate( /*builder, output*/ ) {
  1837. console.warn( 'Abstract function.' );
  1838. }
  1839. }
  1840. /**
  1841. * Class for representing a constant value in the shader.
  1842. *
  1843. * @augments InputNode
  1844. */
  1845. class ConstNode extends InputNode {
  1846. static get type() {
  1847. return 'ConstNode';
  1848. }
  1849. /**
  1850. * Constructs a new input node.
  1851. *
  1852. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1853. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1854. */
  1855. constructor( value, nodeType = null ) {
  1856. super( value, nodeType );
  1857. /**
  1858. * This flag can be used for type testing.
  1859. *
  1860. * @type {Boolean}
  1861. * @readonly
  1862. * @default true
  1863. */
  1864. this.isConstNode = true;
  1865. }
  1866. /**
  1867. * Generates the shader string of the value with the current node builder.
  1868. *
  1869. * @param {NodeBuilder} builder - The current node builder.
  1870. * @return {String} The generated value as a shader string.
  1871. */
  1872. generateConst( builder ) {
  1873. return builder.generateConst( this.getNodeType( builder ), this.value );
  1874. }
  1875. generate( builder, output ) {
  1876. const type = this.getNodeType( builder );
  1877. return builder.format( this.generateConst( builder ), type, output );
  1878. }
  1879. }
  1880. //
  1881. let currentStack = null;
  1882. const NodeElements = new Map();
  1883. function addMethodChaining( name, nodeElement ) {
  1884. if ( NodeElements.has( name ) ) {
  1885. console.warn( `Redefinition of method chaining ${ name }` );
  1886. return;
  1887. }
  1888. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1889. NodeElements.set( name, nodeElement );
  1890. }
  1891. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1892. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1893. const shaderNodeHandler = {
  1894. setup( NodeClosure, params ) {
  1895. const inputs = params.shift();
  1896. return NodeClosure( nodeObjects( inputs ), ...params );
  1897. },
  1898. get( node, prop, nodeObj ) {
  1899. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1900. if ( node.isStackNode !== true && prop === 'assign' ) {
  1901. return ( ...params ) => {
  1902. currentStack.assign( nodeObj, ...params );
  1903. return nodeObj;
  1904. };
  1905. } else if ( NodeElements.has( prop ) ) {
  1906. const nodeElement = NodeElements.get( prop );
  1907. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1908. } else if ( prop === 'self' ) {
  1909. return node;
  1910. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1911. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1912. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1913. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1914. // accessing properties ( swizzle )
  1915. prop = parseSwizzle( prop );
  1916. return nodeObject( new SplitNode( nodeObj, prop ) );
  1917. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1918. // set properties ( swizzle ) and sort to xyzw sequence
  1919. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1920. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1921. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1922. // set properties ( swizzle ) and sort to xyzw sequence
  1923. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1924. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1925. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1926. // accessing property
  1927. if ( prop === 'width' ) prop = 'x';
  1928. else if ( prop === 'height' ) prop = 'y';
  1929. else if ( prop === 'depth' ) prop = 'z';
  1930. return nodeObject( new SplitNode( node, prop ) );
  1931. } else if ( /^\d+$/.test( prop ) === true ) {
  1932. // accessing array
  1933. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1934. }
  1935. }
  1936. return Reflect.get( node, prop, nodeObj );
  1937. },
  1938. set( node, prop, value, nodeObj ) {
  1939. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1940. // setting properties
  1941. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1942. nodeObj[ prop ].assign( value );
  1943. return true;
  1944. }
  1945. }
  1946. return Reflect.set( node, prop, value, nodeObj );
  1947. }
  1948. };
  1949. const nodeObjectsCacheMap = new WeakMap();
  1950. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1951. const ShaderNodeObject = function ( obj, altType = null ) {
  1952. const type = getValueType( obj );
  1953. if ( type === 'node' ) {
  1954. let nodeObject = nodeObjectsCacheMap.get( obj );
  1955. if ( nodeObject === undefined ) {
  1956. nodeObject = new Proxy( obj, shaderNodeHandler );
  1957. nodeObjectsCacheMap.set( obj, nodeObject );
  1958. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1959. }
  1960. return nodeObject;
  1961. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1962. return nodeObject( getConstNode( obj, altType ) );
  1963. } else if ( type === 'shader' ) {
  1964. return Fn( obj );
  1965. }
  1966. return obj;
  1967. };
  1968. const ShaderNodeObjects = function ( objects, altType = null ) {
  1969. for ( const name in objects ) {
  1970. objects[ name ] = nodeObject( objects[ name ], altType );
  1971. }
  1972. return objects;
  1973. };
  1974. const ShaderNodeArray = function ( array, altType = null ) {
  1975. const len = array.length;
  1976. for ( let i = 0; i < len; i ++ ) {
  1977. array[ i ] = nodeObject( array[ i ], altType );
  1978. }
  1979. return array;
  1980. };
  1981. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1982. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1983. if ( scope === null ) {
  1984. return ( ...params ) => {
  1985. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1986. };
  1987. } else if ( factor !== null ) {
  1988. factor = nodeObject( factor );
  1989. return ( ...params ) => {
  1990. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1991. };
  1992. } else {
  1993. return ( ...params ) => {
  1994. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1995. };
  1996. }
  1997. };
  1998. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1999. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2000. };
  2001. class ShaderCallNodeInternal extends Node {
  2002. constructor( shaderNode, inputNodes ) {
  2003. super();
  2004. this.shaderNode = shaderNode;
  2005. this.inputNodes = inputNodes;
  2006. }
  2007. getNodeType( builder ) {
  2008. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2009. }
  2010. call( builder ) {
  2011. const { shaderNode, inputNodes } = this;
  2012. const properties = builder.getNodeProperties( shaderNode );
  2013. if ( properties.onceOutput ) return properties.onceOutput;
  2014. //
  2015. let result = null;
  2016. if ( shaderNode.layout ) {
  2017. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2018. if ( functionNodesCacheMap === undefined ) {
  2019. functionNodesCacheMap = new WeakMap();
  2020. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2021. }
  2022. let functionNode = functionNodesCacheMap.get( shaderNode );
  2023. if ( functionNode === undefined ) {
  2024. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2025. functionNodesCacheMap.set( shaderNode, functionNode );
  2026. }
  2027. if ( builder.currentFunctionNode !== null ) {
  2028. builder.currentFunctionNode.includes.push( functionNode );
  2029. }
  2030. result = nodeObject( functionNode.call( inputNodes ) );
  2031. } else {
  2032. const jsFunc = shaderNode.jsFunc;
  2033. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  2034. result = nodeObject( outputNode );
  2035. }
  2036. if ( shaderNode.once ) {
  2037. properties.onceOutput = result;
  2038. }
  2039. return result;
  2040. }
  2041. getOutputNode( builder ) {
  2042. const properties = builder.getNodeProperties( this );
  2043. if ( properties.outputNode === null ) {
  2044. properties.outputNode = this.setupOutput( builder );
  2045. }
  2046. return properties.outputNode;
  2047. }
  2048. setup( builder ) {
  2049. return this.getOutputNode( builder );
  2050. }
  2051. setupOutput( builder ) {
  2052. builder.addStack();
  2053. builder.stack.outputNode = this.call( builder );
  2054. return builder.removeStack();
  2055. }
  2056. generate( builder, output ) {
  2057. const outputNode = this.getOutputNode( builder );
  2058. return outputNode.build( builder, output );
  2059. }
  2060. }
  2061. class ShaderNodeInternal extends Node {
  2062. constructor( jsFunc, nodeType ) {
  2063. super( nodeType );
  2064. this.jsFunc = jsFunc;
  2065. this.layout = null;
  2066. this.global = true;
  2067. this.once = false;
  2068. }
  2069. setLayout( layout ) {
  2070. this.layout = layout;
  2071. return this;
  2072. }
  2073. call( inputs = null ) {
  2074. nodeObjects( inputs );
  2075. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2076. }
  2077. setup() {
  2078. return this.call();
  2079. }
  2080. }
  2081. const bools = [ false, true ];
  2082. const uints = [ 0, 1, 2, 3 ];
  2083. const ints = [ - 1, - 2 ];
  2084. 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 ];
  2085. const boolsCacheMap = new Map();
  2086. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2087. const uintsCacheMap = new Map();
  2088. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2089. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2090. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2091. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2092. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2093. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2094. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2095. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2096. const getConstNode = ( value, type ) => {
  2097. if ( constNodesCacheMap.has( value ) ) {
  2098. return constNodesCacheMap.get( value );
  2099. } else if ( value.isNode === true ) {
  2100. return value;
  2101. } else {
  2102. return new ConstNode( value, type );
  2103. }
  2104. };
  2105. const safeGetNodeType = ( node ) => {
  2106. try {
  2107. return node.getNodeType();
  2108. } catch ( _ ) {
  2109. return undefined;
  2110. }
  2111. };
  2112. const ConvertType = function ( type, cacheMap = null ) {
  2113. return ( ...params ) => {
  2114. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2115. params = [ getValueFromType( type, ...params ) ];
  2116. }
  2117. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2118. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2119. }
  2120. if ( params.length === 1 ) {
  2121. const node = getConstNode( params[ 0 ], type );
  2122. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2123. return nodeObject( new ConvertNode( node, type ) );
  2124. }
  2125. const nodes = params.map( param => getConstNode( param ) );
  2126. return nodeObject( new JoinNode( nodes, type ) );
  2127. };
  2128. };
  2129. // exports
  2130. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2131. // utils
  2132. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2133. // shader node base
  2134. function ShaderNode( jsFunc, nodeType ) {
  2135. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2136. }
  2137. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2138. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2139. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2140. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2141. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2142. const Fn = ( jsFunc, nodeType ) => {
  2143. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2144. const fn = ( ...params ) => {
  2145. let inputs;
  2146. nodeObjects( params );
  2147. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2148. inputs = [ ...params ];
  2149. } else {
  2150. inputs = params[ 0 ];
  2151. }
  2152. return shaderNode.call( inputs );
  2153. };
  2154. fn.shaderNode = shaderNode;
  2155. fn.setLayout = ( layout ) => {
  2156. shaderNode.setLayout( layout );
  2157. return fn;
  2158. };
  2159. fn.once = () => {
  2160. shaderNode.once = true;
  2161. return fn;
  2162. };
  2163. return fn;
  2164. };
  2165. const tslFn = ( ...params ) => { // @deprecated, r168
  2166. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2167. return Fn( ...params );
  2168. };
  2169. //
  2170. addMethodChaining( 'toGlobal', ( node ) => {
  2171. node.global = true;
  2172. return node;
  2173. } );
  2174. //
  2175. const setCurrentStack = ( stack ) => {
  2176. currentStack = stack;
  2177. };
  2178. const getCurrentStack = () => currentStack;
  2179. const If = ( ...params ) => currentStack.If( ...params );
  2180. function append( node ) {
  2181. if ( currentStack ) currentStack.add( node );
  2182. return node;
  2183. }
  2184. addMethodChaining( 'append', append );
  2185. // types
  2186. const color = new ConvertType( 'color' );
  2187. const float = new ConvertType( 'float', cacheMaps.float );
  2188. const int = new ConvertType( 'int', cacheMaps.ints );
  2189. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2190. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2191. const vec2 = new ConvertType( 'vec2' );
  2192. const ivec2 = new ConvertType( 'ivec2' );
  2193. const uvec2 = new ConvertType( 'uvec2' );
  2194. const bvec2 = new ConvertType( 'bvec2' );
  2195. const vec3 = new ConvertType( 'vec3' );
  2196. const ivec3 = new ConvertType( 'ivec3' );
  2197. const uvec3 = new ConvertType( 'uvec3' );
  2198. const bvec3 = new ConvertType( 'bvec3' );
  2199. const vec4 = new ConvertType( 'vec4' );
  2200. const ivec4 = new ConvertType( 'ivec4' );
  2201. const uvec4 = new ConvertType( 'uvec4' );
  2202. const bvec4 = new ConvertType( 'bvec4' );
  2203. const mat2 = new ConvertType( 'mat2' );
  2204. const mat3 = new ConvertType( 'mat3' );
  2205. const mat4 = new ConvertType( 'mat4' );
  2206. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2207. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2208. addMethodChaining( 'toColor', color );
  2209. addMethodChaining( 'toFloat', float );
  2210. addMethodChaining( 'toInt', int );
  2211. addMethodChaining( 'toUint', uint );
  2212. addMethodChaining( 'toBool', bool );
  2213. addMethodChaining( 'toVec2', vec2 );
  2214. addMethodChaining( 'toIVec2', ivec2 );
  2215. addMethodChaining( 'toUVec2', uvec2 );
  2216. addMethodChaining( 'toBVec2', bvec2 );
  2217. addMethodChaining( 'toVec3', vec3 );
  2218. addMethodChaining( 'toIVec3', ivec3 );
  2219. addMethodChaining( 'toUVec3', uvec3 );
  2220. addMethodChaining( 'toBVec3', bvec3 );
  2221. addMethodChaining( 'toVec4', vec4 );
  2222. addMethodChaining( 'toIVec4', ivec4 );
  2223. addMethodChaining( 'toUVec4', uvec4 );
  2224. addMethodChaining( 'toBVec4', bvec4 );
  2225. addMethodChaining( 'toMat2', mat2 );
  2226. addMethodChaining( 'toMat3', mat3 );
  2227. addMethodChaining( 'toMat4', mat4 );
  2228. // basic nodes
  2229. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2230. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2231. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2232. addMethodChaining( 'element', element );
  2233. addMethodChaining( 'convert', convert );
  2234. /** @module UniformGroupNode **/
  2235. /**
  2236. * This node can be used to group single instances of {@link UniformNode}
  2237. * and manage them as a uniform buffer.
  2238. *
  2239. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2240. * will be used when defining the {@link UniformNode#groupNode} property.
  2241. *
  2242. * - `objectGroup`: Uniform buffer per object.
  2243. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2244. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2245. *
  2246. * @augments Node
  2247. */
  2248. class UniformGroupNode extends Node {
  2249. static get type() {
  2250. return 'UniformGroupNode';
  2251. }
  2252. /**
  2253. * Constructs a new uniform group node.
  2254. *
  2255. * @param {String} name - The name of the uniform group node.
  2256. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2257. * @param {Number} [order=1] - Influences the internal sorting.
  2258. */
  2259. constructor( name, shared = false, order = 1 ) {
  2260. super( 'string' );
  2261. /**
  2262. * The name of the uniform group node.
  2263. *
  2264. * @type {String}
  2265. */
  2266. this.name = name;
  2267. /**
  2268. * Whether this uniform group node is shared or not.
  2269. *
  2270. * @type {Boolean}
  2271. * @default false
  2272. */
  2273. this.shared = shared;
  2274. /**
  2275. * Influences the internal sorting.
  2276. * TODO: Add details when this property should be changed.
  2277. *
  2278. * @type {Number}
  2279. * @default 1
  2280. */
  2281. this.order = order;
  2282. /**
  2283. * This flag can be used for type testing.
  2284. *
  2285. * @type {Boolean}
  2286. * @readonly
  2287. * @default true
  2288. */
  2289. this.isUniformGroup = true;
  2290. }
  2291. serialize( data ) {
  2292. super.serialize( data );
  2293. data.name = this.name;
  2294. data.version = this.version;
  2295. data.shared = this.shared;
  2296. }
  2297. deserialize( data ) {
  2298. super.deserialize( data );
  2299. this.name = data.name;
  2300. this.version = data.version;
  2301. this.shared = data.shared;
  2302. }
  2303. }
  2304. /**
  2305. * TSL function for creating a uniform group node with the given name.
  2306. *
  2307. * @function
  2308. * @param {String} name - The name of the uniform group node.
  2309. * @returns {UniformGroupNode}
  2310. */
  2311. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2312. /**
  2313. * TSL function for creating a shared uniform group node with the given name and order.
  2314. *
  2315. * @function
  2316. * @param {String} name - The name of the uniform group node.
  2317. * @param {Number} [order=0] - Influences the internal sorting.
  2318. * @returns {UniformGroupNode}
  2319. */
  2320. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2321. /**
  2322. * TSL object that represents a shared uniform group node which is updated once per frame.
  2323. *
  2324. * @type {UniformGroupNode}
  2325. */
  2326. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2327. /**
  2328. * TSL object that represents a shared uniform group node which is updated once per render.
  2329. *
  2330. * @type {UniformGroupNode}
  2331. */
  2332. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2333. /**
  2334. * TSL object that represents a uniform group node which is updated once per object.
  2335. *
  2336. * @type {UniformGroupNode}
  2337. */
  2338. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2339. /** @module UniformNode **/
  2340. /**
  2341. * Class for representing a uniform.
  2342. *
  2343. * @augments InputNode
  2344. */
  2345. class UniformNode extends InputNode {
  2346. static get type() {
  2347. return 'UniformNode';
  2348. }
  2349. /**
  2350. * Constructs a new uniform node.
  2351. *
  2352. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2353. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2354. */
  2355. constructor( value, nodeType = null ) {
  2356. super( value, nodeType );
  2357. /**
  2358. * This flag can be used for type testing.
  2359. *
  2360. * @type {Boolean}
  2361. * @readonly
  2362. * @default true
  2363. */
  2364. this.isUniformNode = true;
  2365. /**
  2366. * The name or label of the uniform.
  2367. *
  2368. * @type {String}
  2369. * @default ''
  2370. */
  2371. this.name = '';
  2372. /**
  2373. * The uniform group of this uniform. By default, uniforms are
  2374. * managed per object but they might belong to a shared group
  2375. * which is updated per frame or render call.
  2376. *
  2377. * @type {UniformGroupNode}
  2378. */
  2379. this.groupNode = objectGroup;
  2380. }
  2381. /**
  2382. * Sets the {@link UniformNode#name} property.
  2383. *
  2384. * @param {String} name - The name of the uniform.
  2385. * @return {UniformNode} A reference to this node.
  2386. */
  2387. label( name ) {
  2388. this.name = name;
  2389. return this;
  2390. }
  2391. /**
  2392. * Sets the {@link UniformNode#groupNode} property.
  2393. *
  2394. * @param {UniformGroupNode} group - The uniform group.
  2395. * @return {UniformNode} A reference to this node.
  2396. */
  2397. setGroup( group ) {
  2398. this.groupNode = group;
  2399. return this;
  2400. }
  2401. /**
  2402. * Returns the {@link UniformNode#groupNode}.
  2403. *
  2404. * @return {UniformGroupNode} The uniform group.
  2405. */
  2406. getGroup() {
  2407. return this.groupNode;
  2408. }
  2409. /**
  2410. * By default, this method returns the result of {@link Node#getHash} but derived
  2411. * classes might overwrite this method with a different implementation.
  2412. *
  2413. * @param {NodeBuilder} builder - The current node builder.
  2414. * @return {String} The uniform hash.
  2415. */
  2416. getUniformHash( builder ) {
  2417. return this.getHash( builder );
  2418. }
  2419. onUpdate( callback, updateType ) {
  2420. const self = this.getSelf();
  2421. callback = callback.bind( self );
  2422. return super.onUpdate( ( frame ) => {
  2423. const value = callback( frame, self );
  2424. if ( value !== undefined ) {
  2425. this.value = value;
  2426. }
  2427. }, updateType );
  2428. }
  2429. generate( builder, output ) {
  2430. const type = this.getNodeType( builder );
  2431. const hash = this.getUniformHash( builder );
  2432. let sharedNode = builder.getNodeFromHash( hash );
  2433. if ( sharedNode === undefined ) {
  2434. builder.setHashNode( this, hash );
  2435. sharedNode = this;
  2436. }
  2437. const sharedNodeType = sharedNode.getInputType( builder );
  2438. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2439. const propertyName = builder.getPropertyName( nodeUniform );
  2440. if ( builder.context.label !== undefined ) delete builder.context.label;
  2441. return builder.format( propertyName, type, output );
  2442. }
  2443. }
  2444. /**
  2445. * TSL function for creating a uniform node.
  2446. *
  2447. * @function
  2448. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2449. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2450. * @returns {UniformNode}
  2451. */
  2452. const uniform = ( arg1, arg2 ) => {
  2453. const nodeType = getConstNodeType( arg2 || arg1 );
  2454. // @TODO: get ConstNode from .traverse() in the future
  2455. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2456. return nodeObject( new UniformNode( value, nodeType ) );
  2457. };
  2458. /** @module PropertyNode **/
  2459. /**
  2460. * This class represents a shader property. It can be used
  2461. * to explicitly define a property and assign a value to it.
  2462. *
  2463. * ```js
  2464. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2465. *```
  2466. * `PropertyNode` is used by the engine to predefined common material properties
  2467. * for TSL code.
  2468. *
  2469. * @augments Node
  2470. */
  2471. class PropertyNode extends Node {
  2472. static get type() {
  2473. return 'PropertyNode';
  2474. }
  2475. /**
  2476. * Constructs a new property node.
  2477. *
  2478. * @param {String} nodeType - The type of the node.
  2479. * @param {String?} [name=null] - The name of the property in the shader.
  2480. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2481. */
  2482. constructor( nodeType, name = null, varying = false ) {
  2483. super( nodeType );
  2484. /**
  2485. * The name of the property in the shader. If no name is defined,
  2486. * the node system auto-generates one.
  2487. *
  2488. * @type {String?}
  2489. * @default null
  2490. */
  2491. this.name = name;
  2492. /**
  2493. * Whether this property is a varying or not.
  2494. *
  2495. * @type {Boolean}
  2496. * @default false
  2497. */
  2498. this.varying = varying;
  2499. /**
  2500. * This flag can be used for type testing.
  2501. *
  2502. * @type {Boolean}
  2503. * @readonly
  2504. * @default true
  2505. */
  2506. this.isPropertyNode = true;
  2507. }
  2508. getHash( builder ) {
  2509. return this.name || super.getHash( builder );
  2510. }
  2511. /**
  2512. * The method is overwritten so it always returns `true`.
  2513. *
  2514. * @param {NodeBuilder} builder - The current node builder.
  2515. * @return {Boolean} Whether this node is global or not.
  2516. */
  2517. isGlobal( /*builder*/ ) {
  2518. return true;
  2519. }
  2520. generate( builder ) {
  2521. let nodeVar;
  2522. if ( this.varying === true ) {
  2523. nodeVar = builder.getVaryingFromNode( this, this.name );
  2524. nodeVar.needsInterpolation = true;
  2525. } else {
  2526. nodeVar = builder.getVarFromNode( this, this.name );
  2527. }
  2528. return builder.getPropertyName( nodeVar );
  2529. }
  2530. }
  2531. /**
  2532. * TSL function for creating a property node.
  2533. *
  2534. * @function
  2535. * @param {String} type - The type of the node.
  2536. * @param {String?} [name=null] - The name of the property in the shader.
  2537. * @returns {PropertyNode}
  2538. */
  2539. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2540. /**
  2541. * TSL function for creating a varying property node.
  2542. *
  2543. * @function
  2544. * @param {String} type - The type of the node.
  2545. * @param {String?} [name=null] - The name of the varying in the shader.
  2546. * @returns {PropertyNode}
  2547. */
  2548. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2549. /**
  2550. * TSL object that represents the shader variable `DiffuseColor`.
  2551. *
  2552. * @type {PropertyNode<vec4>}
  2553. */
  2554. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2555. /**
  2556. * TSL object that represents the shader variable `EmissiveColor`.
  2557. *
  2558. * @type {PropertyNode<vec3>}
  2559. */
  2560. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2561. /**
  2562. * TSL object that represents the shader variable `Roughness`.
  2563. *
  2564. * @type {PropertyNode<float>}
  2565. */
  2566. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2567. /**
  2568. * TSL object that represents the shader variable `Metalness`.
  2569. *
  2570. * @type {PropertyNode<float>}
  2571. */
  2572. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2573. /**
  2574. * TSL object that represents the shader variable `Clearcoat`.
  2575. *
  2576. * @type {PropertyNode<float>}
  2577. */
  2578. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2579. /**
  2580. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2581. *
  2582. * @type {PropertyNode<float>}
  2583. */
  2584. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2585. /**
  2586. * TSL object that represents the shader variable `Sheen`.
  2587. *
  2588. * @type {PropertyNode<vec3>}
  2589. */
  2590. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2591. /**
  2592. * TSL object that represents the shader variable `SheenRoughness`.
  2593. *
  2594. * @type {PropertyNode<float>}
  2595. */
  2596. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2597. /**
  2598. * TSL object that represents the shader variable `Iridescence`.
  2599. *
  2600. * @type {PropertyNode<float>}
  2601. */
  2602. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2603. /**
  2604. * TSL object that represents the shader variable `IridescenceIOR`.
  2605. *
  2606. * @type {PropertyNode<float>}
  2607. */
  2608. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2609. /**
  2610. * TSL object that represents the shader variable `IridescenceThickness`.
  2611. *
  2612. * @type {PropertyNode<float>}
  2613. */
  2614. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2615. /**
  2616. * TSL object that represents the shader variable `AlphaT`.
  2617. *
  2618. * @type {PropertyNode<float>}
  2619. */
  2620. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2621. /**
  2622. * TSL object that represents the shader variable `Anisotropy`.
  2623. *
  2624. * @type {PropertyNode<float>}
  2625. */
  2626. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2627. /**
  2628. * TSL object that represents the shader variable `AnisotropyT`.
  2629. *
  2630. * @type {PropertyNode<vec3>}
  2631. */
  2632. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2633. /**
  2634. * TSL object that represents the shader variable `AnisotropyB`.
  2635. *
  2636. * @type {PropertyNode<vec3>}
  2637. */
  2638. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2639. /**
  2640. * TSL object that represents the shader variable `SpecularColor`.
  2641. *
  2642. * @type {PropertyNode<color>}
  2643. */
  2644. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2645. /**
  2646. * TSL object that represents the shader variable `SpecularF90`.
  2647. *
  2648. * @type {PropertyNode<float>}
  2649. */
  2650. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2651. /**
  2652. * TSL object that represents the shader variable `Shininess`.
  2653. *
  2654. * @type {PropertyNode<float>}
  2655. */
  2656. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2657. /**
  2658. * TSL object that represents the shader variable `Output`.
  2659. *
  2660. * @type {PropertyNode<vec4>}
  2661. */
  2662. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2663. /**
  2664. * TSL object that represents the shader variable `dashSize`.
  2665. *
  2666. * @type {PropertyNode<float>}
  2667. */
  2668. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2669. /**
  2670. * TSL object that represents the shader variable `gapSize`.
  2671. *
  2672. * @type {PropertyNode<float>}
  2673. */
  2674. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2675. /**
  2676. * TSL object that represents the shader variable `pointWidth`.
  2677. *
  2678. * @type {PropertyNode<float>}
  2679. */
  2680. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2681. /**
  2682. * TSL object that represents the shader variable `IOR`.
  2683. *
  2684. * @type {PropertyNode<float>}
  2685. */
  2686. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2687. /**
  2688. * TSL object that represents the shader variable `Transmission`.
  2689. *
  2690. * @type {PropertyNode<float>}
  2691. */
  2692. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2693. /**
  2694. * TSL object that represents the shader variable `Thickness`.
  2695. *
  2696. * @type {PropertyNode<float>}
  2697. */
  2698. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2699. /**
  2700. * TSL object that represents the shader variable `AttenuationDistance`.
  2701. *
  2702. * @type {PropertyNode<float>}
  2703. */
  2704. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2705. /**
  2706. * TSL object that represents the shader variable `AttenuationColor`.
  2707. *
  2708. * @type {PropertyNode<color>}
  2709. */
  2710. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2711. /**
  2712. * TSL object that represents the shader variable `Dispersion`.
  2713. *
  2714. * @type {PropertyNode<float>}
  2715. */
  2716. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2717. /** @module AssignNode **/
  2718. /**
  2719. * These node represents an assign operation. Meaning a node is assigned
  2720. * to another node.
  2721. *
  2722. * @augments TempNode
  2723. */
  2724. class AssignNode extends TempNode {
  2725. static get type() {
  2726. return 'AssignNode';
  2727. }
  2728. /**
  2729. * Constructs a new assign node.
  2730. *
  2731. * @param {Node} targetNode - The target node.
  2732. * @param {Node} sourceNode - The source type.
  2733. */
  2734. constructor( targetNode, sourceNode ) {
  2735. super();
  2736. /**
  2737. * The target node.
  2738. *
  2739. * @type {Node}
  2740. */
  2741. this.targetNode = targetNode;
  2742. /**
  2743. * The source node.
  2744. *
  2745. * @type {Node}
  2746. */
  2747. this.sourceNode = sourceNode;
  2748. }
  2749. /**
  2750. * Whether this node is used more than once in context of other nodes. This method
  2751. * is overwritten since it always returns `false` (assigns are unique).
  2752. *
  2753. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2754. */
  2755. hasDependencies() {
  2756. return false;
  2757. }
  2758. getNodeType( builder, output ) {
  2759. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2760. }
  2761. /**
  2762. * Whether a split is required when assigning source to target. This can happen when the component length of
  2763. * target and source data type does not match.
  2764. *
  2765. * @param {NodeBuilder} builder - The current node builder.
  2766. * @return {Boolean} Whether a split is required when assigning source to target.
  2767. */
  2768. needsSplitAssign( builder ) {
  2769. const { targetNode } = this;
  2770. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2771. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2772. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2773. return assignDifferentVector;
  2774. }
  2775. return false;
  2776. }
  2777. generate( builder, output ) {
  2778. const { targetNode, sourceNode } = this;
  2779. const needsSplitAssign = this.needsSplitAssign( builder );
  2780. const targetType = targetNode.getNodeType( builder );
  2781. const target = targetNode.context( { assign: true } ).build( builder );
  2782. const source = sourceNode.build( builder, targetType );
  2783. const sourceType = sourceNode.getNodeType( builder );
  2784. const nodeData = builder.getDataFromNode( this );
  2785. //
  2786. let snippet;
  2787. if ( nodeData.initialized === true ) {
  2788. if ( output !== 'void' ) {
  2789. snippet = target;
  2790. }
  2791. } else if ( needsSplitAssign ) {
  2792. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2793. const sourceProperty = builder.getPropertyName( sourceVar );
  2794. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2795. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2796. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2797. const component = targetNode.components[ i ];
  2798. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2799. }
  2800. if ( output !== 'void' ) {
  2801. snippet = target;
  2802. }
  2803. } else {
  2804. snippet = `${ target } = ${ source }`;
  2805. if ( output === 'void' || sourceType === 'void' ) {
  2806. builder.addLineFlowCode( snippet, this );
  2807. if ( output !== 'void' ) {
  2808. snippet = target;
  2809. }
  2810. }
  2811. }
  2812. nodeData.initialized = true;
  2813. return builder.format( snippet, targetType, output );
  2814. }
  2815. }
  2816. /**
  2817. * TSL function for creating an assign node.
  2818. *
  2819. * @function
  2820. * @param {Node} targetNode - The target node.
  2821. * @param {Node} sourceNode - The source type.
  2822. * @returns {AssignNode}
  2823. */
  2824. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2825. addMethodChaining( 'assign', assign );
  2826. /**
  2827. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2828. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2829. * this logic.
  2830. *
  2831. * @augments TempNode
  2832. */
  2833. class FunctionCallNode extends TempNode {
  2834. static get type() {
  2835. return 'FunctionCallNode';
  2836. }
  2837. /**
  2838. * Constructs a new function call node.
  2839. *
  2840. * @param {FunctionNode?} functionNode - The function node.
  2841. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2842. */
  2843. constructor( functionNode = null, parameters = {} ) {
  2844. super();
  2845. /**
  2846. * The function node.
  2847. *
  2848. * @type {FunctionNode}
  2849. * @default null
  2850. */
  2851. this.functionNode = functionNode;
  2852. /**
  2853. * The parameters of the function call.
  2854. *
  2855. * @type {Object<String, Node>}
  2856. * @default {}
  2857. */
  2858. this.parameters = parameters;
  2859. }
  2860. /**
  2861. * Sets the parameters of the function call node.
  2862. *
  2863. * @param {Object<String, Node>} parameters - The parameters to set.
  2864. * @return {FunctionCallNode} A reference to this node.
  2865. */
  2866. setParameters( parameters ) {
  2867. this.parameters = parameters;
  2868. return this;
  2869. }
  2870. /**
  2871. * Returns the parameters of the function call node.
  2872. *
  2873. * @return {Object<String, Node>} The parameters of this node.
  2874. */
  2875. getParameters() {
  2876. return this.parameters;
  2877. }
  2878. getNodeType( builder ) {
  2879. return this.functionNode.getNodeType( builder );
  2880. }
  2881. generate( builder ) {
  2882. const params = [];
  2883. const functionNode = this.functionNode;
  2884. const inputs = functionNode.getInputs( builder );
  2885. const parameters = this.parameters;
  2886. const generateInput = ( node, inputNode ) => {
  2887. const type = inputNode.type;
  2888. const pointer = type === 'pointer';
  2889. let output;
  2890. if ( pointer ) output = '&' + node.build( builder );
  2891. else output = node.build( builder, type );
  2892. return output;
  2893. };
  2894. if ( Array.isArray( parameters ) ) {
  2895. for ( let i = 0; i < parameters.length; i ++ ) {
  2896. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2897. }
  2898. } else {
  2899. for ( const inputNode of inputs ) {
  2900. const node = parameters[ inputNode.name ];
  2901. if ( node !== undefined ) {
  2902. params.push( generateInput( node, inputNode ) );
  2903. } else {
  2904. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2905. }
  2906. }
  2907. }
  2908. const functionName = functionNode.build( builder, 'property' );
  2909. return `${functionName}( ${params.join( ', ' )} )`;
  2910. }
  2911. }
  2912. const call = ( func, ...params ) => {
  2913. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2914. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2915. };
  2916. addMethodChaining( 'call', call );
  2917. /** @module OperatorNode **/
  2918. /**
  2919. * This node represents basic mathematical and logical operations like addition,
  2920. * subtraction or comparisons (e.g. `equal()`).
  2921. *
  2922. * @augments TempNode
  2923. */
  2924. class OperatorNode extends TempNode {
  2925. static get type() {
  2926. return 'OperatorNode';
  2927. }
  2928. /**
  2929. * Constructs a new operator node.
  2930. *
  2931. * @param {String} op - The operator.
  2932. * @param {Node} aNode - The first input.
  2933. * @param {Node} bNode - The second input.
  2934. * @param {...Node} params - Additional input parameters.
  2935. */
  2936. constructor( op, aNode, bNode, ...params ) {
  2937. super();
  2938. if ( params.length > 0 ) {
  2939. let finalOp = new OperatorNode( op, aNode, bNode );
  2940. for ( let i = 0; i < params.length - 1; i ++ ) {
  2941. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2942. }
  2943. aNode = finalOp;
  2944. bNode = params[ params.length - 1 ];
  2945. }
  2946. /**
  2947. * The operator.
  2948. *
  2949. * @type {String}
  2950. */
  2951. this.op = op;
  2952. /**
  2953. * The first input.
  2954. *
  2955. * @type {Node}
  2956. */
  2957. this.aNode = aNode;
  2958. /**
  2959. * The second input.
  2960. *
  2961. * @type {Node}
  2962. */
  2963. this.bNode = bNode;
  2964. }
  2965. /**
  2966. * This method is overwritten since the node type is inferred from the operator
  2967. * and the input node types.
  2968. *
  2969. * @param {NodeBuilder} builder - The current node builder.
  2970. * @param {String} output - The current output string.
  2971. * @return {String} The node type.
  2972. */
  2973. getNodeType( builder, output ) {
  2974. const op = this.op;
  2975. const aNode = this.aNode;
  2976. const bNode = this.bNode;
  2977. const typeA = aNode.getNodeType( builder );
  2978. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2979. if ( typeA === 'void' || typeB === 'void' ) {
  2980. return 'void';
  2981. } else if ( op === '%' ) {
  2982. return typeA;
  2983. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2984. return builder.getIntegerType( typeA );
  2985. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2986. return 'bool';
  2987. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2988. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2989. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2990. } else {
  2991. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2992. return typeB;
  2993. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2994. // matrix x vector
  2995. return builder.getVectorFromMatrix( typeA );
  2996. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2997. // vector x matrix
  2998. return builder.getVectorFromMatrix( typeB );
  2999. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3000. // anytype x anytype: use the greater length vector
  3001. return typeB;
  3002. }
  3003. return typeA;
  3004. }
  3005. }
  3006. generate( builder, output ) {
  3007. const op = this.op;
  3008. const aNode = this.aNode;
  3009. const bNode = this.bNode;
  3010. const type = this.getNodeType( builder, output );
  3011. let typeA = null;
  3012. let typeB = null;
  3013. if ( type !== 'void' ) {
  3014. typeA = aNode.getNodeType( builder );
  3015. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3016. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3017. if ( builder.isVector( typeA ) ) {
  3018. typeB = typeA;
  3019. } else if ( typeA !== typeB ) {
  3020. typeA = typeB = 'float';
  3021. }
  3022. } else if ( op === '>>' || op === '<<' ) {
  3023. typeA = type;
  3024. typeB = builder.changeComponentType( typeB, 'uint' );
  3025. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3026. // matrix x vector
  3027. typeB = builder.getVectorFromMatrix( typeA );
  3028. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3029. // vector x matrix
  3030. typeA = builder.getVectorFromMatrix( typeB );
  3031. } else {
  3032. // anytype x anytype
  3033. typeA = typeB = type;
  3034. }
  3035. } else {
  3036. typeA = typeB = type;
  3037. }
  3038. const a = aNode.build( builder, typeA );
  3039. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3040. const outputLength = builder.getTypeLength( output );
  3041. const fnOpSnippet = builder.getFunctionOperator( op );
  3042. if ( output !== 'void' ) {
  3043. if ( op === '<' && outputLength > 1 ) {
  3044. if ( builder.useComparisonMethod ) {
  3045. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3046. } else {
  3047. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3048. }
  3049. } else if ( op === '<=' && outputLength > 1 ) {
  3050. if ( builder.useComparisonMethod ) {
  3051. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3052. } else {
  3053. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3054. }
  3055. } else if ( op === '>' && outputLength > 1 ) {
  3056. if ( builder.useComparisonMethod ) {
  3057. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3058. } else {
  3059. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3060. }
  3061. } else if ( op === '>=' && outputLength > 1 ) {
  3062. if ( builder.useComparisonMethod ) {
  3063. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3064. } else {
  3065. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3066. }
  3067. } else if ( op === '!' || op === '~' ) {
  3068. return builder.format( `(${op}${a})`, typeA, output );
  3069. } else if ( fnOpSnippet ) {
  3070. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3071. } else {
  3072. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3073. }
  3074. } else if ( typeA !== 'void' ) {
  3075. if ( fnOpSnippet ) {
  3076. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3077. } else {
  3078. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3079. }
  3080. }
  3081. }
  3082. serialize( data ) {
  3083. super.serialize( data );
  3084. data.op = this.op;
  3085. }
  3086. deserialize( data ) {
  3087. super.deserialize( data );
  3088. this.op = data.op;
  3089. }
  3090. }
  3091. /**
  3092. * Returns the addition of two or more value.
  3093. *
  3094. * @function
  3095. * @param {Node} aNode - The first input.
  3096. * @param {Node} bNode - The second input.
  3097. * @param {...Node} params - Additional input parameters.
  3098. * @returns {OperatorNode}
  3099. */
  3100. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3101. /**
  3102. * Returns the subtraction of two or more value.
  3103. *
  3104. * @function
  3105. * @param {Node} aNode - The first input.
  3106. * @param {Node} bNode - The second input.
  3107. * @param {...Node} params - Additional input parameters.
  3108. * @returns {OperatorNode}
  3109. */
  3110. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3111. /**
  3112. * Returns the multiplication of two or more value.
  3113. *
  3114. * @function
  3115. * @param {Node} aNode - The first input.
  3116. * @param {Node} bNode - The second input.
  3117. * @param {...Node} params - Additional input parameters.
  3118. * @returns {OperatorNode}
  3119. */
  3120. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3121. /**
  3122. * Returns the division of two or more value.
  3123. *
  3124. * @function
  3125. * @param {Node} aNode - The first input.
  3126. * @param {Node} bNode - The second input.
  3127. * @param {...Node} params - Additional input parameters.
  3128. * @returns {OperatorNode}
  3129. */
  3130. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3131. /**
  3132. * Computes the remainder of dividing the first node by the second, for integer values.
  3133. *
  3134. * @function
  3135. * @param {Node} aNode - The first input.
  3136. * @param {Node} bNode - The second input.
  3137. * @returns {OperatorNode}
  3138. */
  3139. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3140. /**
  3141. * Checks if two nodes are equal.
  3142. *
  3143. * @function
  3144. * @param {Node} aNode - The first input.
  3145. * @param {Node} bNode - The second input.
  3146. * @returns {OperatorNode}
  3147. */
  3148. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3149. /**
  3150. * Checks if two nodes are not equal.
  3151. *
  3152. * @function
  3153. * @param {Node} aNode - The first input.
  3154. * @param {Node} bNode - The second input.
  3155. * @returns {OperatorNode}
  3156. */
  3157. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3158. /**
  3159. * Checks if the first node is less than the second.
  3160. *
  3161. * @function
  3162. * @param {Node} aNode - The first input.
  3163. * @param {Node} bNode - The second input.
  3164. * @returns {OperatorNode}
  3165. */
  3166. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3167. /**
  3168. * Checks if the first node is greater than the second.
  3169. *
  3170. * @function
  3171. * @param {Node} aNode - The first input.
  3172. * @param {Node} bNode - The second input.
  3173. * @returns {OperatorNode}
  3174. */
  3175. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3176. /**
  3177. * Checks if the first node is less than or equal to the second.
  3178. *
  3179. * @function
  3180. * @param {Node} aNode - The first input.
  3181. * @param {Node} bNode - The second input.
  3182. * @returns {OperatorNode}
  3183. */
  3184. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3185. /**
  3186. * Checks if the first node is greater than or equal to the second.
  3187. *
  3188. * @function
  3189. * @param {Node} aNode - The first input.
  3190. * @param {Node} bNode - The second input.
  3191. * @returns {OperatorNode}
  3192. */
  3193. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3194. /**
  3195. * Performs logical AND on two nodes.
  3196. *
  3197. * @function
  3198. * @param {Node} aNode - The first input.
  3199. * @param {Node} bNode - The second input.
  3200. * @returns {OperatorNode}
  3201. */
  3202. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3203. /**
  3204. * Performs logical OR on two nodes.
  3205. *
  3206. * @function
  3207. * @param {Node} aNode - The first input.
  3208. * @param {Node} bNode - The second input.
  3209. * @returns {OperatorNode}
  3210. */
  3211. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3212. /**
  3213. * Performs logical NOT on a node.
  3214. *
  3215. * @function
  3216. * @param {Node} aNode - The first input.
  3217. * @param {Node} bNode - The second input.
  3218. * @returns {OperatorNode}
  3219. */
  3220. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3221. /**
  3222. * Performs logical XOR on two nodes.
  3223. *
  3224. * @function
  3225. * @param {Node} aNode - The first input.
  3226. * @param {Node} bNode - The second input.
  3227. * @returns {OperatorNode}
  3228. */
  3229. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3230. /**
  3231. * Performs bitwise AND on two nodes.
  3232. *
  3233. * @function
  3234. * @param {Node} aNode - The first input.
  3235. * @param {Node} bNode - The second input.
  3236. * @returns {OperatorNode}
  3237. */
  3238. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3239. /**
  3240. * Performs bitwise NOT on a node.
  3241. *
  3242. * @function
  3243. * @param {Node} aNode - The first input.
  3244. * @param {Node} bNode - The second input.
  3245. * @returns {OperatorNode}
  3246. */
  3247. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3248. /**
  3249. * Performs bitwise OR on two nodes.
  3250. *
  3251. * @function
  3252. * @param {Node} aNode - The first input.
  3253. * @param {Node} bNode - The second input.
  3254. * @returns {OperatorNode}
  3255. */
  3256. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3257. /**
  3258. * Performs bitwise XOR on two nodes.
  3259. *
  3260. * @function
  3261. * @param {Node} aNode - The first input.
  3262. * @param {Node} bNode - The second input.
  3263. * @returns {OperatorNode}
  3264. */
  3265. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3266. /**
  3267. * Shifts a node to the left.
  3268. *
  3269. * @function
  3270. * @param {Node} aNode - The node to shift.
  3271. * @param {Node} bNode - The value to shift.
  3272. * @returns {OperatorNode}
  3273. */
  3274. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3275. /**
  3276. * Shifts a node to the right.
  3277. *
  3278. * @function
  3279. * @param {Node} aNode - The node to shift.
  3280. * @param {Node} bNode - The value to shift.
  3281. * @returns {OperatorNode}
  3282. */
  3283. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3284. addMethodChaining( 'add', add );
  3285. addMethodChaining( 'sub', sub );
  3286. addMethodChaining( 'mul', mul );
  3287. addMethodChaining( 'div', div );
  3288. addMethodChaining( 'modInt', modInt );
  3289. addMethodChaining( 'equal', equal );
  3290. addMethodChaining( 'notEqual', notEqual );
  3291. addMethodChaining( 'lessThan', lessThan );
  3292. addMethodChaining( 'greaterThan', greaterThan );
  3293. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3294. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3295. addMethodChaining( 'and', and );
  3296. addMethodChaining( 'or', or );
  3297. addMethodChaining( 'not', not );
  3298. addMethodChaining( 'xor', xor );
  3299. addMethodChaining( 'bitAnd', bitAnd );
  3300. addMethodChaining( 'bitNot', bitNot );
  3301. addMethodChaining( 'bitOr', bitOr );
  3302. addMethodChaining( 'bitXor', bitXor );
  3303. addMethodChaining( 'shiftLeft', shiftLeft );
  3304. addMethodChaining( 'shiftRight', shiftRight );
  3305. const remainder = ( ...params ) => { // @deprecated, r168
  3306. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3307. return modInt( ...params );
  3308. };
  3309. addMethodChaining( 'remainder', remainder );
  3310. /** @module MathNode **/
  3311. /**
  3312. * This node represents a variety of mathematical methods available in shaders.
  3313. * They are divided into three categories:
  3314. *
  3315. * - Methods with one input like `sin`, `cos` or `normalize`.
  3316. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3317. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3318. *
  3319. * @augments TempNode
  3320. */
  3321. class MathNode extends TempNode {
  3322. static get type() {
  3323. return 'MathNode';
  3324. }
  3325. /**
  3326. * Constructs a new math node.
  3327. *
  3328. * @param {String} method - The method name.
  3329. * @param {Node} aNode - The first input.
  3330. * @param {Node?} [bNode=null] - The second input.
  3331. * @param {Node?} [cNode=null] - The third input.
  3332. */
  3333. constructor( method, aNode, bNode = null, cNode = null ) {
  3334. super();
  3335. /**
  3336. * The method name.
  3337. *
  3338. * @type {String}
  3339. */
  3340. this.method = method;
  3341. /**
  3342. * The first input.
  3343. *
  3344. * @type {Node}
  3345. */
  3346. this.aNode = aNode;
  3347. /**
  3348. * The second input.
  3349. *
  3350. * @type {Node?}
  3351. * @default null
  3352. */
  3353. this.bNode = bNode;
  3354. /**
  3355. * The third input.
  3356. *
  3357. * @type {Node?}
  3358. * @default null
  3359. */
  3360. this.cNode = cNode;
  3361. }
  3362. /**
  3363. * The input type is inferred from the node types of the input nodes.
  3364. *
  3365. * @param {NodeBuilder} builder - The current node builder.
  3366. * @return {String} The input type.
  3367. */
  3368. getInputType( builder ) {
  3369. const aType = this.aNode.getNodeType( builder );
  3370. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3371. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3372. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3373. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3374. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3375. if ( aLen > bLen && aLen > cLen ) {
  3376. return aType;
  3377. } else if ( bLen > cLen ) {
  3378. return bType;
  3379. } else if ( cLen > aLen ) {
  3380. return cType;
  3381. }
  3382. return aType;
  3383. }
  3384. /**
  3385. * The selected method as well as the input type determine the node type of this node.
  3386. *
  3387. * @param {NodeBuilder} builder - The current node builder.
  3388. * @return {String} The node type.
  3389. */
  3390. getNodeType( builder ) {
  3391. const method = this.method;
  3392. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3393. return 'float';
  3394. } else if ( method === MathNode.CROSS ) {
  3395. return 'vec3';
  3396. } else if ( method === MathNode.ALL ) {
  3397. return 'bool';
  3398. } else if ( method === MathNode.EQUALS ) {
  3399. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3400. } else if ( method === MathNode.MOD ) {
  3401. return this.aNode.getNodeType( builder );
  3402. } else {
  3403. return this.getInputType( builder );
  3404. }
  3405. }
  3406. generate( builder, output ) {
  3407. let method = this.method;
  3408. const type = this.getNodeType( builder );
  3409. const inputType = this.getInputType( builder );
  3410. const a = this.aNode;
  3411. const b = this.bNode;
  3412. const c = this.cNode;
  3413. const coordinateSystem = builder.renderer.coordinateSystem;
  3414. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3415. // dir can be either a direction vector or a normal vector
  3416. // upper-left 3x3 of matrix is assumed to be orthogonal
  3417. let tA = a;
  3418. let tB = b;
  3419. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3420. tB = vec4( vec3( tB ), 0.0 );
  3421. } else {
  3422. tA = vec4( vec3( tA ), 0.0 );
  3423. }
  3424. const mulNode = mul( tA, tB ).xyz;
  3425. return normalize( mulNode ).build( builder, output );
  3426. } else if ( method === MathNode.NEGATE ) {
  3427. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3428. } else if ( method === MathNode.ONE_MINUS ) {
  3429. return sub( 1.0, a ).build( builder, output );
  3430. } else if ( method === MathNode.RECIPROCAL ) {
  3431. return div( 1.0, a ).build( builder, output );
  3432. } else if ( method === MathNode.DIFFERENCE ) {
  3433. return abs( sub( a, b ) ).build( builder, output );
  3434. } else {
  3435. const params = [];
  3436. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3437. params.push(
  3438. a.build( builder, type ),
  3439. b.build( builder, type )
  3440. );
  3441. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3442. params.push(
  3443. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3444. b.build( builder, inputType )
  3445. );
  3446. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3447. params.push(
  3448. a.build( builder, inputType ),
  3449. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3450. );
  3451. } else if ( method === MathNode.REFRACT ) {
  3452. params.push(
  3453. a.build( builder, inputType ),
  3454. b.build( builder, inputType ),
  3455. c.build( builder, 'float' )
  3456. );
  3457. } else if ( method === MathNode.MIX ) {
  3458. params.push(
  3459. a.build( builder, inputType ),
  3460. b.build( builder, inputType ),
  3461. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3462. );
  3463. } else {
  3464. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3465. method = 'atan2';
  3466. }
  3467. params.push( a.build( builder, inputType ) );
  3468. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3469. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3470. }
  3471. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3472. }
  3473. }
  3474. serialize( data ) {
  3475. super.serialize( data );
  3476. data.method = this.method;
  3477. }
  3478. deserialize( data ) {
  3479. super.deserialize( data );
  3480. this.method = data.method;
  3481. }
  3482. }
  3483. // 1 input
  3484. MathNode.ALL = 'all';
  3485. MathNode.ANY = 'any';
  3486. MathNode.RADIANS = 'radians';
  3487. MathNode.DEGREES = 'degrees';
  3488. MathNode.EXP = 'exp';
  3489. MathNode.EXP2 = 'exp2';
  3490. MathNode.LOG = 'log';
  3491. MathNode.LOG2 = 'log2';
  3492. MathNode.SQRT = 'sqrt';
  3493. MathNode.INVERSE_SQRT = 'inversesqrt';
  3494. MathNode.FLOOR = 'floor';
  3495. MathNode.CEIL = 'ceil';
  3496. MathNode.NORMALIZE = 'normalize';
  3497. MathNode.FRACT = 'fract';
  3498. MathNode.SIN = 'sin';
  3499. MathNode.COS = 'cos';
  3500. MathNode.TAN = 'tan';
  3501. MathNode.ASIN = 'asin';
  3502. MathNode.ACOS = 'acos';
  3503. MathNode.ATAN = 'atan';
  3504. MathNode.ABS = 'abs';
  3505. MathNode.SIGN = 'sign';
  3506. MathNode.LENGTH = 'length';
  3507. MathNode.NEGATE = 'negate';
  3508. MathNode.ONE_MINUS = 'oneMinus';
  3509. MathNode.DFDX = 'dFdx';
  3510. MathNode.DFDY = 'dFdy';
  3511. MathNode.ROUND = 'round';
  3512. MathNode.RECIPROCAL = 'reciprocal';
  3513. MathNode.TRUNC = 'trunc';
  3514. MathNode.FWIDTH = 'fwidth';
  3515. MathNode.TRANSPOSE = 'transpose';
  3516. // 2 inputs
  3517. MathNode.BITCAST = 'bitcast';
  3518. MathNode.EQUALS = 'equals';
  3519. MathNode.MIN = 'min';
  3520. MathNode.MAX = 'max';
  3521. MathNode.MOD = 'mod';
  3522. MathNode.STEP = 'step';
  3523. MathNode.REFLECT = 'reflect';
  3524. MathNode.DISTANCE = 'distance';
  3525. MathNode.DIFFERENCE = 'difference';
  3526. MathNode.DOT = 'dot';
  3527. MathNode.CROSS = 'cross';
  3528. MathNode.POW = 'pow';
  3529. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3530. // 3 inputs
  3531. MathNode.MIX = 'mix';
  3532. MathNode.CLAMP = 'clamp';
  3533. MathNode.REFRACT = 'refract';
  3534. MathNode.SMOOTHSTEP = 'smoothstep';
  3535. MathNode.FACEFORWARD = 'faceforward';
  3536. // 1 inputs
  3537. /**
  3538. * A small value used to handle floating-point precision errors.
  3539. *
  3540. * @type {Node<float>}
  3541. */
  3542. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3543. /**
  3544. * Represents infinity.
  3545. *
  3546. * @type {Node<float>}
  3547. */
  3548. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3549. /**
  3550. * Represents PI.
  3551. *
  3552. * @type {Node<float>}
  3553. */
  3554. const PI = /*@__PURE__*/ float( Math.PI );
  3555. /**
  3556. * Represents PI * 2.
  3557. *
  3558. * @type {Node<float>}
  3559. */
  3560. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3561. /**
  3562. * Returns `true` if all components of `x` are `true`.
  3563. *
  3564. * @function
  3565. * @param {Node | Number} x - The parameter.
  3566. * @returns {Node<bool>}
  3567. */
  3568. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3569. /**
  3570. * Returns `true` if any components of `x` are `true`.
  3571. *
  3572. * @function
  3573. * @param {Node | Number} x - The parameter.
  3574. * @returns {Node<bool>}
  3575. */
  3576. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3577. /**
  3578. * Converts a quantity in degrees to radians.
  3579. *
  3580. * @function
  3581. * @param {Node | Number} x - The input in degrees.
  3582. * @returns {Node}
  3583. */
  3584. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3585. /**
  3586. * Convert a quantity in radians to degrees.
  3587. *
  3588. * @function
  3589. * @param {Node | Number} x - The input in radians.
  3590. * @returns {Node}
  3591. */
  3592. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3593. /**
  3594. * Returns the natural exponentiation of the parameter.
  3595. *
  3596. * @function
  3597. * @param {Node | Number} x - The parameter.
  3598. * @returns {Node}
  3599. */
  3600. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3601. /**
  3602. * Returns 2 raised to the power of the parameter.
  3603. *
  3604. * @function
  3605. * @param {Node | Number} x - The parameter.
  3606. * @returns {Node}
  3607. */
  3608. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3609. /**
  3610. * Returns the natural logarithm of the parameter.
  3611. *
  3612. * @function
  3613. * @param {Node | Number} x - The parameter.
  3614. * @returns {Node}
  3615. */
  3616. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3617. /**
  3618. * Returns the base 2 logarithm of the parameter.
  3619. *
  3620. * @function
  3621. * @param {Node | Number} x - The parameter.
  3622. * @returns {Node}
  3623. */
  3624. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3625. /**
  3626. * Returns the square root of the parameter.
  3627. *
  3628. * @function
  3629. * @param {Node | Number} x - The parameter.
  3630. * @returns {Node}
  3631. */
  3632. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3633. /**
  3634. * Returns the inverse of the square root of the parameter.
  3635. *
  3636. * @function
  3637. * @param {Node | Number} x - The parameter.
  3638. * @returns {Node}
  3639. */
  3640. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3641. /**
  3642. * Finds the nearest integer less than or equal to the parameter.
  3643. *
  3644. * @function
  3645. * @param {Node | Number} x - The parameter.
  3646. * @returns {Node}
  3647. */
  3648. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3649. /**
  3650. * Finds the nearest integer that is greater than or equal to the parameter.
  3651. *
  3652. * @function
  3653. * @param {Node | Number} x - The parameter.
  3654. * @returns {Node}
  3655. */
  3656. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3657. /**
  3658. * Calculates the unit vector in the same direction as the original vector.
  3659. *
  3660. * @function
  3661. * @param {Node} x - The input vector.
  3662. * @returns {Node}
  3663. */
  3664. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3665. /**
  3666. * Computes the fractional part of the parameter.
  3667. *
  3668. * @function
  3669. * @param {Node | Number} x - The parameter.
  3670. * @returns {Node}
  3671. */
  3672. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3673. /**
  3674. * Returns the sine of the parameter.
  3675. *
  3676. * @function
  3677. * @param {Node | Number} x - The parameter.
  3678. * @returns {Node}
  3679. */
  3680. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3681. /**
  3682. * Returns the cosine of the parameter.
  3683. *
  3684. * @function
  3685. * @param {Node | Number} x - The parameter.
  3686. * @returns {Node}
  3687. */
  3688. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3689. /**
  3690. * Returns the tangent of the parameter.
  3691. *
  3692. * @function
  3693. * @param {Node | Number} x - The parameter.
  3694. * @returns {Node}
  3695. */
  3696. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3697. /**
  3698. * Returns the arcsine of the parameter.
  3699. *
  3700. * @function
  3701. * @param {Node | Number} x - The parameter.
  3702. * @returns {Node}
  3703. */
  3704. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3705. /**
  3706. * Returns the arccosine of the parameter.
  3707. *
  3708. * @function
  3709. * @param {Node | Number} x - The parameter.
  3710. * @returns {Node}
  3711. */
  3712. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3713. /**
  3714. * Returns the arc-tangent of the parameter.
  3715. *
  3716. * @function
  3717. * @param {Node | Number} x - The parameter.
  3718. * @returns {Node}
  3719. */
  3720. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3721. /**
  3722. * Returns the absolute value of the parameter.
  3723. *
  3724. * @function
  3725. * @param {Node | Number} x - The parameter.
  3726. * @returns {Node}
  3727. */
  3728. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3729. /**
  3730. * Extracts the sign of the parameter.
  3731. *
  3732. * @function
  3733. * @param {Node | Number} x - The parameter.
  3734. * @returns {Node}
  3735. */
  3736. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3737. /**
  3738. * Calculates the length of a vector.
  3739. *
  3740. * @function
  3741. * @param {Node} x - The parameter.
  3742. * @returns {Node<float>}
  3743. */
  3744. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3745. /**
  3746. * Negates the value of the parameter (-x).
  3747. *
  3748. * @function
  3749. * @param {Node | Number} x - The parameter.
  3750. * @returns {Node}
  3751. */
  3752. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3753. /**
  3754. * Return `1` minus the parameter.
  3755. *
  3756. * @function
  3757. * @param {Node | Number} x - The parameter.
  3758. * @returns {Node}
  3759. */
  3760. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3761. /**
  3762. * Returns the partial derivative of the parameter with respect to x.
  3763. *
  3764. * @function
  3765. * @param {Node | Number} x - The parameter.
  3766. * @returns {Node}
  3767. */
  3768. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3769. /**
  3770. * Returns the partial derivative of the parameter with respect to y.
  3771. *
  3772. * @function
  3773. * @param {Node | Number} x - The parameter.
  3774. * @returns {Node}
  3775. */
  3776. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3777. /**
  3778. * Rounds the parameter to the nearest integer.
  3779. *
  3780. * @function
  3781. * @param {Node | Number} x - The parameter.
  3782. * @returns {Node}
  3783. */
  3784. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3785. /**
  3786. * Returns the reciprocal of the parameter `(1/x)`.
  3787. *
  3788. * @function
  3789. * @param {Node | Number} x - The parameter.
  3790. * @returns {Node}
  3791. */
  3792. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3793. /**
  3794. * Truncates the parameter, removing the fractional part.
  3795. *
  3796. * @function
  3797. * @param {Node | Number} x - The parameter.
  3798. * @returns {Node}
  3799. */
  3800. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3801. /**
  3802. * Returns the sum of the absolute derivatives in x and y.
  3803. *
  3804. * @function
  3805. * @param {Node | Number} x - The parameter.
  3806. * @returns {Node}
  3807. */
  3808. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3809. /**
  3810. * Returns the transpose of a matrix.
  3811. *
  3812. * @function
  3813. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3814. * @returns {Node}
  3815. */
  3816. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3817. // 2 inputs
  3818. /**
  3819. * Reinterpret the bit representation of a value in one type as a value in another type.
  3820. *
  3821. * @function
  3822. * @param {Node | Number} x - The parameter.
  3823. * @param {String} y - The new type.
  3824. * @returns {Node}
  3825. */
  3826. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3827. /**
  3828. * Returns `true` if `x` equals `y`.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The first parameter.
  3832. * @param {Node | Number} y - The second parameter.
  3833. * @returns {Node<bool>}
  3834. */
  3835. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3836. /**
  3837. * Returns the lesser of two values.
  3838. *
  3839. * @function
  3840. * @param {Node | Number} x - The y parameter.
  3841. * @param {Node | Number} y - The x parameter.
  3842. * @returns {Node}
  3843. */
  3844. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3845. /**
  3846. * Returns the greater of two values.
  3847. *
  3848. * @function
  3849. * @param {Node | Number} x - The y parameter.
  3850. * @param {Node | Number} y - The x parameter.
  3851. * @returns {Node}
  3852. */
  3853. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3854. /**
  3855. * Computes the remainder of dividing the first node by the second one.
  3856. *
  3857. * @function
  3858. * @param {Node | Number} x - The y parameter.
  3859. * @param {Node | Number} y - The x parameter.
  3860. * @returns {Node}
  3861. */
  3862. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3863. /**
  3864. * Generate a step function by comparing two values.
  3865. *
  3866. * @function
  3867. * @param {Node | Number} x - The y parameter.
  3868. * @param {Node | Number} y - The x parameter.
  3869. * @returns {Node}
  3870. */
  3871. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3872. /**
  3873. * Calculates the reflection direction for an incident vector.
  3874. *
  3875. * @function
  3876. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3877. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3878. * @returns {Node<vec2|vec3|vec4>}
  3879. */
  3880. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3881. /**
  3882. * Calculates the distance between two points.
  3883. *
  3884. * @function
  3885. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3886. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3887. * @returns {Node<float>}
  3888. */
  3889. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3890. /**
  3891. * Calculates the absolute difference between two values.
  3892. *
  3893. * @function
  3894. * @param {Node | Number} x - The first parameter.
  3895. * @param {Node | Number} y - The second parameter.
  3896. * @returns {Node}
  3897. */
  3898. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3899. /**
  3900. * Calculates the dot product of two vectors.
  3901. *
  3902. * @function
  3903. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3904. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3905. * @returns {Node<float>}
  3906. */
  3907. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3908. /**
  3909. * Calculates the cross product of two vectors.
  3910. *
  3911. * @function
  3912. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3913. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3914. * @returns {Node<vec2|vec3|vec4>}
  3915. */
  3916. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3917. /**
  3918. * Return the value of the first parameter raised to the power of the second one.
  3919. *
  3920. * @function
  3921. * @param {Node | Number} x - The first parameter.
  3922. * @param {Node | Number} y - The second parameter.
  3923. * @returns {Node}
  3924. */
  3925. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3926. /**
  3927. * Returns the square of the parameter.
  3928. *
  3929. * @function
  3930. * @param {Node | Number} x - The first parameter.
  3931. * @returns {Node}
  3932. */
  3933. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3934. /**
  3935. * Returns the cube of the parameter.
  3936. *
  3937. * @function
  3938. * @param {Node | Number} x - The first parameter.
  3939. * @returns {Node}
  3940. */
  3941. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3942. /**
  3943. * Returns the fourth power of the parameter.
  3944. *
  3945. * @function
  3946. * @param {Node | Number} x - The first parameter.
  3947. * @returns {Node}
  3948. */
  3949. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3950. /**
  3951. * Transforms the direction of a vector by a matrix and then normalizes the result.
  3952. *
  3953. * @function
  3954. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  3955. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  3956. * @returns {Node}
  3957. */
  3958. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3959. /**
  3960. * Returns the cube root of a number.
  3961. *
  3962. * @function
  3963. * @param {Node | Number} a - The first parameter.
  3964. * @returns {Node}
  3965. */
  3966. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  3967. /**
  3968. * Calculate the squared length of a vector.
  3969. *
  3970. * @function
  3971. * @param {Node<vec2|vec3|vec4>} a - The vector.
  3972. * @returns {Node<float>}
  3973. */
  3974. const lengthSq = ( a ) => dot( a, a );
  3975. /**
  3976. * Linearly interpolates between two values.
  3977. *
  3978. * @function
  3979. * @param {Node | Number} a - The first parameter.
  3980. * @param {Node | Number} b - The second parameter.
  3981. * @param {Node | Number} t - The interpolation value.
  3982. * @returns {Node}
  3983. */
  3984. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  3985. /**
  3986. * Constrains a value to lie between two further values.
  3987. *
  3988. * @function
  3989. * @param {Node | Number} value - The value to constrain.
  3990. * @param {Node | Number} [low=0] - The lower bound.
  3991. * @param {Node | Number} [high=1] - The upper bound.
  3992. * @returns {Node}
  3993. */
  3994. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  3995. /**
  3996. * Constrains a value between `0` and `1`.
  3997. *
  3998. * @function
  3999. * @param {Node | Number} value - The value to constrain.
  4000. * @returns {Node}
  4001. */
  4002. const saturate = ( value ) => clamp( value );
  4003. /**
  4004. * Calculates the refraction direction for an incident vector.
  4005. *
  4006. * @function
  4007. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4008. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4009. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4010. * @returns {Node<vec2|vec3|vec4>}
  4011. */
  4012. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4013. /**
  4014. * Performs a Hermite interpolation between two values.
  4015. *
  4016. * @function
  4017. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4018. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4019. * @param {Node | Number} x - The source value for interpolation.
  4020. * @returns {Node}
  4021. */
  4022. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4023. /**
  4024. * Returns a vector pointing in the same direction as another.
  4025. *
  4026. * @function
  4027. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4028. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4029. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4030. * @returns {Node<vec2|vec3|vec4>}
  4031. */
  4032. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4033. /**
  4034. * Returns a random value for the given uv.
  4035. *
  4036. * @function
  4037. * @param {Node<vec2>} uv - The uv node.
  4038. * @returns {Node<float>}
  4039. */
  4040. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4041. const a = 12.9898, b = 78.233, c = 43758.5453;
  4042. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4043. return fract( sin( sn ).mul( c ) );
  4044. } );
  4045. /**
  4046. * Alias for `mix()` with a different parameter order.
  4047. *
  4048. * @function
  4049. * @param {Node | Number} t - The interpolation value.
  4050. * @param {Node | Number} e1 - The first parameter.
  4051. * @param {Node | Number} e2 - The second parameter.
  4052. * @returns {Node}
  4053. */
  4054. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4055. /**
  4056. * Alias for `smoothstep()` with a different parameter order.
  4057. *
  4058. * @function
  4059. * @param {Node | Number} x - The source value for interpolation.
  4060. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4061. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4062. * @returns {Node}
  4063. */
  4064. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4065. /**
  4066. * Returns the arc-tangent of the quotient of its parameters.
  4067. *
  4068. * @function
  4069. * @param {Node | Number} y - The y parameter.
  4070. * @param {Node | Number} x - The x parameter.
  4071. * @returns {Node}
  4072. */
  4073. const atan2 = ( y, x ) => { // @deprecated, r172
  4074. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4075. return atan( y, x );
  4076. };
  4077. // GLSL alias function
  4078. const faceforward = faceForward;
  4079. const inversesqrt = inverseSqrt;
  4080. // Method chaining
  4081. addMethodChaining( 'all', all );
  4082. addMethodChaining( 'any', any );
  4083. addMethodChaining( 'equals', equals );
  4084. addMethodChaining( 'radians', radians );
  4085. addMethodChaining( 'degrees', degrees );
  4086. addMethodChaining( 'exp', exp );
  4087. addMethodChaining( 'exp2', exp2 );
  4088. addMethodChaining( 'log', log );
  4089. addMethodChaining( 'log2', log2 );
  4090. addMethodChaining( 'sqrt', sqrt );
  4091. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4092. addMethodChaining( 'floor', floor );
  4093. addMethodChaining( 'ceil', ceil );
  4094. addMethodChaining( 'normalize', normalize );
  4095. addMethodChaining( 'fract', fract );
  4096. addMethodChaining( 'sin', sin );
  4097. addMethodChaining( 'cos', cos );
  4098. addMethodChaining( 'tan', tan );
  4099. addMethodChaining( 'asin', asin );
  4100. addMethodChaining( 'acos', acos );
  4101. addMethodChaining( 'atan', atan );
  4102. addMethodChaining( 'abs', abs );
  4103. addMethodChaining( 'sign', sign );
  4104. addMethodChaining( 'length', length );
  4105. addMethodChaining( 'lengthSq', lengthSq );
  4106. addMethodChaining( 'negate', negate );
  4107. addMethodChaining( 'oneMinus', oneMinus );
  4108. addMethodChaining( 'dFdx', dFdx );
  4109. addMethodChaining( 'dFdy', dFdy );
  4110. addMethodChaining( 'round', round );
  4111. addMethodChaining( 'reciprocal', reciprocal );
  4112. addMethodChaining( 'trunc', trunc );
  4113. addMethodChaining( 'fwidth', fwidth );
  4114. addMethodChaining( 'atan2', atan2 );
  4115. addMethodChaining( 'min', min$1 );
  4116. addMethodChaining( 'max', max$1 );
  4117. addMethodChaining( 'mod', mod );
  4118. addMethodChaining( 'step', step );
  4119. addMethodChaining( 'reflect', reflect );
  4120. addMethodChaining( 'distance', distance );
  4121. addMethodChaining( 'dot', dot );
  4122. addMethodChaining( 'cross', cross );
  4123. addMethodChaining( 'pow', pow );
  4124. addMethodChaining( 'pow2', pow2 );
  4125. addMethodChaining( 'pow3', pow3 );
  4126. addMethodChaining( 'pow4', pow4 );
  4127. addMethodChaining( 'transformDirection', transformDirection );
  4128. addMethodChaining( 'mix', mixElement );
  4129. addMethodChaining( 'clamp', clamp );
  4130. addMethodChaining( 'refract', refract );
  4131. addMethodChaining( 'smoothstep', smoothstepElement );
  4132. addMethodChaining( 'faceForward', faceForward );
  4133. addMethodChaining( 'difference', difference );
  4134. addMethodChaining( 'saturate', saturate );
  4135. addMethodChaining( 'cbrt', cbrt );
  4136. addMethodChaining( 'transpose', transpose );
  4137. addMethodChaining( 'rand', rand );
  4138. /** @module ConditionalNode **/
  4139. /**
  4140. * Represents a logical `if/else` statement. Can be used as an alternative
  4141. * to the `If()`/`Else()` syntax.
  4142. *
  4143. * The corresponding TSL `select()` looks like so:
  4144. * ```js
  4145. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4146. * ```
  4147. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4148. * determine the outcome of the entire statement.
  4149. *
  4150. * @augments Node
  4151. */
  4152. class ConditionalNode extends Node {
  4153. static get type() {
  4154. return 'ConditionalNode';
  4155. }
  4156. /**
  4157. * Constructs a new conditional node.
  4158. *
  4159. * @param {Node} condNode - The node that defines the condition.
  4160. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4161. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4162. */
  4163. constructor( condNode, ifNode, elseNode = null ) {
  4164. super();
  4165. /**
  4166. * The node that defines the condition.
  4167. *
  4168. * @type {Node}
  4169. */
  4170. this.condNode = condNode;
  4171. /**
  4172. * The node that is evaluate when the condition ends up `true`.
  4173. *
  4174. * @type {Node}
  4175. */
  4176. this.ifNode = ifNode;
  4177. /**
  4178. * The node that is evaluate when the condition ends up `false`.
  4179. *
  4180. * @type {Node?}
  4181. * @default null
  4182. */
  4183. this.elseNode = elseNode;
  4184. }
  4185. /**
  4186. * This method is overwritten since the node type is inferred from the if/else
  4187. * nodes.
  4188. *
  4189. * @param {NodeBuilder} builder - The current node builder.
  4190. * @return {String} The node type.
  4191. */
  4192. getNodeType( builder ) {
  4193. const ifType = this.ifNode.getNodeType( builder );
  4194. if ( this.elseNode !== null ) {
  4195. const elseType = this.elseNode.getNodeType( builder );
  4196. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4197. return elseType;
  4198. }
  4199. }
  4200. return ifType;
  4201. }
  4202. setup( builder ) {
  4203. const condNode = this.condNode.cache();
  4204. const ifNode = this.ifNode.cache();
  4205. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4206. //
  4207. const currentNodeBlock = builder.context.nodeBlock;
  4208. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4209. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4210. //
  4211. const properties = builder.getNodeProperties( this );
  4212. properties.condNode = condNode;
  4213. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4214. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4215. }
  4216. generate( builder, output ) {
  4217. const type = this.getNodeType( builder );
  4218. const nodeData = builder.getDataFromNode( this );
  4219. if ( nodeData.nodeProperty !== undefined ) {
  4220. return nodeData.nodeProperty;
  4221. }
  4222. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4223. const needsOutput = output !== 'void';
  4224. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4225. nodeData.nodeProperty = nodeProperty;
  4226. const nodeSnippet = condNode.build( builder, 'bool' );
  4227. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4228. let ifSnippet = ifNode.build( builder, type );
  4229. if ( ifSnippet ) {
  4230. if ( needsOutput ) {
  4231. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4232. } else {
  4233. ifSnippet = 'return ' + ifSnippet + ';';
  4234. }
  4235. }
  4236. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4237. if ( elseNode !== null ) {
  4238. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4239. let elseSnippet = elseNode.build( builder, type );
  4240. if ( elseSnippet ) {
  4241. if ( needsOutput ) {
  4242. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4243. } else {
  4244. elseSnippet = 'return ' + elseSnippet + ';';
  4245. }
  4246. }
  4247. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4248. } else {
  4249. builder.addFlowCode( '\n\n' );
  4250. }
  4251. return builder.format( nodeProperty, type, output );
  4252. }
  4253. }
  4254. /**
  4255. * TSL function for creating a conditional node.
  4256. *
  4257. * @function
  4258. * @param {Node} condNode - The node that defines the condition.
  4259. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4260. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4261. * @returns {ConditionalNode}
  4262. */
  4263. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4264. addMethodChaining( 'select', select );
  4265. //
  4266. const cond = ( ...params ) => { // @deprecated, r168
  4267. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4268. return select( ...params );
  4269. };
  4270. addMethodChaining( 'cond', cond );
  4271. /** @module ContextNode **/
  4272. /**
  4273. * This node can be used as a context management component for another node.
  4274. * {@link NodeBuilder} performs its node building process in a specific context and
  4275. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4276. *
  4277. * ```js
  4278. *node.context( { getUV: () => customCoord } );
  4279. *```
  4280. * @augments Node
  4281. */
  4282. class ContextNode extends Node {
  4283. static get type() {
  4284. return 'ContextNode';
  4285. }
  4286. /**
  4287. * Constructs a new context node.
  4288. *
  4289. * @param {Node} node - The node whose context should be modified.
  4290. * @param {Object} [value={}] - The modified context data.
  4291. */
  4292. constructor( node, value = {} ) {
  4293. super();
  4294. /**
  4295. * This flag can be used for type testing.
  4296. *
  4297. * @type {Boolean}
  4298. * @readonly
  4299. * @default true
  4300. */
  4301. this.isContextNode = true;
  4302. /**
  4303. * The node whose context should be modified.
  4304. *
  4305. * @type {Node}
  4306. */
  4307. this.node = node;
  4308. /**
  4309. * The modified context data.
  4310. *
  4311. * @type {Object}
  4312. * @default {}
  4313. */
  4314. this.value = value;
  4315. }
  4316. /**
  4317. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4318. *
  4319. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4320. */
  4321. getScope() {
  4322. return this.node.getScope();
  4323. }
  4324. /**
  4325. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4326. *
  4327. * @param {NodeBuilder} builder - The current node builder.
  4328. * @return {String} The node type.
  4329. */
  4330. getNodeType( builder ) {
  4331. return this.node.getNodeType( builder );
  4332. }
  4333. analyze( builder ) {
  4334. this.node.build( builder );
  4335. }
  4336. setup( builder ) {
  4337. const previousContext = builder.getContext();
  4338. builder.setContext( { ...builder.context, ...this.value } );
  4339. const node = this.node.build( builder );
  4340. builder.setContext( previousContext );
  4341. return node;
  4342. }
  4343. generate( builder, output ) {
  4344. const previousContext = builder.getContext();
  4345. builder.setContext( { ...builder.context, ...this.value } );
  4346. const snippet = this.node.build( builder, output );
  4347. builder.setContext( previousContext );
  4348. return snippet;
  4349. }
  4350. }
  4351. /**
  4352. * TSL function for creating a context node.
  4353. *
  4354. * @function
  4355. * @param {Node} node - The node whose context should be modified.
  4356. * @param {Object} [value={}] - The modified context data.
  4357. * @returns {ContextNode}
  4358. */
  4359. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4360. /**
  4361. * TSL function for defining a label context value for a given node.
  4362. *
  4363. * @function
  4364. * @param {Node} node - The node whose context should be modified.
  4365. * @param {String} name - The name/label to set.
  4366. * @returns {ContextNode}
  4367. */
  4368. const label = ( node, name ) => context( node, { label: name } );
  4369. addMethodChaining( 'context', context );
  4370. addMethodChaining( 'label', label );
  4371. /** @module VarNode **/
  4372. /**
  4373. * Class for representing shader variables as nodes. Variables are created from
  4374. * existing nodes like the following:
  4375. *
  4376. * ```js
  4377. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4378. * ```
  4379. *
  4380. * @augments Node
  4381. */
  4382. class VarNode extends Node {
  4383. static get type() {
  4384. return 'VarNode';
  4385. }
  4386. /**
  4387. * Constructs a new variable node.
  4388. *
  4389. * @param {Node} node - The node for which a variable should be created.
  4390. * @param {String?} name - The name of the variable in the shader.
  4391. */
  4392. constructor( node, name = null ) {
  4393. super();
  4394. /**
  4395. * The node for which a variable should be created.
  4396. *
  4397. * @type {Node}
  4398. */
  4399. this.node = node;
  4400. /**
  4401. * The name of the variable in the shader. If no name is defined,
  4402. * the node system auto-generates one.
  4403. *
  4404. * @type {String?}
  4405. * @default null
  4406. */
  4407. this.name = name;
  4408. /**
  4409. * `VarNode` sets this property to `true` by default.
  4410. *
  4411. * @type {Boolean}
  4412. * @default true
  4413. */
  4414. this.global = true;
  4415. /**
  4416. * This flag can be used for type testing.
  4417. *
  4418. * @type {Boolean}
  4419. * @readonly
  4420. * @default true
  4421. */
  4422. this.isVarNode = true;
  4423. }
  4424. getHash( builder ) {
  4425. return this.name || super.getHash( builder );
  4426. }
  4427. getNodeType( builder ) {
  4428. return this.node.getNodeType( builder );
  4429. }
  4430. generate( builder ) {
  4431. const { node, name } = this;
  4432. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  4433. const propertyName = builder.getPropertyName( nodeVar );
  4434. const snippet = node.build( builder, nodeVar.type );
  4435. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4436. return propertyName;
  4437. }
  4438. }
  4439. /**
  4440. * TSL function for creating a var node.
  4441. *
  4442. * @function
  4443. * @param {Node} node - The node for which a variable should be created.
  4444. * @param {String?} name - The name of the variable in the shader.
  4445. * @returns {VarNode}
  4446. */
  4447. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4448. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  4449. // Deprecated
  4450. const temp = ( node ) => { // @deprecated, r170
  4451. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  4452. return createVar( node );
  4453. };
  4454. addMethodChaining( 'temp', temp );
  4455. /** @module VaryingNode **/
  4456. /**
  4457. * Class for representing shader varyings as nodes. Varyings are create from
  4458. * existing nodes like the following:
  4459. *
  4460. * ```js
  4461. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  4462. * ```
  4463. *
  4464. * @augments Node
  4465. */
  4466. class VaryingNode extends Node {
  4467. static get type() {
  4468. return 'VaryingNode';
  4469. }
  4470. /**
  4471. * Constructs a new varying node.
  4472. *
  4473. * @param {Node} node - The node for which a varying should be created.
  4474. * @param {String?} name - The name of the varying in the shader.
  4475. */
  4476. constructor( node, name = null ) {
  4477. super();
  4478. /**
  4479. * The node for which a varying should be created.
  4480. *
  4481. * @type {Node}
  4482. */
  4483. this.node = node;
  4484. /**
  4485. * The name of the varying in the shader. If no name is defined,
  4486. * the node system auto-generates one.
  4487. *
  4488. * @type {String?}
  4489. * @default null
  4490. */
  4491. this.name = name;
  4492. /**
  4493. * This flag can be used for type testing.
  4494. *
  4495. * @type {Boolean}
  4496. * @readonly
  4497. * @default true
  4498. */
  4499. this.isVaryingNode = true;
  4500. }
  4501. /**
  4502. * The method is overwritten so it always returns `true`.
  4503. *
  4504. * @param {NodeBuilder} builder - The current node builder.
  4505. * @return {Boolean} Whether this node is global or not.
  4506. */
  4507. isGlobal( /*builder*/ ) {
  4508. return true;
  4509. }
  4510. getHash( builder ) {
  4511. return this.name || super.getHash( builder );
  4512. }
  4513. getNodeType( builder ) {
  4514. // VaryingNode is auto type
  4515. return this.node.getNodeType( builder );
  4516. }
  4517. /**
  4518. * This method performs the setup of a varying node with the current node builder.
  4519. *
  4520. * @param {NodeBuilder} builder - The current node builder.
  4521. * @return {NodeVarying} The node varying from the node builder.
  4522. */
  4523. setupVarying( builder ) {
  4524. const properties = builder.getNodeProperties( this );
  4525. let varying = properties.varying;
  4526. if ( varying === undefined ) {
  4527. const name = this.name;
  4528. const type = this.getNodeType( builder );
  4529. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4530. properties.node = this.node;
  4531. }
  4532. // this property can be used to check if the varying can be optimized for a variable
  4533. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4534. return varying;
  4535. }
  4536. setup( builder ) {
  4537. this.setupVarying( builder );
  4538. }
  4539. analyze( builder ) {
  4540. this.setupVarying( builder );
  4541. return this.node.analyze( builder );
  4542. }
  4543. generate( builder ) {
  4544. const properties = builder.getNodeProperties( this );
  4545. const varying = this.setupVarying( builder );
  4546. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4547. if ( properties.propertyName === undefined || needsReassign ) {
  4548. const type = this.getNodeType( builder );
  4549. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4550. // force node run in vertex stage
  4551. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4552. properties.propertyName = propertyName;
  4553. if ( needsReassign ) {
  4554. // once reassign varying in fragment stage
  4555. properties.reassignPosition = false;
  4556. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4557. properties.reassignPosition = true;
  4558. }
  4559. }
  4560. return builder.getPropertyName( varying );
  4561. }
  4562. }
  4563. /**
  4564. * TSL function for creating a varying node.
  4565. *
  4566. * @function
  4567. * @param {Node} node - The node for which a varying should be created.
  4568. * @param {String?} name - The name of the varying in the shader.
  4569. * @returns {VaryingNode}
  4570. */
  4571. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4572. /**
  4573. * Computes a node in the vertex stage.
  4574. *
  4575. * @function
  4576. * @param {Node} node - The node which should be executed in the vertex stage.
  4577. * @returns {VaryingNode}
  4578. */
  4579. const vertexStage = ( node ) => varying( node );
  4580. addMethodChaining( 'varying', varying );
  4581. addMethodChaining( 'vertexStage', vertexStage );
  4582. /** @module ColorSpaceFunctions **/
  4583. /**
  4584. * Converts the given color value from sRGB to linear-sRGB color space.
  4585. *
  4586. * @method
  4587. * @param {Node<vec3>} color - The sRGB color.
  4588. * @return {Node<vec3>} The linear-sRGB color.
  4589. */
  4590. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4591. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4592. const b = color.mul( 0.0773993808 );
  4593. const factor = color.lessThanEqual( 0.04045 );
  4594. const rgbResult = mix( a, b, factor );
  4595. return rgbResult;
  4596. } ).setLayout( {
  4597. name: 'sRGBTransferEOTF',
  4598. type: 'vec3',
  4599. inputs: [
  4600. { name: 'color', type: 'vec3' }
  4601. ]
  4602. } );
  4603. /**
  4604. * Converts the given color value from linear-sRGB to sRGB color space.
  4605. *
  4606. * @method
  4607. * @param {Node<vec3>} color - The linear-sRGB color.
  4608. * @return {Node<vec3>} The sRGB color.
  4609. */
  4610. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4611. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4612. const b = color.mul( 12.92 );
  4613. const factor = color.lessThanEqual( 0.0031308 );
  4614. const rgbResult = mix( a, b, factor );
  4615. return rgbResult;
  4616. } ).setLayout( {
  4617. name: 'sRGBTransferOETF',
  4618. type: 'vec3',
  4619. inputs: [
  4620. { name: 'color', type: 'vec3' }
  4621. ]
  4622. } );
  4623. /** @module ColorSpaceNode **/
  4624. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4625. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4626. /**
  4627. * This node represents a color space conversion. Meaning it converts
  4628. * a color value from a source to a target color space.
  4629. *
  4630. * @augments TempNode
  4631. */
  4632. class ColorSpaceNode extends TempNode {
  4633. static get type() {
  4634. return 'ColorSpaceNode';
  4635. }
  4636. /**
  4637. * Constructs a new color space node.
  4638. *
  4639. * @param {Node} colorNode - Represents the color to convert.
  4640. * @param {String} source - The source color space.
  4641. * @param {String} target - The target color space.
  4642. */
  4643. constructor( colorNode, source, target ) {
  4644. super( 'vec4' );
  4645. /**
  4646. * Represents the color to convert.
  4647. *
  4648. * @type {Node}
  4649. */
  4650. this.colorNode = colorNode;
  4651. /**
  4652. * The source color space.
  4653. *
  4654. * @type {String}
  4655. */
  4656. this.source = source;
  4657. /**
  4658. * The target color space.
  4659. *
  4660. * @type {String}
  4661. */
  4662. this.target = target;
  4663. }
  4664. /**
  4665. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4666. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4667. * color management and renderer.
  4668. *
  4669. * @param {NodeBuilder} builder - The current node builder.
  4670. * @param {String} colorSpace - The color space to resolve.
  4671. * @return {String} The resolved color space.
  4672. */
  4673. resolveColorSpace( builder, colorSpace ) {
  4674. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4675. return ColorManagement.workingColorSpace;
  4676. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4677. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4678. }
  4679. return colorSpace;
  4680. }
  4681. setup( builder ) {
  4682. const { colorNode } = this;
  4683. const source = this.resolveColorSpace( builder, this.source );
  4684. const target = this.resolveColorSpace( builder, this.target );
  4685. let outputNode = colorNode;
  4686. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4687. return outputNode;
  4688. }
  4689. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4690. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4691. }
  4692. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4693. outputNode = vec4(
  4694. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4695. outputNode.a
  4696. );
  4697. }
  4698. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4699. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4700. }
  4701. return outputNode;
  4702. }
  4703. }
  4704. /**
  4705. * TSL function for converting a given color node to the current output color space.
  4706. *
  4707. * @function
  4708. * @param {Node} node - Represents the node to convert.
  4709. * @returns {ColorSpaceNode}
  4710. */
  4711. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4712. /**
  4713. * TSL function for converting a given color node to the current working color space.
  4714. *
  4715. * @function
  4716. * @param {Node} node - Represents the node to convert.
  4717. * @returns {ColorSpaceNode}
  4718. */
  4719. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4720. /**
  4721. * TSL function for converting a given color node from the current working color space to the given color space.
  4722. *
  4723. * @function
  4724. * @param {Node} node - Represents the node to convert.
  4725. * @param {String} colorSpace - The target color space.
  4726. * @returns {ColorSpaceNode}
  4727. */
  4728. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4729. /**
  4730. * TSL function for converting a given color node from the given color space to the current working color space.
  4731. *
  4732. * @function
  4733. * @param {Node} node - Represents the node to convert.
  4734. * @param {String} colorSpace - The source color space.
  4735. * @returns {ColorSpaceNode}
  4736. */
  4737. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4738. /**
  4739. * TSL function for converting a given color node from one color space to another one.
  4740. *
  4741. * @function
  4742. * @param {Node} node - Represents the node to convert.
  4743. * @param {String} sourceColorSpace - The source color space.
  4744. * @param {String} targetColorSpace - The target color space.
  4745. * @returns {ColorSpaceNode}
  4746. */
  4747. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4748. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4749. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4750. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4751. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4752. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4753. /** @module ReferenceBaseNode **/
  4754. /**
  4755. * This class is only relevant if the referenced property is array-like.
  4756. * In this case, `ReferenceElementNode` allows to refer to a specific
  4757. * element inside the data structure via an index.
  4758. *
  4759. * @augments ArrayElementNode
  4760. */
  4761. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4762. static get type() {
  4763. return 'ReferenceElementNode';
  4764. }
  4765. /**
  4766. * Constructs a new reference element node.
  4767. *
  4768. * @param {Node?} referenceNode - The reference node.
  4769. * @param {Node} indexNode - The index node that defines the element access.
  4770. */
  4771. constructor( referenceNode, indexNode ) {
  4772. super( referenceNode, indexNode );
  4773. /**
  4774. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4775. * property references to the current node.
  4776. *
  4777. * @type {Node?}
  4778. * @default null
  4779. */
  4780. this.referenceNode = referenceNode;
  4781. /**
  4782. * This flag can be used for type testing.
  4783. *
  4784. * @type {Boolean}
  4785. * @readonly
  4786. * @default true
  4787. */
  4788. this.isReferenceElementNode = true;
  4789. }
  4790. /**
  4791. * This method is overwritten since the node type is inferred from
  4792. * the uniform type of the reference node.
  4793. *
  4794. * @param {NodeBuilder} builder - The current node builder.
  4795. * @return {String} The node type.
  4796. */
  4797. getNodeType() {
  4798. return this.referenceNode.uniformType;
  4799. }
  4800. generate( builder ) {
  4801. const snippet = super.generate( builder );
  4802. const arrayType = this.referenceNode.getNodeType();
  4803. const elementType = this.getNodeType();
  4804. return builder.format( snippet, arrayType, elementType );
  4805. }
  4806. };
  4807. /**
  4808. * Base class for nodes which establishes a reference to a property of another object.
  4809. * In this way, the value of the node is automatically linked to the value of
  4810. * referenced object. Reference nodes internally represent the linked value
  4811. * as a uniform.
  4812. *
  4813. * @augments Node
  4814. */
  4815. class ReferenceBaseNode extends Node {
  4816. static get type() {
  4817. return 'ReferenceBaseNode';
  4818. }
  4819. /**
  4820. * Constructs a new reference base node.
  4821. *
  4822. * @param {String} property - The name of the property the node refers to.
  4823. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4824. * @param {Object?} [object=null] - The object the property belongs to.
  4825. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4826. */
  4827. constructor( property, uniformType, object = null, count = null ) {
  4828. super();
  4829. /**
  4830. * The name of the property the node refers to.
  4831. *
  4832. * @type {String}
  4833. */
  4834. this.property = property;
  4835. /**
  4836. * The uniform type that should be used to represent the property value.
  4837. *
  4838. * @type {String}
  4839. */
  4840. this.uniformType = uniformType;
  4841. /**
  4842. * The object the property belongs to.
  4843. *
  4844. * @type {Object?}
  4845. * @default null
  4846. */
  4847. this.object = object;
  4848. /**
  4849. * When the linked property is an array, this parameter defines its length.
  4850. *
  4851. * @type {Number?}
  4852. * @default null
  4853. */
  4854. this.count = count;
  4855. /**
  4856. * The property name might have dots so nested properties can be referred.
  4857. * The hierarchy of the names is stored inside this array.
  4858. *
  4859. * @type {Array<String>}
  4860. */
  4861. this.properties = property.split( '.' );
  4862. /**
  4863. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  4864. * since the final reference might be updated from calling code.
  4865. *
  4866. * @type {Object?}
  4867. * @default null
  4868. */
  4869. this.reference = object;
  4870. /**
  4871. * The uniform node that holds the value of the reference node.
  4872. *
  4873. * @type {UniformNode}
  4874. * @default null
  4875. */
  4876. this.node = null;
  4877. /**
  4878. * The uniform group of the internal uniform.
  4879. *
  4880. * @type {UniformGroupNode}
  4881. * @default null
  4882. */
  4883. this.group = null;
  4884. /**
  4885. * Overwritten since reference nodes are updated per object.
  4886. *
  4887. * @type {String}
  4888. * @default 'object'
  4889. */
  4890. this.updateType = NodeUpdateType.OBJECT;
  4891. }
  4892. /**
  4893. * Sets the uniform group for this reference node.
  4894. *
  4895. * @param {UniformGroupNode} group - The uniform group to set.
  4896. * @return {ReferenceBaseNode} A reference to this node.
  4897. */
  4898. setGroup( group ) {
  4899. this.group = group;
  4900. return this;
  4901. }
  4902. /**
  4903. * When the referred property is array-like, this method can be used
  4904. * to access elements via an index node.
  4905. *
  4906. * @param {IndexNode} indexNode - indexNode.
  4907. * @return {ReferenceElementNode} A reference to an element.
  4908. */
  4909. element( indexNode ) {
  4910. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  4911. }
  4912. /**
  4913. * Sets the node type which automatically defines the internal
  4914. * uniform type.
  4915. *
  4916. * @param {String} uniformType - The type to set.
  4917. */
  4918. setNodeType( uniformType ) {
  4919. const node = uniform( null, uniformType ).getSelf();
  4920. if ( this.group !== null ) {
  4921. node.setGroup( this.group );
  4922. }
  4923. this.node = node;
  4924. }
  4925. /**
  4926. * This method is overwritten since the node type is inferred from
  4927. * the type of the reference node.
  4928. *
  4929. * @param {NodeBuilder} builder - The current node builder.
  4930. * @return {String} The node type.
  4931. */
  4932. getNodeType( builder ) {
  4933. if ( this.node === null ) {
  4934. this.updateReference( builder );
  4935. this.updateValue();
  4936. }
  4937. return this.node.getNodeType( builder );
  4938. }
  4939. /**
  4940. * Returns the property value from the given referred object.
  4941. *
  4942. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  4943. * @return {Any} The value.
  4944. */
  4945. getValueFromReference( object = this.reference ) {
  4946. const { properties } = this;
  4947. let value = object[ properties[ 0 ] ];
  4948. for ( let i = 1; i < properties.length; i ++ ) {
  4949. value = value[ properties[ i ] ];
  4950. }
  4951. return value;
  4952. }
  4953. /**
  4954. * Allows to update the reference based on the given state. The state is only
  4955. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  4956. *
  4957. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  4958. * @return {Object} The updated reference.
  4959. */
  4960. updateReference( state ) {
  4961. this.reference = this.object !== null ? this.object : state.object;
  4962. return this.reference;
  4963. }
  4964. /**
  4965. * The output of the reference node is the internal uniform node.
  4966. *
  4967. * @param {NodeBuilder} builder - The current node builder.
  4968. * @return {UniformNode} The output node.
  4969. */
  4970. setup() {
  4971. this.updateValue();
  4972. return this.node;
  4973. }
  4974. /**
  4975. * Overwritten to to update the internal uniform value.
  4976. *
  4977. * @param {NodeFrame} frame - A reference to the current node frame.
  4978. */
  4979. update( /*frame*/ ) {
  4980. this.updateValue();
  4981. }
  4982. /**
  4983. * Retrieves the value from the referred object property and uses it
  4984. * to updated the internal uniform.
  4985. */
  4986. updateValue() {
  4987. if ( this.node === null ) this.setNodeType( this.uniformType );
  4988. const value = this.getValueFromReference();
  4989. if ( Array.isArray( value ) ) {
  4990. this.node.array = value;
  4991. } else {
  4992. this.node.value = value;
  4993. }
  4994. }
  4995. }
  4996. /**
  4997. * TSL function for creating a reference base node.
  4998. *
  4999. * @function
  5000. * @param {String} name - The name of the property the node refers to.
  5001. * @param {String} type - The uniform type that should be used to represent the property value.
  5002. * @param {Object} object - The object the property belongs to.
  5003. * @returns {ReferenceBaseNode}
  5004. */
  5005. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5006. /** @module RendererReferenceNode **/
  5007. /**
  5008. * This node is a special type of reference node which is intended
  5009. * for linking renderer properties with node values.
  5010. * ```js
  5011. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5012. * ```
  5013. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5014. * automatically be updated.
  5015. *
  5016. * @augments ReferenceBaseNode
  5017. */
  5018. class RendererReferenceNode extends ReferenceBaseNode {
  5019. static get type() {
  5020. return 'RendererReferenceNode';
  5021. }
  5022. /**
  5023. * Constructs a new renderer reference node.
  5024. *
  5025. * @param {String} property - The name of the property the node refers to.
  5026. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5027. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5028. * the node refers to the renderer of the current state.
  5029. */
  5030. constructor( property, inputType, renderer = null ) {
  5031. super( property, inputType, renderer );
  5032. /**
  5033. * The renderer the property belongs to. When no renderer is set,
  5034. * the node refers to the renderer of the current state.
  5035. *
  5036. * @type {Renderer?}
  5037. * @default null
  5038. */
  5039. this.renderer = renderer;
  5040. this.setGroup( renderGroup );
  5041. }
  5042. /**
  5043. * Updates the reference based on the given state. The state is only evaluated
  5044. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5045. *
  5046. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5047. * @return {Object} The updated reference.
  5048. */
  5049. updateReference( state ) {
  5050. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5051. return this.reference;
  5052. }
  5053. }
  5054. /**
  5055. * TSL function for creating a renderer reference node.
  5056. *
  5057. * @function
  5058. * @param {String} name - The name of the property the node refers to.
  5059. * @param {String} type - The uniform type that should be used to represent the property value.
  5060. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5061. * the node refers to the renderer of the current state.
  5062. * @returns {RendererReferenceNode}
  5063. */
  5064. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5065. /** @module ToneMappingNode **/
  5066. /**
  5067. * This node represents a tone mapping operation.
  5068. *
  5069. * @augments TempNode
  5070. */
  5071. class ToneMappingNode extends TempNode {
  5072. static get type() {
  5073. return 'ToneMappingNode';
  5074. }
  5075. /**
  5076. * Constructs a new tone mapping node.
  5077. *
  5078. * @param {Number} toneMapping - The tone mapping type.
  5079. * @param {Node} exposureNode - The tone mapping exposure.
  5080. * @param {Node} [colorNode=null] - The color node to process.
  5081. */
  5082. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5083. super( 'vec3' );
  5084. /**
  5085. * The tone mapping type.
  5086. *
  5087. * @type {Number}
  5088. */
  5089. this.toneMapping = toneMapping;
  5090. /**
  5091. * The tone mapping exposure.
  5092. *
  5093. * @type {Node}
  5094. * @default null
  5095. */
  5096. this.exposureNode = exposureNode;
  5097. /**
  5098. * Represents the color to process.
  5099. *
  5100. * @type {Node?}
  5101. * @default null
  5102. */
  5103. this.colorNode = colorNode;
  5104. }
  5105. /**
  5106. * Overwrites the default `customCacheKey()` implementation by including the tone
  5107. * mapping type into the cache key.
  5108. *
  5109. * @return {Number} The hash.
  5110. */
  5111. customCacheKey() {
  5112. return hash$1( this.toneMapping );
  5113. }
  5114. setup( builder ) {
  5115. const colorNode = this.colorNode || builder.context.color;
  5116. const toneMapping = this.toneMapping;
  5117. if ( toneMapping === NoToneMapping ) return colorNode;
  5118. let outputNode = null;
  5119. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5120. if ( toneMappingFn !== null ) {
  5121. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5122. } else {
  5123. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5124. outputNode = colorNode;
  5125. }
  5126. return outputNode;
  5127. }
  5128. }
  5129. /**
  5130. * TSL function for creating a tone mapping node.
  5131. *
  5132. * @function
  5133. * @param {Number} mapping - The tone mapping type.
  5134. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5135. * @param {Node<vec3> | Color} color - The color node to process.
  5136. * @returns {ToneMappingNode<vec3>}
  5137. */
  5138. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5139. /**
  5140. * TSL object that represents the global tone mapping exposure of the renderer.
  5141. *
  5142. * @type {RendererReferenceNode<vec3>}
  5143. */
  5144. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5145. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5146. /** @module BufferAttributeNode **/
  5147. /**
  5148. * In earlier `three.js` versions it was only possible to define attribute data
  5149. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5150. * on the node level.
  5151. * ```js
  5152. * const geometry = new THREE.PlaneGeometry();
  5153. * const positionAttribute = geometry.getAttribute( 'position' );
  5154. *
  5155. * const colors = [];
  5156. * for ( let i = 0; i < position.count; i ++ ) {
  5157. * colors.push( 1, 0, 0 );
  5158. * }
  5159. *
  5160. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5161. * ```
  5162. * This new approach is especially interesting when geometry data are generated via
  5163. * compute shaders. The below line converts a storage buffer into an attribute.
  5164. * ```js
  5165. * material.positionNode = positionBuffer.toAttribute();
  5166. * ```
  5167. * @augments InputNode
  5168. */
  5169. class BufferAttributeNode extends InputNode {
  5170. static get type() {
  5171. return 'BufferAttributeNode';
  5172. }
  5173. /**
  5174. * Constructs a new buffer attribute node.
  5175. *
  5176. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5177. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5178. * @param {Number} [bufferStride=0] - The buffer stride.
  5179. * @param {Number} [bufferOffset=0] - The buffer offset.
  5180. */
  5181. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5182. super( value, bufferType );
  5183. /**
  5184. * This flag can be used for type testing.
  5185. *
  5186. * @type {Boolean}
  5187. * @readonly
  5188. * @default true
  5189. */
  5190. this.isBufferNode = true;
  5191. /**
  5192. * The buffer type (e.g. `'vec3'`).
  5193. *
  5194. * @type {String}
  5195. * @default null
  5196. */
  5197. this.bufferType = bufferType;
  5198. /**
  5199. * The buffer stride.
  5200. *
  5201. * @type {Number}
  5202. * @default 0
  5203. */
  5204. this.bufferStride = bufferStride;
  5205. /**
  5206. * The buffer offset.
  5207. *
  5208. * @type {Number}
  5209. * @default 0
  5210. */
  5211. this.bufferOffset = bufferOffset;
  5212. /**
  5213. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5214. * if you are planning to update the attribute data per frame.
  5215. *
  5216. * @type {Number}
  5217. * @default StaticDrawUsage
  5218. */
  5219. this.usage = StaticDrawUsage;
  5220. /**
  5221. * Whether the attribute is instanced or not.
  5222. *
  5223. * @type {Boolean}
  5224. * @default false
  5225. */
  5226. this.instanced = false;
  5227. /**
  5228. * A reference to the buffer attribute.
  5229. *
  5230. * @type {BufferAttribute?}
  5231. * @default null
  5232. */
  5233. this.attribute = null;
  5234. /**
  5235. * `BufferAttributeNode` sets this property to `true` by default.
  5236. *
  5237. * @type {Boolean}
  5238. * @default true
  5239. */
  5240. this.global = true;
  5241. if ( value && value.isBufferAttribute === true ) {
  5242. this.attribute = value;
  5243. this.usage = value.usage;
  5244. this.instanced = value.isInstancedBufferAttribute;
  5245. }
  5246. }
  5247. /**
  5248. * This method is overwritten since the attribute data might be shared
  5249. * and thus the hash should be shared as well.
  5250. *
  5251. * @param {NodeBuilder} builder - The current node builder.
  5252. * @return {String} The hash.
  5253. */
  5254. getHash( builder ) {
  5255. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5256. let bufferData = builder.globalCache.getData( this.value );
  5257. if ( bufferData === undefined ) {
  5258. bufferData = {
  5259. node: this
  5260. };
  5261. builder.globalCache.setData( this.value, bufferData );
  5262. }
  5263. return bufferData.node.uuid;
  5264. }
  5265. return this.uuid;
  5266. }
  5267. /**
  5268. * This method is overwritten since the node type is inferred from
  5269. * the buffer attribute.
  5270. *
  5271. * @param {NodeBuilder} builder - The current node builder.
  5272. * @return {String} The node type.
  5273. */
  5274. getNodeType( builder ) {
  5275. if ( this.bufferType === null ) {
  5276. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5277. }
  5278. return this.bufferType;
  5279. }
  5280. /**
  5281. * Depending on which value was passed to the node, `setup()` behaves
  5282. * differently. If no instance of `BufferAttribute` was passed, the method
  5283. * creates an internal attribute and configures it respectively.
  5284. *
  5285. * @param {NodeBuilder} builder - The current node builder.
  5286. */
  5287. setup( builder ) {
  5288. if ( this.attribute !== null ) return;
  5289. const type = this.getNodeType( builder );
  5290. const array = this.value;
  5291. const itemSize = builder.getTypeLength( type );
  5292. const stride = this.bufferStride || itemSize;
  5293. const offset = this.bufferOffset;
  5294. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5295. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5296. buffer.setUsage( this.usage );
  5297. this.attribute = bufferAttribute;
  5298. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5299. }
  5300. /**
  5301. * Generates the code snippet of the buffer attribute node.
  5302. *
  5303. * @param {NodeBuilder} builder - The current node builder.
  5304. * @return {String} The generated code snippet.
  5305. */
  5306. generate( builder ) {
  5307. const nodeType = this.getNodeType( builder );
  5308. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5309. const propertyName = builder.getPropertyName( nodeAttribute );
  5310. let output = null;
  5311. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5312. this.name = propertyName;
  5313. output = propertyName;
  5314. } else {
  5315. const nodeVarying = varying( this );
  5316. output = nodeVarying.build( builder, nodeType );
  5317. }
  5318. return output;
  5319. }
  5320. /**
  5321. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5322. *
  5323. * @param {NodeBuilder} builder - The current node builder.
  5324. * @return {String} The input type.
  5325. */
  5326. getInputType( /*builder*/ ) {
  5327. return 'bufferAttribute';
  5328. }
  5329. /**
  5330. * Sets the `usage` property to the given value.
  5331. *
  5332. * @param {Number} value - The usage to set.
  5333. * @return {BufferAttributeNode} A reference to this node.
  5334. */
  5335. setUsage( value ) {
  5336. this.usage = value;
  5337. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5338. this.attribute.usage = value;
  5339. }
  5340. return this;
  5341. }
  5342. /**
  5343. * Sets the `instanced` property to the given value.
  5344. *
  5345. * @param {Number} value - The value to set.
  5346. * @return {BufferAttributeNode} A reference to this node.
  5347. */
  5348. setInstanced( value ) {
  5349. this.instanced = value;
  5350. return this;
  5351. }
  5352. }
  5353. /**
  5354. * TSL function for creating a buffer attribute node.
  5355. *
  5356. * @function
  5357. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5358. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5359. * @param {Number} [stride=0] - The buffer stride.
  5360. * @param {Number} [offset=0] - The buffer offset.
  5361. * @returns {BufferAttributeNode}
  5362. */
  5363. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5364. /**
  5365. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5366. * Use this function if attribute data are updated per frame.
  5367. *
  5368. * @function
  5369. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5370. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5371. * @param {Number} [stride=0] - The buffer stride.
  5372. * @param {Number} [offset=0] - The buffer offset.
  5373. * @returns {BufferAttributeNode}
  5374. */
  5375. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5376. /**
  5377. * TSL function for creating a buffer attribute node but with enabled instancing
  5378. *
  5379. * @function
  5380. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5381. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5382. * @param {Number} [stride=0] - The buffer stride.
  5383. * @param {Number} [offset=0] - The buffer offset.
  5384. * @returns {BufferAttributeNode}
  5385. */
  5386. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5387. /**
  5388. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5389. *
  5390. * @function
  5391. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5392. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5393. * @param {Number} [stride=0] - The buffer stride.
  5394. * @param {Number} [offset=0] - The buffer offset.
  5395. * @returns {BufferAttributeNode}
  5396. */
  5397. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5398. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5399. /** @module ComputeNode **/
  5400. /**
  5401. * TODO
  5402. *
  5403. * @augments Node
  5404. */
  5405. class ComputeNode extends Node {
  5406. static get type() {
  5407. return 'ComputeNode';
  5408. }
  5409. /**
  5410. * Constructs a new compute node.
  5411. *
  5412. * @param {Node} computeNode - TODO
  5413. * @param {Number} count - TODO.
  5414. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5415. */
  5416. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5417. super( 'void' );
  5418. /**
  5419. * This flag can be used for type testing.
  5420. *
  5421. * @type {Boolean}
  5422. * @readonly
  5423. * @default true
  5424. */
  5425. this.isComputeNode = true;
  5426. /**
  5427. * TODO
  5428. *
  5429. * @type {Node}
  5430. */
  5431. this.computeNode = computeNode;
  5432. /**
  5433. * TODO
  5434. *
  5435. * @type {Number}
  5436. */
  5437. this.count = count;
  5438. /**
  5439. * TODO
  5440. *
  5441. * @type {Array<Number>}
  5442. * @default [64]
  5443. */
  5444. this.workgroupSize = workgroupSize;
  5445. /**
  5446. * TODO
  5447. *
  5448. * @type {Number}
  5449. */
  5450. this.dispatchCount = 0;
  5451. /**
  5452. * TODO
  5453. *
  5454. * @type {Number}
  5455. */
  5456. this.version = 1;
  5457. /**
  5458. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5459. * is executed once per object by default.
  5460. *
  5461. * @type {String}
  5462. * @default 'object'
  5463. */
  5464. this.updateBeforeType = NodeUpdateType.OBJECT;
  5465. /**
  5466. * TODO
  5467. *
  5468. * @type {Function}
  5469. */
  5470. this.onInitFunction = null;
  5471. this.updateDispatchCount();
  5472. }
  5473. /**
  5474. * Executes the `dispose` event for this node.
  5475. */
  5476. dispose() {
  5477. this.dispatchEvent( { type: 'dispose' } );
  5478. }
  5479. /**
  5480. * TODO
  5481. */
  5482. updateDispatchCount() {
  5483. const { count, workgroupSize } = this;
  5484. let size = workgroupSize[ 0 ];
  5485. for ( let i = 1; i < workgroupSize.length; i ++ )
  5486. size *= workgroupSize[ i ];
  5487. this.dispatchCount = Math.ceil( count / size );
  5488. }
  5489. /**
  5490. * TODO
  5491. *
  5492. * @param {Function} callback - TODO.
  5493. * @return {ComputeNode} A reference to this node.
  5494. */
  5495. onInit( callback ) {
  5496. this.onInitFunction = callback;
  5497. return this;
  5498. }
  5499. /**
  5500. * The method execute the compute for this node.
  5501. *
  5502. * @param {NodeFrame} frame - A reference to the current node frame.
  5503. */
  5504. updateBefore( { renderer } ) {
  5505. renderer.compute( this );
  5506. }
  5507. generate( builder ) {
  5508. const { shaderStage } = builder;
  5509. if ( shaderStage === 'compute' ) {
  5510. const snippet = this.computeNode.build( builder, 'void' );
  5511. if ( snippet !== '' ) {
  5512. builder.addLineFlowCode( snippet, this );
  5513. }
  5514. }
  5515. }
  5516. }
  5517. /**
  5518. * TSL function for creating a compute node.
  5519. *
  5520. * @function
  5521. * @param {Node} node - TODO
  5522. * @param {Number} count - TODO.
  5523. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5524. * @returns {AtomicFunctionNode}
  5525. */
  5526. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5527. addMethodChaining( 'compute', compute );
  5528. /** @module CacheNode **/
  5529. /**
  5530. * This node can be used as a cache management component for another node.
  5531. * Caching is in general used by default in {@link NodeBuilder} but this node
  5532. * allows the usage of a shared parent cache during the build process.
  5533. *
  5534. * @augments Node
  5535. */
  5536. class CacheNode extends Node {
  5537. static get type() {
  5538. return 'CacheNode';
  5539. }
  5540. /**
  5541. * Constructs a new cache node.
  5542. *
  5543. * @param {Node} node - The node that should be cached.
  5544. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5545. */
  5546. constructor( node, parent = true ) {
  5547. super();
  5548. /**
  5549. * The node that should be cached.
  5550. *
  5551. * @type {Node}
  5552. */
  5553. this.node = node;
  5554. /**
  5555. * Whether this node refers to a shared parent cache or not.
  5556. *
  5557. * @type {Boolean}
  5558. * @default true
  5559. */
  5560. this.parent = parent;
  5561. /**
  5562. * This flag can be used for type testing.
  5563. *
  5564. * @type {Boolean}
  5565. * @readonly
  5566. * @default true
  5567. */
  5568. this.isCacheNode = true;
  5569. }
  5570. getNodeType( builder ) {
  5571. return this.node.getNodeType( builder );
  5572. }
  5573. build( builder, ...params ) {
  5574. const previousCache = builder.getCache();
  5575. const cache = builder.getCacheFromNode( this, this.parent );
  5576. builder.setCache( cache );
  5577. const data = this.node.build( builder, ...params );
  5578. builder.setCache( previousCache );
  5579. return data;
  5580. }
  5581. }
  5582. /**
  5583. * TSL function for creating a cache node.
  5584. *
  5585. * @function
  5586. * @param {Node} node - The node that should be cached.
  5587. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5588. * @returns {CacheNode}
  5589. */
  5590. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5591. addMethodChaining( 'cache', cache );
  5592. /** @module BypassNode **/
  5593. /**
  5594. * The class generates the code of a given node but returns another node in the output.
  5595. * This can be used to call a method or node that does not return a value, i.e.
  5596. * type `void` on an input where returning a value is required. Example:
  5597. *
  5598. * ```js
  5599. * material.colorNode = myColor.bypass( runVoidFn() )
  5600. *```
  5601. *
  5602. * @augments Node
  5603. */
  5604. class BypassNode extends Node {
  5605. static get type() {
  5606. return 'BypassNode';
  5607. }
  5608. /**
  5609. * Constructs a new bypass node.
  5610. *
  5611. * @param {Node} outputNode - The output node.
  5612. * @param {Node} callNode - The call node.
  5613. */
  5614. constructor( outputNode, callNode ) {
  5615. super();
  5616. /**
  5617. * This flag can be used for type testing.
  5618. *
  5619. * @type {Boolean}
  5620. * @readonly
  5621. * @default true
  5622. */
  5623. this.isBypassNode = true;
  5624. /**
  5625. * The output node.
  5626. *
  5627. * @type {Node}
  5628. */
  5629. this.outputNode = outputNode;
  5630. /**
  5631. * The call node.
  5632. *
  5633. * @type {Node}
  5634. */
  5635. this.callNode = callNode;
  5636. }
  5637. getNodeType( builder ) {
  5638. return this.outputNode.getNodeType( builder );
  5639. }
  5640. generate( builder ) {
  5641. const snippet = this.callNode.build( builder, 'void' );
  5642. if ( snippet !== '' ) {
  5643. builder.addLineFlowCode( snippet, this );
  5644. }
  5645. return this.outputNode.build( builder );
  5646. }
  5647. }
  5648. /**
  5649. * TSL function for creating a bypass node.
  5650. *
  5651. * @function
  5652. * @param {Node} outputNode - The output node.
  5653. * @param {Node} callNode - The call node.
  5654. * @returns {BypassNode}
  5655. */
  5656. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5657. addMethodChaining( 'bypass', bypass );
  5658. /** @module RemapNode **/
  5659. /**
  5660. * This node allows to remap a node value from one range into another. E.g a value of
  5661. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5662. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5663. *
  5664. * @augments Node
  5665. */
  5666. class RemapNode extends Node {
  5667. static get type() {
  5668. return 'RemapNode';
  5669. }
  5670. /**
  5671. * Constructs a new remap node.
  5672. *
  5673. * @param {Node} node - The node that should be remapped.
  5674. * @param {Node} inLowNode - The source or current lower bound of the range.
  5675. * @param {Node} inHighNode - The source or current upper bound of the range.
  5676. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5677. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5678. */
  5679. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5680. super();
  5681. /**
  5682. * The node that should be remapped.
  5683. *
  5684. * @type {Node}
  5685. */
  5686. this.node = node;
  5687. /**
  5688. * The source or current lower bound of the range.
  5689. *
  5690. * @type {Node}
  5691. */
  5692. this.inLowNode = inLowNode;
  5693. /**
  5694. * The source or current upper bound of the range.
  5695. *
  5696. * @type {Node}
  5697. */
  5698. this.inHighNode = inHighNode;
  5699. /**
  5700. * The target lower bound of the range.
  5701. *
  5702. * @type {Node}
  5703. * @default float(0)
  5704. */
  5705. this.outLowNode = outLowNode;
  5706. /**
  5707. * The target upper bound of the range.
  5708. *
  5709. * @type {Node}
  5710. * @default float(1)
  5711. */
  5712. this.outHighNode = outHighNode;
  5713. /**
  5714. * Whether the node value should be clamped before
  5715. * remapping it to the target range.
  5716. *
  5717. * @type {Boolean}
  5718. * @default true
  5719. */
  5720. this.doClamp = true;
  5721. }
  5722. setup() {
  5723. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5724. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5725. if ( doClamp === true ) t = t.clamp();
  5726. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5727. }
  5728. }
  5729. /**
  5730. * TSL function for creating a remap node.
  5731. *
  5732. * @function
  5733. * @param {Node} node - The node that should be remapped.
  5734. * @param {Node} inLowNode - The source or current lower bound of the range.
  5735. * @param {Node} inHighNode - The source or current upper bound of the range.
  5736. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5737. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5738. * @returns {RemapNode}
  5739. */
  5740. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5741. /**
  5742. * TSL function for creating a remap node, but with enabled clamping.
  5743. *
  5744. * @function
  5745. * @param {Node} node - The node that should be remapped.
  5746. * @param {Node} inLowNode - The source or current lower bound of the range.
  5747. * @param {Node} inHighNode - The source or current upper bound of the range.
  5748. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5749. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5750. * @returns {RemapNode}
  5751. */
  5752. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5753. addMethodChaining( 'remap', remap );
  5754. addMethodChaining( 'remapClamp', remapClamp );
  5755. /** @module ExpressionNode **/
  5756. /**
  5757. * This class can be used to implement basic expressions in shader code.
  5758. * Basic examples for that are `return`, `continue` or `discard` statements.
  5759. *
  5760. * @augments Node
  5761. */
  5762. class ExpressionNode extends Node {
  5763. static get type() {
  5764. return 'ExpressionNode';
  5765. }
  5766. /**
  5767. * Constructs a new expression node.
  5768. *
  5769. * @param {String} [snippet=''] - The native code snippet.
  5770. * @param {String} [nodeType='void'] - The node type.
  5771. */
  5772. constructor( snippet = '', nodeType = 'void' ) {
  5773. super( nodeType );
  5774. /**
  5775. * The native code snippet.
  5776. *
  5777. * @type {String}
  5778. * @default ''
  5779. */
  5780. this.snippet = snippet;
  5781. }
  5782. generate( builder, output ) {
  5783. const type = this.getNodeType( builder );
  5784. const snippet = this.snippet;
  5785. if ( type === 'void' ) {
  5786. builder.addLineFlowCode( snippet, this );
  5787. } else {
  5788. return builder.format( `( ${ snippet } )`, type, output );
  5789. }
  5790. }
  5791. }
  5792. /**
  5793. * TSL function for creating an expression node.
  5794. *
  5795. * @function
  5796. * @param {String} [snippet=''] - The native code snippet.
  5797. * @param {String} [nodeType='void'] - The node type.
  5798. * @returns {ExpressionNode}
  5799. */
  5800. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5801. /** @module Discard **/
  5802. /**
  5803. * Represents a `discard` shader operation in TSL.
  5804. *
  5805. * @method
  5806. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5807. * @return {Node} The `discard` expression.
  5808. */
  5809. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5810. /**
  5811. * Represents a `return` shader operation in TSL.
  5812. *
  5813. * @method
  5814. * @return {ExpressionNode} The `return` expression.
  5815. */
  5816. const Return = () => expression( 'return' ).append();
  5817. addMethodChaining( 'discard', Discard );
  5818. /** @module RenderOutputNode **/
  5819. /**
  5820. * Normally, tone mapping and color conversion happens automatically
  5821. * before outputting pixel too the default (screen) framebuffer. In certain
  5822. * post processing setups this happens to late because certain effects
  5823. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5824. * to apply tone mapping and color space conversion at an arbitrary point
  5825. * in the effect chain.
  5826. *
  5827. * When applying tone mapping and color space conversion manually with this node,
  5828. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5829. *
  5830. * ```js
  5831. * const postProcessing = new PostProcessing( renderer );
  5832. * postProcessing.outputColorTransform = false;
  5833. *
  5834. * const scenePass = pass( scene, camera );
  5835. * const outputPass = renderOutput( scenePass );
  5836. *
  5837. * postProcessing.outputNode = outputPass;
  5838. * ```
  5839. *
  5840. * @augments TempNode
  5841. */
  5842. class RenderOutputNode extends TempNode {
  5843. static get type() {
  5844. return 'RenderOutputNode';
  5845. }
  5846. /**
  5847. * Constructs a new render output node.
  5848. *
  5849. * @param {Node} colorNode - The color node to process.
  5850. * @param {Number} toneMapping - The tone mapping type.
  5851. * @param {String} outputColorSpace - The output color space.
  5852. */
  5853. constructor( colorNode, toneMapping, outputColorSpace ) {
  5854. super( 'vec4' );
  5855. /**
  5856. * The color node to process.
  5857. *
  5858. * @type {Node}
  5859. */
  5860. this.colorNode = colorNode;
  5861. /**
  5862. * The tone mapping type.
  5863. *
  5864. * @type {Number?}
  5865. */
  5866. this.toneMapping = toneMapping;
  5867. /**
  5868. * The output color space.
  5869. *
  5870. * @type {String?}
  5871. */
  5872. this.outputColorSpace = outputColorSpace;
  5873. /**
  5874. * This flag can be used for type testing.
  5875. *
  5876. * @type {Boolean}
  5877. * @readonly
  5878. * @default true
  5879. */
  5880. this.isRenderOutputNode = true;
  5881. }
  5882. setup( { context } ) {
  5883. let outputNode = this.colorNode || context.color;
  5884. // tone mapping
  5885. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  5886. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  5887. if ( toneMapping !== NoToneMapping ) {
  5888. outputNode = outputNode.toneMapping( toneMapping );
  5889. }
  5890. // working to output color space
  5891. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  5892. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  5893. }
  5894. return outputNode;
  5895. }
  5896. }
  5897. /**
  5898. * TSL function for creating a posterize node.
  5899. *
  5900. * @function
  5901. * @param {Node} color - The color node to process.
  5902. * @param {Number?} [toneMapping=null] - The tone mapping type.
  5903. * @param {String?} [outputColorSpace=null] - The output color space.
  5904. * @returns {RenderOutputNode}
  5905. */
  5906. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  5907. addMethodChaining( 'renderOutput', renderOutput );
  5908. // Non-PURE exports list, side-effects are required here.
  5909. // TSL Base Syntax
  5910. function addNodeElement( name/*, nodeElement*/ ) {
  5911. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  5912. }
  5913. /** @module AttributeNode **/
  5914. /**
  5915. * Base class for representing shader attributes as nodes.
  5916. *
  5917. * @augments Node
  5918. */
  5919. class AttributeNode extends Node {
  5920. static get type() {
  5921. return 'AttributeNode';
  5922. }
  5923. /**
  5924. * Constructs a new attribute node.
  5925. *
  5926. * @param {String} attributeName - The name of the attribute.
  5927. * @param {String?} nodeType - The node type.
  5928. */
  5929. constructor( attributeName, nodeType = null ) {
  5930. super( nodeType );
  5931. /**
  5932. * `AttributeNode` sets this property to `true` by default.
  5933. *
  5934. * @type {Boolean}
  5935. * @default true
  5936. */
  5937. this.global = true;
  5938. this._attributeName = attributeName;
  5939. }
  5940. getHash( builder ) {
  5941. return this.getAttributeName( builder );
  5942. }
  5943. getNodeType( builder ) {
  5944. let nodeType = this.nodeType;
  5945. if ( nodeType === null ) {
  5946. const attributeName = this.getAttributeName( builder );
  5947. if ( builder.hasGeometryAttribute( attributeName ) ) {
  5948. const attribute = builder.geometry.getAttribute( attributeName );
  5949. nodeType = builder.getTypeFromAttribute( attribute );
  5950. } else {
  5951. nodeType = 'float';
  5952. }
  5953. }
  5954. return nodeType;
  5955. }
  5956. /**
  5957. * Sets the attribute name to the given value. The method can be
  5958. * overwritten in derived classes if the final name must be computed
  5959. * analytically.
  5960. *
  5961. * @param {String} attributeName - The name of the attribute.
  5962. * @return {AttributeNode} A reference to this node.
  5963. */
  5964. setAttributeName( attributeName ) {
  5965. this._attributeName = attributeName;
  5966. return this;
  5967. }
  5968. /**
  5969. * Returns the attribute name of this node. The method can be
  5970. * overwritten in derived classes if the final name must be computed
  5971. * analytically.
  5972. *
  5973. * @param {NodeBuilder} builder - The current node builder.
  5974. * @return {String} The attribute name.
  5975. */
  5976. getAttributeName( /*builder*/ ) {
  5977. return this._attributeName;
  5978. }
  5979. generate( builder ) {
  5980. const attributeName = this.getAttributeName( builder );
  5981. const nodeType = this.getNodeType( builder );
  5982. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  5983. if ( geometryAttribute === true ) {
  5984. const attribute = builder.geometry.getAttribute( attributeName );
  5985. const attributeType = builder.getTypeFromAttribute( attribute );
  5986. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  5987. if ( builder.shaderStage === 'vertex' ) {
  5988. return builder.format( nodeAttribute.name, attributeType, nodeType );
  5989. } else {
  5990. const nodeVarying = varying( this );
  5991. return nodeVarying.build( builder, nodeType );
  5992. }
  5993. } else {
  5994. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  5995. return builder.generateConst( nodeType );
  5996. }
  5997. }
  5998. serialize( data ) {
  5999. super.serialize( data );
  6000. data.global = this.global;
  6001. data._attributeName = this._attributeName;
  6002. }
  6003. deserialize( data ) {
  6004. super.deserialize( data );
  6005. this.global = data.global;
  6006. this._attributeName = data._attributeName;
  6007. }
  6008. }
  6009. /**
  6010. * TSL function for creating an attribute node.
  6011. *
  6012. * @function
  6013. * @param {String} name - The name of the attribute.
  6014. * @param {String?} nodeType - The node type.
  6015. * @returns {AttributeNode}
  6016. */
  6017. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6018. /** @module UV **/
  6019. /**
  6020. * TSL function for creating an uv attribute node with the given index.
  6021. *
  6022. * @function
  6023. * @param {Number} [index=0] - The uv index.
  6024. * @return {AttributeNode<vec2>} The uv attribute node.
  6025. */
  6026. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6027. /** @module TextureSizeNode **/
  6028. /**
  6029. * A node that represents the dimensions of a texture. The texture size is
  6030. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6031. * or `textureSize()`.
  6032. *
  6033. * @augments Node
  6034. */
  6035. class TextureSizeNode extends Node {
  6036. static get type() {
  6037. return 'TextureSizeNode';
  6038. }
  6039. /**
  6040. * Constructs a new texture size node.
  6041. *
  6042. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6043. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6044. */
  6045. constructor( textureNode, levelNode = null ) {
  6046. super( 'uvec2' );
  6047. /**
  6048. * This flag can be used for type testing.
  6049. *
  6050. * @type {Boolean}
  6051. * @readonly
  6052. * @default true
  6053. */
  6054. this.isTextureSizeNode = true;
  6055. /**
  6056. * A texture node which size should be retrieved.
  6057. *
  6058. * @type {TextureNode}
  6059. */
  6060. this.textureNode = textureNode;
  6061. /**
  6062. * A level node which defines the requested mip.
  6063. *
  6064. * @type {Node<int>}
  6065. * @default null
  6066. */
  6067. this.levelNode = levelNode;
  6068. }
  6069. generate( builder, output ) {
  6070. const textureProperty = this.textureNode.build( builder, 'property' );
  6071. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6072. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6073. }
  6074. }
  6075. /**
  6076. * TSL function for creating a texture size node.
  6077. *
  6078. * @function
  6079. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6080. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6081. * @returns {TextureSizeNode}
  6082. */
  6083. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6084. /** @module MatcapUVNode **/
  6085. /**
  6086. * A special type of uniform node that computes the
  6087. * maximum mipmap level for a given texture node.
  6088. *
  6089. * ```js
  6090. * const level = maxMipLevel( textureNode );
  6091. * ```
  6092. *
  6093. * @augments module:UniformNode~UniformNode
  6094. */
  6095. class MaxMipLevelNode extends UniformNode {
  6096. static get type() {
  6097. return 'MaxMipLevelNode';
  6098. }
  6099. /**
  6100. * Constructs a new max mip level node.
  6101. *
  6102. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6103. */
  6104. constructor( textureNode ) {
  6105. super( 0 );
  6106. /**
  6107. * The texture node to compute the max mip level for.
  6108. *
  6109. * @private
  6110. * @type {TextureNode}
  6111. */
  6112. this._textureNode = textureNode;
  6113. /**
  6114. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6115. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6116. *
  6117. * @type {String}
  6118. * @default 'frame'
  6119. */
  6120. this.updateType = NodeUpdateType.FRAME;
  6121. }
  6122. /**
  6123. * The texture node to compute the max mip level for.
  6124. *
  6125. * @readonly
  6126. * @type {TextureNode}
  6127. */
  6128. get textureNode() {
  6129. return this._textureNode;
  6130. }
  6131. /**
  6132. * The texture.
  6133. *
  6134. * @readonly
  6135. * @type {Texture}
  6136. */
  6137. get texture() {
  6138. return this._textureNode.value;
  6139. }
  6140. update() {
  6141. const texture = this.texture;
  6142. const images = texture.images;
  6143. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6144. if ( image && image.width !== undefined ) {
  6145. const { width, height } = image;
  6146. this.value = Math.log2( Math.max( width, height ) );
  6147. }
  6148. }
  6149. }
  6150. /**
  6151. * TSL function for creating a max mip level node.
  6152. *
  6153. * @function
  6154. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6155. * @returns {MaxMipLevelNode}
  6156. */
  6157. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6158. /** @module TextureNode **/
  6159. /**
  6160. * This type of uniform node represents a 2D texture.
  6161. *
  6162. * @augments module:UniformNode~UniformNode
  6163. */
  6164. class TextureNode extends UniformNode {
  6165. static get type() {
  6166. return 'TextureNode';
  6167. }
  6168. /**
  6169. * Constructs a new texture node.
  6170. *
  6171. * @param {Texture} value - The texture.
  6172. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6173. * @param {Node<int>?} [levelNode=null] - The level node.
  6174. * @param {Node<float>?} [biasNode=null] - The bias node.
  6175. */
  6176. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6177. super( value );
  6178. /**
  6179. * This flag can be used for type testing.
  6180. *
  6181. * @type {Boolean}
  6182. * @readonly
  6183. * @default true
  6184. */
  6185. this.isTextureNode = true;
  6186. /**
  6187. * Represents the texture coordinates.
  6188. *
  6189. * @type {Node<vec2|vec3>?}
  6190. * @default null
  6191. */
  6192. this.uvNode = uvNode;
  6193. /**
  6194. * Represents the mip level that should be selected.
  6195. *
  6196. * @type {Node<int>?}
  6197. * @default null
  6198. */
  6199. this.levelNode = levelNode;
  6200. /**
  6201. * Represents the bias to be applied during level-of-detail computation.
  6202. *
  6203. * @type {Node<float>?}
  6204. * @default null
  6205. */
  6206. this.biasNode = biasNode;
  6207. /**
  6208. * Represents a reference value a texture sample is compared to.
  6209. *
  6210. * @type {Node<float>?}
  6211. * @default null
  6212. */
  6213. this.compareNode = null;
  6214. /**
  6215. * When using texture arrays, the depth node defines the layer to select.
  6216. *
  6217. * @type {Node<int>?}
  6218. * @default null
  6219. */
  6220. this.depthNode = null;
  6221. /**
  6222. * When defined, a texture is sampled using explicit gradients.
  6223. *
  6224. * @type {Array<Node<vec2>>?}
  6225. * @default null
  6226. */
  6227. this.gradNode = null;
  6228. /**
  6229. * Whether texture values should be sampled or fetched.
  6230. *
  6231. * @type {Boolean}
  6232. * @default true
  6233. */
  6234. this.sampler = true;
  6235. /**
  6236. * Whether the uv transformation matrix should be
  6237. * automatically updated or not. Use `setUpdateMatrix()`
  6238. * if you want to change the value of the property.
  6239. *
  6240. * @type {Boolean}
  6241. * @default false
  6242. */
  6243. this.updateMatrix = false;
  6244. /**
  6245. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6246. * sets the value to `frame` when the uv transformation matrix should
  6247. * automatically be updated.
  6248. *
  6249. * @type {String}
  6250. * @default 'none'
  6251. */
  6252. this.updateType = NodeUpdateType.NONE;
  6253. /**
  6254. * The reference node.
  6255. *
  6256. * @type {Node?}
  6257. * @default null
  6258. */
  6259. this.referenceNode = null;
  6260. /**
  6261. * The texture value is stored in a private property.
  6262. *
  6263. * @private
  6264. * @type {Texture}
  6265. */
  6266. this._value = value;
  6267. /**
  6268. * The uniform node that represents the uv transformation matrix.
  6269. *
  6270. * @private
  6271. * @type {UniformNode<mat3>?}
  6272. */
  6273. this._matrixUniform = null;
  6274. this.setUpdateMatrix( uvNode === null );
  6275. }
  6276. set value( value ) {
  6277. if ( this.referenceNode ) {
  6278. this.referenceNode.value = value;
  6279. } else {
  6280. this._value = value;
  6281. }
  6282. }
  6283. /**
  6284. * The texture value.
  6285. *
  6286. * @type {Texture}
  6287. */
  6288. get value() {
  6289. return this.referenceNode ? this.referenceNode.value : this._value;
  6290. }
  6291. /**
  6292. * Overwritten since the uniform hash is defined by the texture's UUID.
  6293. *
  6294. * @param {NodeBuilder} builder - The current node builder.
  6295. * @return {String} The uniform hash.
  6296. */
  6297. getUniformHash( /*builder*/ ) {
  6298. return this.value.uuid;
  6299. }
  6300. /**
  6301. * Overwritten since the node type is inferred from the texture type.
  6302. *
  6303. * @param {NodeBuilder} builder - The current node builder.
  6304. * @return {String} The node type.
  6305. */
  6306. getNodeType( /*builder*/ ) {
  6307. if ( this.value.isDepthTexture === true ) return 'float';
  6308. if ( this.value.type === UnsignedIntType ) {
  6309. return 'uvec4';
  6310. } else if ( this.value.type === IntType ) {
  6311. return 'ivec4';
  6312. }
  6313. return 'vec4';
  6314. }
  6315. /**
  6316. * Overwrites the default implementation to return a fixed value `'texture'`.
  6317. *
  6318. * @param {NodeBuilder} builder - The current node builder.
  6319. * @return {String} The input type.
  6320. */
  6321. getInputType( /*builder*/ ) {
  6322. return 'texture';
  6323. }
  6324. /**
  6325. * Returns a default uvs based on the current texture's channel.
  6326. *
  6327. * @return {AttributeNode<vec2>} The default uvs.
  6328. */
  6329. getDefaultUV() {
  6330. return uv( this.value.channel );
  6331. }
  6332. /**
  6333. * Overwritten to always return the texture reference of the node.
  6334. *
  6335. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6336. * @return {Texture} The texture reference.
  6337. */
  6338. updateReference( /*state*/ ) {
  6339. return this.value;
  6340. }
  6341. /**
  6342. * Transforms the given uv node with the texture transformation matrix.
  6343. *
  6344. * @param {Node} uvNode - The uv node to transform.
  6345. * @return {Node} The transformed uv node.
  6346. */
  6347. getTransformedUV( uvNode ) {
  6348. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6349. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6350. }
  6351. /**
  6352. * Defines whether the uv transformation matrix should automatically be updated or not.
  6353. *
  6354. * @param {Boolean} value - The update toggle.
  6355. * @return {TextureNode} A reference to this node.
  6356. */
  6357. setUpdateMatrix( value ) {
  6358. this.updateMatrix = value;
  6359. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  6360. return this;
  6361. }
  6362. /**
  6363. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6364. * to modify the uv node for correct sampling.
  6365. *
  6366. * @param {NodeBuilder} builder - The current node builder.
  6367. * @param {Node} uvNode - The uv node to setup.
  6368. * @return {Node} The updated uv node.
  6369. */
  6370. setupUV( builder, uvNode ) {
  6371. const texture = this.value;
  6372. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6373. if ( this.sampler ) {
  6374. uvNode = uvNode.flipY();
  6375. } else {
  6376. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6377. }
  6378. }
  6379. return uvNode;
  6380. }
  6381. /**
  6382. * Setups texture node by preparing the internal nodes for code generation.
  6383. *
  6384. * @param {NodeBuilder} builder - The current node builder.
  6385. */
  6386. setup( builder ) {
  6387. const properties = builder.getNodeProperties( this );
  6388. properties.referenceNode = this.referenceNode;
  6389. //
  6390. let uvNode = this.uvNode;
  6391. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6392. uvNode = builder.context.getUV( this );
  6393. }
  6394. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6395. if ( this.updateMatrix === true ) {
  6396. uvNode = this.getTransformedUV( uvNode );
  6397. }
  6398. uvNode = this.setupUV( builder, uvNode );
  6399. //
  6400. let levelNode = this.levelNode;
  6401. if ( levelNode === null && builder.context.getTextureLevel ) {
  6402. levelNode = builder.context.getTextureLevel( this );
  6403. }
  6404. //
  6405. properties.uvNode = uvNode;
  6406. properties.levelNode = levelNode;
  6407. properties.biasNode = this.biasNode;
  6408. properties.compareNode = this.compareNode;
  6409. properties.gradNode = this.gradNode;
  6410. properties.depthNode = this.depthNode;
  6411. }
  6412. /**
  6413. * Generates the uv code snippet.
  6414. *
  6415. * @param {NodeBuilder} builder - The current node builder.
  6416. * @param {Node} uvNode - The uv node to generate code for.
  6417. * @return {String} The generated code snippet.
  6418. */
  6419. generateUV( builder, uvNode ) {
  6420. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6421. }
  6422. /**
  6423. * Generates the snippet for the texture sampling.
  6424. *
  6425. * @param {NodeBuilder} builder - The current node builder.
  6426. * @param {String} textureProperty - The texture property.
  6427. * @param {String} uvSnippet - The uv snippet.
  6428. * @param {String} levelSnippet - The level snippet.
  6429. * @param {String} biasSnippet - The bias snippet.
  6430. * @param {String} depthSnippet - The depth snippet.
  6431. * @param {String} compareSnippet - The compare snippet.
  6432. * @param {String} gradSnippet - The grad snippet.
  6433. * @return {String} The generated code snippet.
  6434. */
  6435. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6436. const texture = this.value;
  6437. let snippet;
  6438. if ( levelSnippet ) {
  6439. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6440. } else if ( biasSnippet ) {
  6441. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6442. } else if ( gradSnippet ) {
  6443. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6444. } else if ( compareSnippet ) {
  6445. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6446. } else if ( this.sampler === false ) {
  6447. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6448. } else {
  6449. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6450. }
  6451. return snippet;
  6452. }
  6453. /**
  6454. * Generates the code snippet of the texture node.
  6455. *
  6456. * @param {NodeBuilder} builder - The current node builder.
  6457. * @param {String} output - The current output.
  6458. * @return {String} The generated code snippet.
  6459. */
  6460. generate( builder, output ) {
  6461. const properties = builder.getNodeProperties( this );
  6462. const texture = this.value;
  6463. if ( ! texture || texture.isTexture !== true ) {
  6464. throw new Error( 'TextureNode: Need a three.js texture.' );
  6465. }
  6466. const textureProperty = super.generate( builder, 'property' );
  6467. if ( output === 'sampler' ) {
  6468. return textureProperty + '_sampler';
  6469. } else if ( builder.isReference( output ) ) {
  6470. return textureProperty;
  6471. } else {
  6472. const nodeData = builder.getDataFromNode( this );
  6473. let propertyName = nodeData.propertyName;
  6474. if ( propertyName === undefined ) {
  6475. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6476. const uvSnippet = this.generateUV( builder, uvNode );
  6477. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6478. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6479. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6480. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6481. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6482. const nodeVar = builder.getVarFromNode( this );
  6483. propertyName = builder.getPropertyName( nodeVar );
  6484. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6485. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6486. nodeData.snippet = snippet;
  6487. nodeData.propertyName = propertyName;
  6488. }
  6489. let snippet = propertyName;
  6490. const nodeType = this.getNodeType( builder );
  6491. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6492. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6493. }
  6494. return builder.format( snippet, nodeType, output );
  6495. }
  6496. }
  6497. /**
  6498. * Sets the sampler value.
  6499. *
  6500. * @param {Boolean} value - The sampler value to set.
  6501. * @return {TextureNode} A reference to this texture node.
  6502. */
  6503. setSampler( value ) {
  6504. this.sampler = value;
  6505. return this;
  6506. }
  6507. /**
  6508. * Returns the sampler value.
  6509. *
  6510. * @return {Boolean} The sampler value.
  6511. */
  6512. getSampler() {
  6513. return this.sampler;
  6514. }
  6515. // @TODO: Move to TSL
  6516. uv( uvNode ) { // @deprecated, r172
  6517. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6518. return this.sample( uvNode );
  6519. }
  6520. /**
  6521. * Samples the texture with the given uv node.
  6522. *
  6523. * @param {Node} uvNode - The uv node.
  6524. * @return {TextureNode} A texture node representing the texture sample.
  6525. */
  6526. sample( uvNode ) {
  6527. const textureNode = this.clone();
  6528. textureNode.uvNode = nodeObject( uvNode );
  6529. textureNode.referenceNode = this.getSelf();
  6530. return nodeObject( textureNode );
  6531. }
  6532. /**
  6533. * Samples a blurred version of the texture by defining an internal bias.
  6534. *
  6535. * @param {Node<float>} amountNode - How blurred the texture should be.
  6536. * @return {TextureNode} A texture node representing the texture sample.
  6537. */
  6538. blur( amountNode ) {
  6539. const textureNode = this.clone();
  6540. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6541. textureNode.referenceNode = this.getSelf();
  6542. return nodeObject( textureNode );
  6543. }
  6544. /**
  6545. * Samples a specific mip of the texture.
  6546. *
  6547. * @param {Node<int>} levelNode - The mip level to sample.
  6548. * @return {TextureNode} A texture node representing the texture sample.
  6549. */
  6550. level( levelNode ) {
  6551. const textureNode = this.clone();
  6552. textureNode.levelNode = nodeObject( levelNode );
  6553. textureNode.referenceNode = this.getSelf();
  6554. return nodeObject( textureNode );
  6555. }
  6556. /**
  6557. * Returns the texture size of the requested level.
  6558. *
  6559. * @param {Node<int>} levelNode - The level to compute the size for.
  6560. * @return {TextureSizeNode} The texture size.
  6561. */
  6562. size( levelNode ) {
  6563. return textureSize( this, levelNode );
  6564. }
  6565. /**
  6566. * Samples the texture with the given bias.
  6567. *
  6568. * @param {Node<float>} biasNode - The bias node.
  6569. * @return {TextureNode} A texture node representing the texture sample.
  6570. */
  6571. bias( biasNode ) {
  6572. const textureNode = this.clone();
  6573. textureNode.biasNode = nodeObject( biasNode );
  6574. textureNode.referenceNode = this.getSelf();
  6575. return nodeObject( textureNode );
  6576. }
  6577. /**
  6578. * Samples the texture by executing a compare operation.
  6579. *
  6580. * @param {Node<float>} compareNode - The node that defines the compare value.
  6581. * @return {TextureNode} A texture node representing the texture sample.
  6582. */
  6583. compare( compareNode ) {
  6584. const textureNode = this.clone();
  6585. textureNode.compareNode = nodeObject( compareNode );
  6586. textureNode.referenceNode = this.getSelf();
  6587. return nodeObject( textureNode );
  6588. }
  6589. /**
  6590. * Samples the texture using an explicit gradient.
  6591. *
  6592. * @param {Node<vec2>} gradNodeX - The gradX node.
  6593. * @param {Node<vec2>} gradNodeY - The gradY node.
  6594. * @return {TextureNode} A texture node representing the texture sample.
  6595. */
  6596. grad( gradNodeX, gradNodeY ) {
  6597. const textureNode = this.clone();
  6598. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6599. textureNode.referenceNode = this.getSelf();
  6600. return nodeObject( textureNode );
  6601. }
  6602. /**
  6603. * Samples the texture by defining a depth node.
  6604. *
  6605. * @param {Node<int>} depthNode - The depth node.
  6606. * @return {TextureNode} A texture node representing the texture sample.
  6607. */
  6608. depth( depthNode ) {
  6609. const textureNode = this.clone();
  6610. textureNode.depthNode = nodeObject( depthNode );
  6611. textureNode.referenceNode = this.getSelf();
  6612. return nodeObject( textureNode );
  6613. }
  6614. // --
  6615. serialize( data ) {
  6616. super.serialize( data );
  6617. data.value = this.value.toJSON( data.meta ).uuid;
  6618. data.sampler = this.sampler;
  6619. data.updateMatrix = this.updateMatrix;
  6620. data.updateType = this.updateType;
  6621. }
  6622. deserialize( data ) {
  6623. super.deserialize( data );
  6624. this.value = data.meta.textures[ data.value ];
  6625. this.sampler = data.sampler;
  6626. this.updateMatrix = data.updateMatrix;
  6627. this.updateType = data.updateType;
  6628. }
  6629. /**
  6630. * The update is used to implement the update of the uv transformation matrix.
  6631. */
  6632. update() {
  6633. const texture = this.value;
  6634. const matrixUniform = this._matrixUniform;
  6635. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6636. if ( texture.matrixAutoUpdate === true ) {
  6637. texture.updateMatrix();
  6638. }
  6639. }
  6640. /**
  6641. * Clones the texture node.
  6642. *
  6643. * @return {TextureNode} The cloned texture node.
  6644. */
  6645. clone() {
  6646. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6647. newNode.sampler = this.sampler;
  6648. return newNode;
  6649. }
  6650. }
  6651. /**
  6652. * TSL function for creating a texture node.
  6653. *
  6654. * @function
  6655. * @param {Texture} value - The texture.
  6656. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6657. * @param {Node<int>?} [levelNode=null] - The level node.
  6658. * @param {Node<float>?} [biasNode=null] - The bias node.
  6659. * @returns {TextureNode}
  6660. */
  6661. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6662. /**
  6663. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6664. *
  6665. * @function
  6666. * @param {Texture} value - The texture.
  6667. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6668. * @param {Node<int>?} [levelNode=null] - The level node.
  6669. * @param {Node<float>?} [biasNode=null] - The bias node.
  6670. * @returns {TextureNode}
  6671. */
  6672. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6673. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6674. /**
  6675. * Converts a texture or texture node to a sampler.
  6676. *
  6677. * @function
  6678. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6679. * @returns {Node}
  6680. */
  6681. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6682. /** @module Camera **/
  6683. /**
  6684. * TSL object that represents the `near` value of the camera used for the current render.
  6685. *
  6686. * @type {UniformNode<float>}
  6687. */
  6688. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  6689. /**
  6690. * TSL object that represents the `far` value of the camera used for the current render.
  6691. *
  6692. * @type {UniformNode<float>}
  6693. */
  6694. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  6695. /**
  6696. * TSL object that represents the projection matrix of the camera used for the current render.
  6697. *
  6698. * @type {UniformNode<mat4>}
  6699. */
  6700. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  6701. /**
  6702. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  6703. *
  6704. * @type {UniformNode<mat4>}
  6705. */
  6706. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  6707. /**
  6708. * TSL object that represents the view matrix of the camera used for the current render.
  6709. *
  6710. * @type {UniformNode<mat4>}
  6711. */
  6712. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  6713. /**
  6714. * TSL object that represents the world matrix of the camera used for the current render.
  6715. *
  6716. * @type {UniformNode<mat4>}
  6717. */
  6718. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  6719. /**
  6720. * TSL object that represents the normal matrix of the camera used for the current render.
  6721. *
  6722. * @type {UniformNode<mat3>}
  6723. */
  6724. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  6725. /**
  6726. * TSL object that represents the position in world space of the camera used for the current render.
  6727. *
  6728. * @type {UniformNode<vec3>}
  6729. */
  6730. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  6731. /** @module Object3DNode **/
  6732. /**
  6733. * This node can be used to access transformation related metrics of 3D objects.
  6734. * Depending on the selected scope, a different metric is represented as a uniform
  6735. * in the shader. The following scopes are supported:
  6736. *
  6737. * - `POSITION`: The object's position in world space.
  6738. * - `VIEW_POSITION`: The object's position in view/camera space.
  6739. * - `DIRECTION`: The object's direction in world space.
  6740. * - `SCALE`: The object's scale in world space.
  6741. * - `WORLD_MATRIX`: The object's matrix in world space.
  6742. *
  6743. * @augments Node
  6744. */
  6745. class Object3DNode extends Node {
  6746. static get type() {
  6747. return 'Object3DNode';
  6748. }
  6749. /**
  6750. * Constructs a new object 3D node.
  6751. *
  6752. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6753. * @param {Object3D?} [object3d=null] - The 3D object.
  6754. */
  6755. constructor( scope, object3d = null ) {
  6756. super();
  6757. /**
  6758. * The node reports a different type of transformation depending on the scope.
  6759. *
  6760. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  6761. */
  6762. this.scope = scope;
  6763. /**
  6764. * The 3D object.
  6765. *
  6766. * @type {Object3D?}
  6767. * @default null
  6768. */
  6769. this.object3d = object3d;
  6770. /**
  6771. * Overwritten since this type of node is updated per object.
  6772. *
  6773. * @type {String}
  6774. * @default 'object'
  6775. */
  6776. this.updateType = NodeUpdateType.OBJECT;
  6777. /**
  6778. * Holds the value of the node as a uniform.
  6779. *
  6780. * @private
  6781. * @type {UniformNode}
  6782. */
  6783. this._uniformNode = new UniformNode( null );
  6784. }
  6785. /**
  6786. * Overwritten since the node type is inferred from the scope.
  6787. *
  6788. * @param {NodeBuilder} builder - The current node builder.
  6789. * @return {String} The node type.
  6790. */
  6791. getNodeType() {
  6792. const scope = this.scope;
  6793. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6794. return 'mat4';
  6795. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6796. return 'vec3';
  6797. }
  6798. }
  6799. /**
  6800. * Updates the uniform value depending on the scope.
  6801. *
  6802. * @param {NodeFrame} frame - The current node frame.
  6803. */
  6804. update( frame ) {
  6805. const object = this.object3d;
  6806. const uniformNode = this._uniformNode;
  6807. const scope = this.scope;
  6808. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6809. uniformNode.value = object.matrixWorld;
  6810. } else if ( scope === Object3DNode.POSITION ) {
  6811. uniformNode.value = uniformNode.value || new Vector3();
  6812. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6813. } else if ( scope === Object3DNode.SCALE ) {
  6814. uniformNode.value = uniformNode.value || new Vector3();
  6815. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  6816. } else if ( scope === Object3DNode.DIRECTION ) {
  6817. uniformNode.value = uniformNode.value || new Vector3();
  6818. object.getWorldDirection( uniformNode.value );
  6819. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  6820. const camera = frame.camera;
  6821. uniformNode.value = uniformNode.value || new Vector3();
  6822. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6823. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  6824. }
  6825. }
  6826. /**
  6827. * Generates the code snippet of the uniform node. The node type of the uniform
  6828. * node also depends on the selected scope.
  6829. *
  6830. * @param {NodeBuilder} builder - The current node builder.
  6831. * @return {String} The generated code snippet.
  6832. */
  6833. generate( builder ) {
  6834. const scope = this.scope;
  6835. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6836. this._uniformNode.nodeType = 'mat4';
  6837. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6838. this._uniformNode.nodeType = 'vec3';
  6839. }
  6840. return this._uniformNode.build( builder );
  6841. }
  6842. serialize( data ) {
  6843. super.serialize( data );
  6844. data.scope = this.scope;
  6845. }
  6846. deserialize( data ) {
  6847. super.deserialize( data );
  6848. this.scope = data.scope;
  6849. }
  6850. }
  6851. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  6852. Object3DNode.POSITION = 'position';
  6853. Object3DNode.SCALE = 'scale';
  6854. Object3DNode.VIEW_POSITION = 'viewPosition';
  6855. Object3DNode.DIRECTION = 'direction';
  6856. /**
  6857. * TSL function for creating an object 3D node that represents the object's direction in world space.
  6858. *
  6859. * @function
  6860. * @param {Object3D?} [object3d=null] - The 3D object.
  6861. * @returns {Object3DNode<vec3>}
  6862. */
  6863. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  6864. /**
  6865. * TSL function for creating an object 3D node that represents the object's world matrix.
  6866. *
  6867. * @function
  6868. * @param {Object3D?} [object3d=null] - The 3D object.
  6869. * @returns {Object3DNode<mat4>}
  6870. */
  6871. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  6872. /**
  6873. * TSL function for creating an object 3D node that represents the object's position in world space.
  6874. *
  6875. * @function
  6876. * @param {Object3D?} [object3d=null] - The 3D object.
  6877. * @returns {Object3DNode<vec3>}
  6878. */
  6879. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  6880. /**
  6881. * TSL function for creating an object 3D node that represents the object's scale in world space.
  6882. *
  6883. * @function
  6884. * @param {Object3D?} [object3d=null] - The 3D object.
  6885. * @returns {Object3DNode<vec3>}
  6886. */
  6887. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  6888. /**
  6889. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  6890. *
  6891. * @function
  6892. * @param {Object3D?} [object3d=null] - The 3D object.
  6893. * @returns {Object3DNode<vec3>}
  6894. */
  6895. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  6896. /** @module ModelNode **/
  6897. /**
  6898. * This type of node is a specialized version of `Object3DNode`
  6899. * with larger set of model related metrics. Unlike `Object3DNode`,
  6900. * `ModelNode` extracts the reference to the 3D object from the
  6901. * current node frame state.
  6902. *
  6903. * @augments module:Object3DNode~Object3DNode
  6904. */
  6905. class ModelNode extends Object3DNode {
  6906. static get type() {
  6907. return 'ModelNode';
  6908. }
  6909. /**
  6910. * Constructs a new object model node.
  6911. *
  6912. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6913. */
  6914. constructor( scope ) {
  6915. super( scope );
  6916. }
  6917. /**
  6918. * Extracts the model reference from the frame state and then
  6919. * updates the uniform value depending on the scope.
  6920. *
  6921. * @param {NodeFrame} frame - The current node frame.
  6922. */
  6923. update( frame ) {
  6924. this.object3d = frame.object;
  6925. super.update( frame );
  6926. }
  6927. }
  6928. /**
  6929. * TSL object that represents the object's direction in world space.
  6930. *
  6931. * @type {ModelNode<vec3>}
  6932. */
  6933. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  6934. /**
  6935. * TSL object that represents the object's world matrix.
  6936. *
  6937. * @type {ModelNode<mat4>}
  6938. */
  6939. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  6940. /**
  6941. * TSL object that represents the object's position in world space.
  6942. *
  6943. * @type {ModelNode<vec3>}
  6944. */
  6945. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  6946. /**
  6947. * TSL object that represents the object's scale in world space.
  6948. *
  6949. * @type {ModelNode<vec3>}
  6950. */
  6951. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  6952. /**
  6953. * TSL object that represents the object's position in view/camera space.
  6954. *
  6955. * @type {ModelNode<vec3>}
  6956. */
  6957. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  6958. /**
  6959. * TSL object that represents the object's normal matrix.
  6960. *
  6961. * @type {UniformNode<mat3>}
  6962. */
  6963. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  6964. /**
  6965. * TSL object that represents the object's inverse world matrix.
  6966. *
  6967. * @type {UniformNode<mat4>}
  6968. */
  6969. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  6970. /**
  6971. * TSL object that represents the object's model view matrix.
  6972. *
  6973. * @type {Node<mat4>}
  6974. */
  6975. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  6976. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  6977. } ).once() )().toVar( 'modelViewMatrix' );
  6978. // GPU Precision
  6979. /**
  6980. * TSL object that represents the object's model view in `mediump` precision.
  6981. *
  6982. * @type {Node<mat4>}
  6983. */
  6984. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  6985. // CPU Precision
  6986. /**
  6987. * TSL object that represents the object's model view in `highp` precision
  6988. * which is achieved by computing the matrix in JS and not in the shader.
  6989. *
  6990. * @type {Node<mat4>}
  6991. */
  6992. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  6993. builder.context.isHighPrecisionModelViewMatrix = true;
  6994. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  6995. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  6996. } );
  6997. } ).once() )().toVar( 'highpModelViewMatrix' );
  6998. /**
  6999. * TSL object that represents the object's model normal view in `highp` precision
  7000. * which is achieved by computing the matrix in JS and not in the shader.
  7001. *
  7002. * @type {Node<mat3>}
  7003. */
  7004. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7005. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7006. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7007. if ( isHighPrecisionModelViewMatrix !== true ) {
  7008. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7009. }
  7010. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7011. } );
  7012. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7013. /** @module Position **/
  7014. /**
  7015. * TSL object that represents the position attribute of the current rendered object.
  7016. *
  7017. * @type {AttributeNode<vec3>}
  7018. */
  7019. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7020. /**
  7021. * TSL object that represents the vertex position in local space of the current rendered object.
  7022. *
  7023. * @type {AttributeNode<vec3>}
  7024. */
  7025. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7026. /**
  7027. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7028. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7029. *
  7030. * @type {AttributeNode<vec3>}
  7031. */
  7032. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7033. /**
  7034. * TSL object that represents the vertex position in world space of the current rendered object.
  7035. *
  7036. * @type {VaryingNode<vec3>}
  7037. */
  7038. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7039. /**
  7040. * TSL object that represents the position world direction of the current rendered object.
  7041. *
  7042. * @type {Node<vec3>}
  7043. */
  7044. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7045. /**
  7046. * TSL object that represents the vertex position in view space of the current rendered object.
  7047. *
  7048. * @type {VaryingNode<vec3>}
  7049. */
  7050. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7051. return builder.context.setupPositionView();
  7052. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7053. /**
  7054. * TSL object that represents the position view direction of the current rendered object.
  7055. *
  7056. * @type {VaryingNode<vec3>}
  7057. */
  7058. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7059. /** @module FrontFacingNode **/
  7060. /**
  7061. * This node can be used to evaluate whether a primitive is front or back facing.
  7062. *
  7063. * @augments Node
  7064. */
  7065. class FrontFacingNode extends Node {
  7066. static get type() {
  7067. return 'FrontFacingNode';
  7068. }
  7069. /**
  7070. * Constructs a new front facing node.
  7071. */
  7072. constructor() {
  7073. super( 'bool' );
  7074. /**
  7075. * This flag can be used for type testing.
  7076. *
  7077. * @type {Boolean}
  7078. * @readonly
  7079. * @default true
  7080. */
  7081. this.isFrontFacingNode = true;
  7082. }
  7083. generate( builder ) {
  7084. const { renderer, material } = builder;
  7085. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7086. if ( material.side === BackSide ) {
  7087. return 'false';
  7088. }
  7089. }
  7090. return builder.getFrontFacing();
  7091. }
  7092. }
  7093. /**
  7094. * TSL object that represents whether a primitive is front or back facing
  7095. *
  7096. * @type {FrontFacingNode<bool>}
  7097. */
  7098. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7099. /**
  7100. * TSL object that represents the front facing status as a number instead of a bool.
  7101. * `1` means front facing, `-1` means back facing.
  7102. *
  7103. * @type {Node<float>}
  7104. */
  7105. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7106. /** @module Normal **/
  7107. /**
  7108. * TSL object that represents the normal attribute of the current rendered object.
  7109. *
  7110. * @type {Node<vec3>}
  7111. */
  7112. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7113. /**
  7114. * TSL object that represents the vertex normal in local space of the current rendered object.
  7115. *
  7116. * @type {Node<vec3>}
  7117. */
  7118. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7119. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7120. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7121. return vec3( 0, 1, 0 );
  7122. }
  7123. return normalGeometry;
  7124. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7125. /**
  7126. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7127. *
  7128. * @type {Node<vec3>}
  7129. */
  7130. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7131. /**
  7132. * TSL object that represents the vertex normal in view space of the current rendered object.
  7133. *
  7134. * @type {Node<vec3>}
  7135. */
  7136. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7137. let node;
  7138. if ( builder.material.flatShading === true ) {
  7139. node = normalFlat;
  7140. } else {
  7141. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7142. }
  7143. return node;
  7144. }, 'vec3' ).once() )().toVar( 'normalView' );
  7145. /**
  7146. * TSL object that represents the vertex normal in world space of the current rendered object.
  7147. *
  7148. * @type {Node<vec3>}
  7149. */
  7150. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7151. /**
  7152. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7153. *
  7154. * @type {Node<vec3>}
  7155. */
  7156. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7157. return builder.context.setupNormal();
  7158. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7159. /**
  7160. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7161. *
  7162. * @type {Node<vec3>}
  7163. */
  7164. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7165. /**
  7166. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7167. *
  7168. * @type {Node<vec3>}
  7169. */
  7170. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7171. return builder.context.setupClearcoatNormal();
  7172. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7173. /**
  7174. * Transforms the normal with the given matrix.
  7175. *
  7176. * @function
  7177. * @param {Node<vec3>} normal - The normal.
  7178. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7179. * @return {Node<vec3>} The transformed normal.
  7180. */
  7181. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7182. const m = mat3( matrix );
  7183. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7184. return m.mul( transformedNormal ).xyz;
  7185. } );
  7186. /**
  7187. * Transforms the given normal from local to view space.
  7188. *
  7189. * @function
  7190. * @param {Node<vec3>} normal - The normal.
  7191. * @param {NodeBuilder} builder - The current node builder.
  7192. * @return {Node<vec3>} The transformed normal.
  7193. */
  7194. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7195. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7196. if ( modelNormalViewMatrix !== null ) {
  7197. return modelNormalViewMatrix.transformDirection( normal );
  7198. }
  7199. //
  7200. const transformedNormal = modelNormalMatrix.mul( normal );
  7201. return cameraViewMatrix.transformDirection( transformedNormal );
  7202. } );
  7203. /** @module MaterialProperties **/
  7204. /**
  7205. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7206. *
  7207. * @type {UniformNode<float>}
  7208. */
  7209. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7210. /** @module ReflectVector **/
  7211. /**
  7212. * The reflect vector in view space.
  7213. *
  7214. * @type {Node<vec3>}
  7215. */
  7216. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7217. /**
  7218. * The refract vector in view space.
  7219. *
  7220. * @type {Node<vec3>}
  7221. */
  7222. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7223. /**
  7224. * Used for sampling cube maps when using cube reflection mapping.
  7225. *
  7226. * @type {Node<vec3>}
  7227. */
  7228. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7229. /**
  7230. * Used for sampling cube maps when using cube refraction mapping.
  7231. *
  7232. * @type {Node<vec3>}
  7233. */
  7234. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7235. /** @module CubeTextureNode **/
  7236. /**
  7237. * This type of uniform node represents a cube texture.
  7238. *
  7239. * @augments module:TextureNode~TextureNode
  7240. */
  7241. class CubeTextureNode extends TextureNode {
  7242. static get type() {
  7243. return 'CubeTextureNode';
  7244. }
  7245. /**
  7246. * Constructs a new cube texture node.
  7247. *
  7248. * @param {CubeTexture} value - The cube texture.
  7249. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7250. * @param {Node<int>?} [levelNode=null] - The level node.
  7251. * @param {Node<float>?} [biasNode=null] - The bias node.
  7252. */
  7253. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7254. super( value, uvNode, levelNode, biasNode );
  7255. /**
  7256. * This flag can be used for type testing.
  7257. *
  7258. * @type {Boolean}
  7259. * @readonly
  7260. * @default true
  7261. */
  7262. this.isCubeTextureNode = true;
  7263. }
  7264. /**
  7265. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7266. *
  7267. * @param {NodeBuilder} builder - The current node builder.
  7268. * @return {String} The input type.
  7269. */
  7270. getInputType( /*builder*/ ) {
  7271. return 'cubeTexture';
  7272. }
  7273. /**
  7274. * Returns a default uvs based on the mapping type of the cube texture.
  7275. *
  7276. * @return {Node<vec3>} The default uv attribute.
  7277. */
  7278. getDefaultUV() {
  7279. const texture = this.value;
  7280. if ( texture.mapping === CubeReflectionMapping ) {
  7281. return reflectVector;
  7282. } else if ( texture.mapping === CubeRefractionMapping ) {
  7283. return refractVector;
  7284. } else {
  7285. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7286. return vec3( 0, 0, 0 );
  7287. }
  7288. }
  7289. /**
  7290. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7291. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7292. *
  7293. * @param {Boolean} value - The update toggle.
  7294. */
  7295. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7296. /**
  7297. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7298. * to modify the uv node for correct sampling.
  7299. *
  7300. * @param {NodeBuilder} builder - The current node builder.
  7301. * @param {Node} uvNode - The uv node to setup.
  7302. * @return {Node} The updated uv node.
  7303. */
  7304. setupUV( builder, uvNode ) {
  7305. const texture = this.value;
  7306. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7307. return vec3( uvNode.x.negate(), uvNode.yz );
  7308. } else {
  7309. return uvNode;
  7310. }
  7311. }
  7312. /**
  7313. * Generates the uv code snippet.
  7314. *
  7315. * @param {NodeBuilder} builder - The current node builder.
  7316. * @param {Node} cubeUV - The uv node to generate code for.
  7317. * @return {String} The generated code snippet.
  7318. */
  7319. generateUV( builder, cubeUV ) {
  7320. return cubeUV.build( builder, 'vec3' );
  7321. }
  7322. }
  7323. /**
  7324. * TSL function for creating a cube texture node.
  7325. *
  7326. * @function
  7327. * @param {CubeTexture} value - The cube texture.
  7328. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7329. * @param {Node<int>?} [levelNode=null] - The level node.
  7330. * @param {Node<float>?} [biasNode=null] - The bias node.
  7331. * @returns {CubeTextureNode}
  7332. */
  7333. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7334. /** @module BufferNode **/
  7335. /**
  7336. * A special type of uniform node which represents array-like data
  7337. * as uniform buffers. The access usually happens via `element()`
  7338. * which returns an instance of {@link ArrayElementNode}. For example:
  7339. *
  7340. * ```js
  7341. * const bufferNode = buffer( array, 'mat4', count );
  7342. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7343. * ```
  7344. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7345. * since it handles more input types and automatically cares about buffer paddings.
  7346. *
  7347. * @augments module:UniformNode~UniformNode
  7348. */
  7349. class BufferNode extends UniformNode {
  7350. static get type() {
  7351. return 'BufferNode';
  7352. }
  7353. /**
  7354. * Constructs a new buffer node.
  7355. *
  7356. * @param {Array<Number>} value - Array-like buffer data.
  7357. * @param {String} bufferType - The data type of the buffer.
  7358. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7359. */
  7360. constructor( value, bufferType, bufferCount = 0 ) {
  7361. super( value, bufferType );
  7362. /**
  7363. * This flag can be used for type testing.
  7364. *
  7365. * @type {Boolean}
  7366. * @readonly
  7367. * @default true
  7368. */
  7369. this.isBufferNode = true;
  7370. /**
  7371. * The data type of the buffer.
  7372. *
  7373. * @type {String}
  7374. */
  7375. this.bufferType = bufferType;
  7376. /**
  7377. * The uniform node that holds the value of the reference node.
  7378. *
  7379. * @type {Number}
  7380. * @default 0
  7381. */
  7382. this.bufferCount = bufferCount;
  7383. }
  7384. /**
  7385. * The data type of the buffer elements.
  7386. *
  7387. * @param {NodeBuilder} builder - The current node builder.
  7388. * @return {String} The element type.
  7389. */
  7390. getElementType( builder ) {
  7391. return this.getNodeType( builder );
  7392. }
  7393. /**
  7394. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7395. *
  7396. * @param {NodeBuilder} builder - The current node builder.
  7397. * @return {String} The input type.
  7398. */
  7399. getInputType( /*builder*/ ) {
  7400. return 'buffer';
  7401. }
  7402. }
  7403. /**
  7404. * TSL function for creating a buffer node.
  7405. *
  7406. * @function
  7407. * @param {Array} value - Array-like buffer data.
  7408. * @param {String} type - The data type of a buffer element.
  7409. * @param {Number} count - The count of buffer elements.
  7410. * @returns {BufferNode}
  7411. */
  7412. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7413. /** @module UniformArrayNode **/
  7414. /**
  7415. * Represents the element access on uniform array nodes.
  7416. *
  7417. * @augments ArrayElementNode
  7418. */
  7419. class UniformArrayElementNode extends ArrayElementNode {
  7420. static get type() {
  7421. return 'UniformArrayElementNode';
  7422. }
  7423. /**
  7424. * Constructs a new buffer node.
  7425. *
  7426. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7427. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7428. */
  7429. constructor( uniformArrayNode, indexNode ) {
  7430. super( uniformArrayNode, indexNode );
  7431. /**
  7432. * This flag can be used for type testing.
  7433. *
  7434. * @type {Boolean}
  7435. * @readonly
  7436. * @default true
  7437. */
  7438. this.isArrayBufferElementNode = true;
  7439. }
  7440. generate( builder ) {
  7441. const snippet = super.generate( builder );
  7442. const type = this.getNodeType();
  7443. const paddedType = this.node.getPaddedType();
  7444. return builder.format( snippet, paddedType, type );
  7445. }
  7446. }
  7447. /**
  7448. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7449. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7450. * data types in the array (e.g `three.js` primitives) and automatically
  7451. * manage buffer padding. It should be the first choice when working with
  7452. * uniforms buffers.
  7453. * ```js
  7454. * const tintColors = uniformArray( [
  7455. * new Color( 1, 0, 0 ),
  7456. * new Color( 0, 1, 0 ),
  7457. * new Color( 0, 0, 1 )
  7458. * ], 'color' );
  7459. *
  7460. * const redColor = tintColors.element( 0 );
  7461. *
  7462. * @augments module:BufferNode~BufferNode
  7463. */
  7464. class UniformArrayNode extends BufferNode {
  7465. static get type() {
  7466. return 'UniformArrayNode';
  7467. }
  7468. /**
  7469. * Constructs a new uniform array node.
  7470. *
  7471. * @param {Array<Any>} value - Array holding the buffer data.
  7472. * @param {String?} [elementType=null] - The data type of a buffer element.
  7473. */
  7474. constructor( value, elementType = null ) {
  7475. super( null );
  7476. /**
  7477. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7478. * hold number primitives as well as three.js objects like vectors, matrices
  7479. * or colors.
  7480. *
  7481. * @type {Array<Any>}
  7482. */
  7483. this.array = value;
  7484. /**
  7485. * The data type of an array element.
  7486. *
  7487. * @type {String}
  7488. */
  7489. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7490. /**
  7491. * The padded type. Uniform buffers must conform to a certain buffer layout
  7492. * so a separate type is computed to ensure correct buffer size.
  7493. *
  7494. * @type {String}
  7495. */
  7496. this.paddedType = this.getPaddedType();
  7497. /**
  7498. * Overwritten since uniform array nodes are updated per render.
  7499. *
  7500. * @type {String}
  7501. * @default 'render'
  7502. */
  7503. this.updateType = NodeUpdateType.RENDER;
  7504. /**
  7505. * This flag can be used for type testing.
  7506. *
  7507. * @type {Boolean}
  7508. * @readonly
  7509. * @default true
  7510. */
  7511. this.isArrayBufferNode = true;
  7512. }
  7513. /**
  7514. * This method is overwritten since the node type is inferred from the
  7515. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7516. *
  7517. * @param {NodeBuilder} builder - The current node builder.
  7518. * @return {String} The node type.
  7519. */
  7520. getNodeType( /*builder*/ ) {
  7521. return this.paddedType;
  7522. }
  7523. /**
  7524. * The data type of the array elements.
  7525. *
  7526. * @param {NodeBuilder} builder - The current node builder.
  7527. * @return {String} The element type.
  7528. */
  7529. getElementType() {
  7530. return this.elementType;
  7531. }
  7532. /**
  7533. * Returns the padded type based on the element type.
  7534. *
  7535. * @return {String} The padded type.
  7536. */
  7537. getPaddedType() {
  7538. const elementType = this.elementType;
  7539. let paddedType = 'vec4';
  7540. if ( elementType === 'mat2' ) {
  7541. paddedType = 'mat2';
  7542. } else if ( /mat/.test( elementType ) === true ) {
  7543. paddedType = 'mat4';
  7544. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7545. paddedType = 'ivec4';
  7546. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7547. paddedType = 'uvec4';
  7548. }
  7549. return paddedType;
  7550. }
  7551. /**
  7552. * The update makes sure to correctly transfer the data from the (complex) objects
  7553. * in the array to the internal, correctly padded value buffer.
  7554. *
  7555. * @param {NodeFrame} frame - A reference to the current node frame.
  7556. */
  7557. update( /*frame*/ ) {
  7558. const { array, value } = this;
  7559. const elementType = this.elementType;
  7560. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7561. for ( let i = 0; i < array.length; i ++ ) {
  7562. const index = i * 4;
  7563. value[ index ] = array[ i ];
  7564. }
  7565. } else if ( elementType === 'color' ) {
  7566. for ( let i = 0; i < array.length; i ++ ) {
  7567. const index = i * 4;
  7568. const vector = array[ i ];
  7569. value[ index ] = vector.r;
  7570. value[ index + 1 ] = vector.g;
  7571. value[ index + 2 ] = vector.b || 0;
  7572. //value[ index + 3 ] = vector.a || 0;
  7573. }
  7574. } else if ( elementType === 'mat2' ) {
  7575. for ( let i = 0; i < array.length; i ++ ) {
  7576. const index = i * 4;
  7577. const matrix = array[ i ];
  7578. value[ index ] = matrix.elements[ 0 ];
  7579. value[ index + 1 ] = matrix.elements[ 1 ];
  7580. value[ index + 2 ] = matrix.elements[ 2 ];
  7581. value[ index + 3 ] = matrix.elements[ 3 ];
  7582. }
  7583. } else if ( elementType === 'mat3' ) {
  7584. for ( let i = 0; i < array.length; i ++ ) {
  7585. const index = i * 16;
  7586. const matrix = array[ i ];
  7587. value[ index ] = matrix.elements[ 0 ];
  7588. value[ index + 1 ] = matrix.elements[ 1 ];
  7589. value[ index + 2 ] = matrix.elements[ 2 ];
  7590. value[ index + 4 ] = matrix.elements[ 3 ];
  7591. value[ index + 5 ] = matrix.elements[ 4 ];
  7592. value[ index + 6 ] = matrix.elements[ 5 ];
  7593. value[ index + 8 ] = matrix.elements[ 6 ];
  7594. value[ index + 9 ] = matrix.elements[ 7 ];
  7595. value[ index + 10 ] = matrix.elements[ 8 ];
  7596. value[ index + 15 ] = 1;
  7597. }
  7598. } else if ( elementType === 'mat4' ) {
  7599. for ( let i = 0; i < array.length; i ++ ) {
  7600. const index = i * 16;
  7601. const matrix = array[ i ];
  7602. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7603. value[ index + i ] = matrix.elements[ i ];
  7604. }
  7605. }
  7606. } else {
  7607. for ( let i = 0; i < array.length; i ++ ) {
  7608. const index = i * 4;
  7609. const vector = array[ i ];
  7610. value[ index ] = vector.x;
  7611. value[ index + 1 ] = vector.y;
  7612. value[ index + 2 ] = vector.z || 0;
  7613. value[ index + 3 ] = vector.w || 0;
  7614. }
  7615. }
  7616. }
  7617. /**
  7618. * Implement the value buffer creation based on the array data.
  7619. *
  7620. * @param {NodeBuilder} builder - A reference to the current node builder.
  7621. * @return {null}
  7622. */
  7623. setup( builder ) {
  7624. const length = this.array.length;
  7625. const elementType = this.elementType;
  7626. let arrayType = Float32Array;
  7627. const paddedType = this.paddedType;
  7628. const paddedElementLength = builder.getTypeLength( paddedType );
  7629. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7630. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7631. this.value = new arrayType( length * paddedElementLength );
  7632. this.bufferCount = length;
  7633. this.bufferType = paddedType;
  7634. return super.setup( builder );
  7635. }
  7636. /**
  7637. * Overwrites the default `element()` method to provide element access
  7638. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7639. *
  7640. * @param {IndexNode} indexNode - The index node.
  7641. * @return {UniformArrayElementNode}
  7642. */
  7643. element( indexNode ) {
  7644. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7645. }
  7646. }
  7647. /**
  7648. * TSL function for creating an uniform array node.
  7649. *
  7650. * @function
  7651. * @param {Array<Any>} values - Array-like data.
  7652. * @param {String} nodeType - The data type of the array elements.
  7653. * @returns {UniformArrayNode}
  7654. */
  7655. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7656. //
  7657. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7658. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7659. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7660. };
  7661. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7662. /** @module ReferenceNode **/
  7663. /**
  7664. * This class is only relevant if the referenced property is array-like.
  7665. * In this case, `ReferenceElementNode` allows to refer to a specific
  7666. * element inside the data structure via an index.
  7667. *
  7668. * @augments ArrayElementNode
  7669. */
  7670. class ReferenceElementNode extends ArrayElementNode {
  7671. static get type() {
  7672. return 'ReferenceElementNode';
  7673. }
  7674. /**
  7675. * Constructs a new reference element node.
  7676. *
  7677. * @param {Node?} referenceNode - The reference node.
  7678. * @param {Node} indexNode - The index node that defines the element access.
  7679. */
  7680. constructor( referenceNode, indexNode ) {
  7681. super( referenceNode, indexNode );
  7682. /**
  7683. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7684. * property references to the current node.
  7685. *
  7686. * @type {Node?}
  7687. * @default null
  7688. */
  7689. this.referenceNode = referenceNode;
  7690. /**
  7691. * This flag can be used for type testing.
  7692. *
  7693. * @type {Boolean}
  7694. * @readonly
  7695. * @default true
  7696. */
  7697. this.isReferenceElementNode = true;
  7698. }
  7699. /**
  7700. * This method is overwritten since the node type is inferred from
  7701. * the uniform type of the reference node.
  7702. *
  7703. * @param {NodeBuilder} builder - The current node builder.
  7704. * @return {String} The node type.
  7705. */
  7706. getNodeType() {
  7707. return this.referenceNode.uniformType;
  7708. }
  7709. generate( builder ) {
  7710. const snippet = super.generate( builder );
  7711. const arrayType = this.referenceNode.getNodeType();
  7712. const elementType = this.getNodeType();
  7713. return builder.format( snippet, arrayType, elementType );
  7714. }
  7715. }
  7716. /**
  7717. * This type of node establishes a reference to a property of another object.
  7718. * In this way, the value of the node is automatically linked to the value of
  7719. * referenced object. Reference nodes internally represent the linked value
  7720. * as a uniform.
  7721. *
  7722. * @augments Node
  7723. */
  7724. class ReferenceNode extends Node {
  7725. static get type() {
  7726. return 'ReferenceNode';
  7727. }
  7728. /**
  7729. * Constructs a new reference node.
  7730. *
  7731. * @param {String} property - The name of the property the node refers to.
  7732. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7733. * @param {Object?} [object=null] - The object the property belongs to.
  7734. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7735. */
  7736. constructor( property, uniformType, object = null, count = null ) {
  7737. super();
  7738. /**
  7739. * The name of the property the node refers to.
  7740. *
  7741. * @type {String}
  7742. */
  7743. this.property = property;
  7744. /**
  7745. * The uniform type that should be used to represent the property value.
  7746. *
  7747. * @type {String}
  7748. */
  7749. this.uniformType = uniformType;
  7750. /**
  7751. * The object the property belongs to.
  7752. *
  7753. * @type {Object?}
  7754. * @default null
  7755. */
  7756. this.object = object;
  7757. /**
  7758. * When the linked property is an array, this parameter defines its length.
  7759. *
  7760. * @type {Number?}
  7761. * @default null
  7762. */
  7763. this.count = count;
  7764. /**
  7765. * The property name might have dots so nested properties can be referred.
  7766. * The hierarchy of the names is stored inside this array.
  7767. *
  7768. * @type {Array<String>}
  7769. */
  7770. this.properties = property.split( '.' );
  7771. /**
  7772. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7773. * since the final reference might be updated from calling code.
  7774. *
  7775. * @type {Object?}
  7776. * @default null
  7777. */
  7778. this.reference = object;
  7779. /**
  7780. * The uniform node that holds the value of the reference node.
  7781. *
  7782. * @type {UniformNode}
  7783. * @default null
  7784. */
  7785. this.node = null;
  7786. /**
  7787. * The uniform group of the internal uniform.
  7788. *
  7789. * @type {UniformGroupNode}
  7790. * @default null
  7791. */
  7792. this.group = null;
  7793. /**
  7794. * An optional label of the internal uniform node.
  7795. *
  7796. * @type {String?}
  7797. * @default null
  7798. */
  7799. this.name = null;
  7800. /**
  7801. * Overwritten since reference nodes are updated per object.
  7802. *
  7803. * @type {String}
  7804. * @default 'object'
  7805. */
  7806. this.updateType = NodeUpdateType.OBJECT;
  7807. }
  7808. /**
  7809. * When the referred property is array-like, this method can be used
  7810. * to access elements via an index node.
  7811. *
  7812. * @param {IndexNode} indexNode - indexNode.
  7813. * @return {ReferenceElementNode} A reference to an element.
  7814. */
  7815. element( indexNode ) {
  7816. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  7817. }
  7818. /**
  7819. * Sets the uniform group for this reference node.
  7820. *
  7821. * @param {UniformGroupNode} group - The uniform group to set.
  7822. * @return {ReferenceNode} A reference to this node.
  7823. */
  7824. setGroup( group ) {
  7825. this.group = group;
  7826. return this;
  7827. }
  7828. /**
  7829. * Sets the label for the internal uniform.
  7830. *
  7831. * @param {String} name - The label to set.
  7832. * @return {ReferenceNode} A reference to this node.
  7833. */
  7834. label( name ) {
  7835. this.name = name;
  7836. return this;
  7837. }
  7838. /**
  7839. * Sets the node type which automatically defines the internal
  7840. * uniform type.
  7841. *
  7842. * @param {String} uniformType - The type to set.
  7843. */
  7844. setNodeType( uniformType ) {
  7845. let node = null;
  7846. if ( this.count !== null ) {
  7847. node = buffer( null, uniformType, this.count );
  7848. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  7849. node = uniformArray( null, uniformType );
  7850. } else if ( uniformType === 'texture' ) {
  7851. node = texture( null );
  7852. } else if ( uniformType === 'cubeTexture' ) {
  7853. node = cubeTexture( null );
  7854. } else {
  7855. node = uniform( null, uniformType );
  7856. }
  7857. if ( this.group !== null ) {
  7858. node.setGroup( this.group );
  7859. }
  7860. if ( this.name !== null ) node.label( this.name );
  7861. this.node = node.getSelf();
  7862. }
  7863. /**
  7864. * This method is overwritten since the node type is inferred from
  7865. * the type of the reference node.
  7866. *
  7867. * @param {NodeBuilder} builder - The current node builder.
  7868. * @return {String} The node type.
  7869. */
  7870. getNodeType( builder ) {
  7871. if ( this.node === null ) {
  7872. this.updateReference( builder );
  7873. this.updateValue();
  7874. }
  7875. return this.node.getNodeType( builder );
  7876. }
  7877. /**
  7878. * Returns the property value from the given referred object.
  7879. *
  7880. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  7881. * @return {Any} The value.
  7882. */
  7883. getValueFromReference( object = this.reference ) {
  7884. const { properties } = this;
  7885. let value = object[ properties[ 0 ] ];
  7886. for ( let i = 1; i < properties.length; i ++ ) {
  7887. value = value[ properties[ i ] ];
  7888. }
  7889. return value;
  7890. }
  7891. /**
  7892. * Allows to update the reference based on the given state. The state is only
  7893. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  7894. *
  7895. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7896. * @return {Object} The updated reference.
  7897. */
  7898. updateReference( state ) {
  7899. this.reference = this.object !== null ? this.object : state.object;
  7900. return this.reference;
  7901. }
  7902. /**
  7903. * The output of the reference node is the internal uniform node.
  7904. *
  7905. * @param {NodeBuilder} builder - The current node builder.
  7906. * @return {UniformNode} The output node.
  7907. */
  7908. setup( /* builder */ ) {
  7909. this.updateValue();
  7910. return this.node;
  7911. }
  7912. /**
  7913. * Overwritten to to update the internal uniform value.
  7914. *
  7915. * @param {NodeFrame} frame - A reference to the current node frame.
  7916. */
  7917. update( /*frame*/ ) {
  7918. this.updateValue();
  7919. }
  7920. /**
  7921. * Retrieves the value from the referred object property and uses it
  7922. * to updated the internal uniform.
  7923. */
  7924. updateValue() {
  7925. if ( this.node === null ) this.setNodeType( this.uniformType );
  7926. const value = this.getValueFromReference();
  7927. if ( Array.isArray( value ) ) {
  7928. this.node.array = value;
  7929. } else {
  7930. this.node.value = value;
  7931. }
  7932. }
  7933. }
  7934. /**
  7935. * TSL function for creating a reference node.
  7936. *
  7937. * @function
  7938. * @param {String} name - The name of the property the node refers to.
  7939. * @param {String} type - The uniform type that should be used to represent the property value.
  7940. * @param {Object} object - The object the property belongs to.
  7941. * @returns {ReferenceNode}
  7942. */
  7943. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  7944. /**
  7945. * TSL function for creating a reference node. Use this function if you want need a reference
  7946. * to an array-like property that should be represented as a uniform buffer.
  7947. *
  7948. * @function
  7949. * @param {String} name - The name of the property the node refers to.
  7950. * @param {String} type - The uniform type that should be used to represent the property value.
  7951. * @param {Number} count - The number of value inside the array-like object.
  7952. * @param {Object} object - An array-like object the property belongs to.
  7953. * @returns {ReferenceNode}
  7954. */
  7955. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  7956. /** @module MaterialReferenceNode **/
  7957. /**
  7958. * This node is a special type of reference node which is intended
  7959. * for linking material properties with node values.
  7960. * ```js
  7961. * const opacityNode = materialReference( 'opacity', 'float', material );
  7962. * ```
  7963. * When changing `material.opacity`, the node value of `opacityNode` will
  7964. * automatically be updated.
  7965. *
  7966. * @augments module:ReferenceNode~ReferenceNode
  7967. */
  7968. class MaterialReferenceNode extends ReferenceNode {
  7969. static get type() {
  7970. return 'MaterialReferenceNode';
  7971. }
  7972. /**
  7973. * Constructs a new material reference node.
  7974. *
  7975. * @param {String} property - The name of the property the node refers to.
  7976. * @param {String} inputType - The uniform type that should be used to represent the property value.
  7977. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  7978. * the node refers to the material of the current rendered object.
  7979. */
  7980. constructor( property, inputType, material = null ) {
  7981. super( property, inputType, material );
  7982. /**
  7983. * The material the property belongs to. When no material is set,
  7984. * the node refers to the material of the current rendered object.
  7985. *
  7986. * @type {Material?}
  7987. * @default null
  7988. */
  7989. this.material = material;
  7990. /**
  7991. * This flag can be used for type testing.
  7992. *
  7993. * @type {Boolean}
  7994. * @readonly
  7995. * @default true
  7996. */
  7997. this.isMaterialReferenceNode = true;
  7998. }
  7999. /**
  8000. * Updates the reference based on the given state. The state is only evaluated
  8001. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8002. *
  8003. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8004. * @return {Object} The updated reference.
  8005. */
  8006. updateReference( state ) {
  8007. this.reference = this.material !== null ? this.material : state.material;
  8008. return this.reference;
  8009. }
  8010. }
  8011. /**
  8012. * TSL function for creating a material reference node.
  8013. *
  8014. * @function
  8015. * @param {String} name - The name of the property the node refers to.
  8016. * @param {String} type - The uniform type that should be used to represent the property value.
  8017. * @param {Material?} [material=null] - The material the property belongs to.
  8018. * When no material is set, the node refers to the material of the current rendered object.
  8019. * @returns {MaterialReferenceNode}
  8020. */
  8021. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8022. /** @module Tangent **/
  8023. /**
  8024. * TSL object that represents the tangent attribute of the current rendered object.
  8025. *
  8026. * @type {Node<vec4>}
  8027. */
  8028. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8029. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8030. builder.geometry.computeTangents();
  8031. }
  8032. return attribute( 'tangent', 'vec4' );
  8033. } )();
  8034. /**
  8035. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8036. *
  8037. * @type {Node<vec3>}
  8038. */
  8039. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8040. /**
  8041. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8042. *
  8043. * @type {Node<vec3>}
  8044. */
  8045. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8046. /**
  8047. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8048. *
  8049. * @type {Node<vec3>}
  8050. */
  8051. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8052. /**
  8053. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8054. *
  8055. * @type {Node<vec3>}
  8056. */
  8057. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8058. /**
  8059. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8060. *
  8061. * @type {Node<vec3>}
  8062. */
  8063. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8064. /** @module Bitangent **/
  8065. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8066. /**
  8067. * TSL object that represents the bitangent attribute of the current rendered object.
  8068. *
  8069. * @type {Node<vec3>}
  8070. */
  8071. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8072. /**
  8073. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8074. *
  8075. * @type {Node<vec3>}
  8076. */
  8077. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8078. /**
  8079. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8080. *
  8081. * @type {Node<vec4>}
  8082. */
  8083. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8084. /**
  8085. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8086. *
  8087. * @type {Node<vec4>}
  8088. */
  8089. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8090. /**
  8091. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8092. *
  8093. * @type {Node<vec4>}
  8094. */
  8095. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8096. /**
  8097. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8098. *
  8099. * @type {Node<vec4>}
  8100. */
  8101. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8102. /** @module AccessorsUtils **/
  8103. /**
  8104. * TSL object that represents the TBN matrix in view space.
  8105. *
  8106. * @type {Node<mat3>}
  8107. */
  8108. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8109. /**
  8110. * TSL object that represents the parallax direction.
  8111. *
  8112. * @type {Node<mat3>}
  8113. */
  8114. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8115. /**
  8116. * TSL function for computing parallax uv coordinates.
  8117. *
  8118. * @function
  8119. * @param {Node<vec2>} uv - A uv node.
  8120. * @param {Node<vec2>} scale - A scale node.
  8121. * @returns {Node<vec2>} Parallax uv coordinates.
  8122. */
  8123. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8124. /**
  8125. * TSL function for computing bent normals.
  8126. *
  8127. * @function
  8128. * @returns {Node<vec3>} Bent normals.
  8129. */
  8130. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8131. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8132. let bentNormal = anisotropyB.cross( positionViewDirection );
  8133. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8134. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8135. return bentNormal;
  8136. } )();
  8137. /** @module NormalMapNode **/
  8138. // Normal Mapping Without Precomputed Tangents
  8139. // http://www.thetenthplanet.de/archives/1180
  8140. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8141. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8142. const q0 = eye_pos.dFdx();
  8143. const q1 = eye_pos.dFdy();
  8144. const st0 = uv.dFdx();
  8145. const st1 = uv.dFdy();
  8146. const N = surf_norm; // normalized
  8147. const q1perp = q1.cross( N );
  8148. const q0perp = N.cross( q0 );
  8149. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8150. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8151. const det = T.dot( T ).max( B.dot( B ) );
  8152. const scale = faceDirection.mul( det.inverseSqrt() );
  8153. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8154. } );
  8155. /**
  8156. * This class can be used for applying normals maps to materials.
  8157. *
  8158. * ```js
  8159. * material.normalNode = normalMap( texture( normalTex ) );
  8160. * ```
  8161. *
  8162. * @augments TempNode
  8163. */
  8164. class NormalMapNode extends TempNode {
  8165. static get type() {
  8166. return 'NormalMapNode';
  8167. }
  8168. /**
  8169. * Constructs a new normal map node.
  8170. *
  8171. * @param {Node} node - Represents the normal map data.
  8172. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8173. */
  8174. constructor( node, scaleNode = null ) {
  8175. super( 'vec3' );
  8176. /**
  8177. * Represents the normal map data.
  8178. *
  8179. * @type {Node}
  8180. */
  8181. this.node = node;
  8182. /**
  8183. * Controls the intensity of the effect.
  8184. *
  8185. * @type {Node?}
  8186. * @default null
  8187. */
  8188. this.scaleNode = scaleNode;
  8189. /**
  8190. * The normal map type.
  8191. *
  8192. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8193. * @default TangentSpaceNormalMap
  8194. */
  8195. this.normalMapType = TangentSpaceNormalMap;
  8196. }
  8197. setup( builder ) {
  8198. const { normalMapType, scaleNode } = this;
  8199. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8200. if ( scaleNode !== null ) {
  8201. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8202. }
  8203. let outputNode = null;
  8204. if ( normalMapType === ObjectSpaceNormalMap ) {
  8205. outputNode = transformNormalToView( normalMap );
  8206. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8207. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8208. if ( tangent === true ) {
  8209. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8210. } else {
  8211. outputNode = perturbNormal2Arb( {
  8212. eye_pos: positionView,
  8213. surf_norm: normalView,
  8214. mapN: normalMap,
  8215. uv: uv()
  8216. } );
  8217. }
  8218. }
  8219. return outputNode;
  8220. }
  8221. }
  8222. /**
  8223. * TSL function for creating a normal map node.
  8224. *
  8225. * @function
  8226. * @param {Node} node - Represents the normal map data.
  8227. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8228. * @returns {NormalMapNode}
  8229. */
  8230. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8231. /** @module BumpMapNode **/
  8232. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8233. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8234. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8235. // It's used to preserve the same TextureNode instance
  8236. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8237. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8238. return vec2(
  8239. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8240. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8241. ).mul( bumpScale );
  8242. } );
  8243. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8244. const perturbNormalArb = Fn( ( inputs ) => {
  8245. const { surf_pos, surf_norm, dHdxy } = inputs;
  8246. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8247. const vSigmaX = surf_pos.dFdx().normalize();
  8248. const vSigmaY = surf_pos.dFdy().normalize();
  8249. const vN = surf_norm; // normalized
  8250. const R1 = vSigmaY.cross( vN );
  8251. const R2 = vN.cross( vSigmaX );
  8252. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8253. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8254. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8255. } );
  8256. /**
  8257. * This class can be used for applying bump maps to materials.
  8258. *
  8259. * ```js
  8260. * material.normalNode = bumpMap( texture( bumpTex ) );
  8261. * ```
  8262. *
  8263. * @augments TempNode
  8264. */
  8265. class BumpMapNode extends TempNode {
  8266. static get type() {
  8267. return 'BumpMapNode';
  8268. }
  8269. /**
  8270. * Constructs a new bump map node.
  8271. *
  8272. * @param {Node} textureNode - Represents the bump map data.
  8273. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8274. */
  8275. constructor( textureNode, scaleNode = null ) {
  8276. super( 'vec3' );
  8277. /**
  8278. * Represents the bump map data.
  8279. *
  8280. * @type {Node}
  8281. */
  8282. this.textureNode = textureNode;
  8283. /**
  8284. * Controls the intensity of the bump effect.
  8285. *
  8286. * @type {Node?}
  8287. * @default null
  8288. */
  8289. this.scaleNode = scaleNode;
  8290. }
  8291. setup() {
  8292. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8293. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8294. return perturbNormalArb( {
  8295. surf_pos: positionView,
  8296. surf_norm: normalView,
  8297. dHdxy
  8298. } );
  8299. }
  8300. }
  8301. /**
  8302. * TSL function for creating a bump map node.
  8303. *
  8304. * @function
  8305. * @param {Node} textureNode - Represents the bump map data.
  8306. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8307. * @returns {BumpMapNode}
  8308. */
  8309. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8310. /** @module MaterialNode **/
  8311. const _propertyCache = new Map();
  8312. /**
  8313. * This class should simplify the node access to material properties.
  8314. * It internal uses reference nodes to make sure changes to material
  8315. * properties are automatically reflected to predefined TSL objects
  8316. * like e.g. `materialColor`.
  8317. *
  8318. * @augments Node
  8319. */
  8320. class MaterialNode extends Node {
  8321. static get type() {
  8322. return 'MaterialNode';
  8323. }
  8324. /**
  8325. * Constructs a new material node.
  8326. *
  8327. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8328. */
  8329. constructor( scope ) {
  8330. super();
  8331. /**
  8332. * The scope defines what material property is referred by the node.
  8333. *
  8334. * @type {String}
  8335. */
  8336. this.scope = scope;
  8337. }
  8338. /**
  8339. * Returns a cached reference node for the given property and type.
  8340. *
  8341. * @param {String} property - The name of the material property.
  8342. * @param {String} type - The uniform type of the property.
  8343. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8344. */
  8345. getCache( property, type ) {
  8346. let node = _propertyCache.get( property );
  8347. if ( node === undefined ) {
  8348. node = materialReference( property, type );
  8349. _propertyCache.set( property, node );
  8350. }
  8351. return node;
  8352. }
  8353. /**
  8354. * Returns a float-typed material reference node for the given property name.
  8355. *
  8356. * @param {String} property - The name of the material property.
  8357. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8358. */
  8359. getFloat( property ) {
  8360. return this.getCache( property, 'float' );
  8361. }
  8362. /**
  8363. * Returns a color-typed material reference node for the given property name.
  8364. *
  8365. * @param {String} property - The name of the material property.
  8366. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8367. */
  8368. getColor( property ) {
  8369. return this.getCache( property, 'color' );
  8370. }
  8371. /**
  8372. * Returns a texture-typed material reference node for the given property name.
  8373. *
  8374. * @param {String} property - The name of the material property.
  8375. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8376. */
  8377. getTexture( property ) {
  8378. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8379. }
  8380. /**
  8381. * The node setup is done depending on the selected scope. Multiple material properties
  8382. * might be grouped into a single node composition if they logically belong together.
  8383. *
  8384. * @param {NodeBuilder} builder - The current node builder.
  8385. * @return {Node} The node representing the selected scope.
  8386. */
  8387. setup( builder ) {
  8388. const material = builder.context.material;
  8389. const scope = this.scope;
  8390. let node = null;
  8391. if ( scope === MaterialNode.COLOR ) {
  8392. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8393. if ( material.map && material.map.isTexture === true ) {
  8394. node = colorNode.mul( this.getTexture( 'map' ) );
  8395. } else {
  8396. node = colorNode;
  8397. }
  8398. } else if ( scope === MaterialNode.OPACITY ) {
  8399. const opacityNode = this.getFloat( scope );
  8400. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8401. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8402. } else {
  8403. node = opacityNode;
  8404. }
  8405. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8406. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8407. node = this.getTexture( 'specular' ).r;
  8408. } else {
  8409. node = float( 1 );
  8410. }
  8411. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8412. const specularIntensityNode = this.getFloat( scope );
  8413. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8414. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8415. } else {
  8416. node = specularIntensityNode;
  8417. }
  8418. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8419. const specularColorNode = this.getColor( scope );
  8420. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8421. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8422. } else {
  8423. node = specularColorNode;
  8424. }
  8425. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8426. const roughnessNode = this.getFloat( scope );
  8427. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8428. node = roughnessNode.mul( this.getTexture( scope ).g );
  8429. } else {
  8430. node = roughnessNode;
  8431. }
  8432. } else if ( scope === MaterialNode.METALNESS ) {
  8433. const metalnessNode = this.getFloat( scope );
  8434. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8435. node = metalnessNode.mul( this.getTexture( scope ).b );
  8436. } else {
  8437. node = metalnessNode;
  8438. }
  8439. } else if ( scope === MaterialNode.EMISSIVE ) {
  8440. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8441. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8442. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8443. node = emissiveNode.mul( this.getTexture( scope ) );
  8444. } else {
  8445. node = emissiveNode;
  8446. }
  8447. } else if ( scope === MaterialNode.NORMAL ) {
  8448. if ( material.normalMap ) {
  8449. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8450. node.normalMapType = material.normalMapType;
  8451. } else if ( material.bumpMap ) {
  8452. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8453. } else {
  8454. node = normalView;
  8455. }
  8456. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8457. const clearcoatNode = this.getFloat( scope );
  8458. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8459. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8460. } else {
  8461. node = clearcoatNode;
  8462. }
  8463. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8464. const clearcoatRoughnessNode = this.getFloat( scope );
  8465. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8466. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8467. } else {
  8468. node = clearcoatRoughnessNode;
  8469. }
  8470. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8471. if ( material.clearcoatNormalMap ) {
  8472. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8473. } else {
  8474. node = normalView;
  8475. }
  8476. } else if ( scope === MaterialNode.SHEEN ) {
  8477. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8478. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8479. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8480. } else {
  8481. node = sheenNode;
  8482. }
  8483. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8484. const sheenRoughnessNode = this.getFloat( scope );
  8485. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8486. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8487. } else {
  8488. node = sheenRoughnessNode;
  8489. }
  8490. node = node.clamp( 0.07, 1.0 );
  8491. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8492. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8493. const anisotropyPolar = this.getTexture( scope );
  8494. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8495. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8496. } else {
  8497. node = materialAnisotropyVector;
  8498. }
  8499. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8500. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8501. if ( material.iridescenceThicknessMap ) {
  8502. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8503. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8504. } else {
  8505. node = iridescenceThicknessMaximum;
  8506. }
  8507. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8508. const transmissionNode = this.getFloat( scope );
  8509. if ( material.transmissionMap ) {
  8510. node = transmissionNode.mul( this.getTexture( scope ).r );
  8511. } else {
  8512. node = transmissionNode;
  8513. }
  8514. } else if ( scope === MaterialNode.THICKNESS ) {
  8515. const thicknessNode = this.getFloat( scope );
  8516. if ( material.thicknessMap ) {
  8517. node = thicknessNode.mul( this.getTexture( scope ).g );
  8518. } else {
  8519. node = thicknessNode;
  8520. }
  8521. } else if ( scope === MaterialNode.IOR ) {
  8522. node = this.getFloat( scope );
  8523. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8524. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8525. } else if ( scope === MaterialNode.AO ) {
  8526. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8527. } else {
  8528. const outputType = this.getNodeType( builder );
  8529. node = this.getCache( scope, outputType );
  8530. }
  8531. return node;
  8532. }
  8533. }
  8534. MaterialNode.ALPHA_TEST = 'alphaTest';
  8535. MaterialNode.COLOR = 'color';
  8536. MaterialNode.OPACITY = 'opacity';
  8537. MaterialNode.SHININESS = 'shininess';
  8538. MaterialNode.SPECULAR = 'specular';
  8539. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8540. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8541. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8542. MaterialNode.REFLECTIVITY = 'reflectivity';
  8543. MaterialNode.ROUGHNESS = 'roughness';
  8544. MaterialNode.METALNESS = 'metalness';
  8545. MaterialNode.NORMAL = 'normal';
  8546. MaterialNode.CLEARCOAT = 'clearcoat';
  8547. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8548. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8549. MaterialNode.EMISSIVE = 'emissive';
  8550. MaterialNode.ROTATION = 'rotation';
  8551. MaterialNode.SHEEN = 'sheen';
  8552. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8553. MaterialNode.ANISOTROPY = 'anisotropy';
  8554. MaterialNode.IRIDESCENCE = 'iridescence';
  8555. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8556. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8557. MaterialNode.IOR = 'ior';
  8558. MaterialNode.TRANSMISSION = 'transmission';
  8559. MaterialNode.THICKNESS = 'thickness';
  8560. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8561. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8562. MaterialNode.LINE_SCALE = 'scale';
  8563. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8564. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8565. MaterialNode.LINE_WIDTH = 'linewidth';
  8566. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8567. MaterialNode.POINT_WIDTH = 'pointWidth';
  8568. MaterialNode.DISPERSION = 'dispersion';
  8569. MaterialNode.LIGHT_MAP = 'light';
  8570. MaterialNode.AO = 'ao';
  8571. /**
  8572. * TSL object that represents alpha test of the current material.
  8573. *
  8574. * @type {Node<float>}
  8575. */
  8576. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8577. /**
  8578. * TSL object that represents the diffuse color of the current material.
  8579. * The value is composed via `color` * `map`.
  8580. *
  8581. * @type {Node<vec3>}
  8582. */
  8583. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8584. /**
  8585. * TSL object that represents the shininess of the current material.
  8586. *
  8587. * @type {Node<float>}
  8588. */
  8589. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8590. /**
  8591. * TSL object that represents the emissive color of the current material.
  8592. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8593. *
  8594. * @type {Node<vec3>}
  8595. */
  8596. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8597. /**
  8598. * TSL object that represents the opacity of the current material.
  8599. * The value is composed via `opacity` * `alphaMap`.
  8600. *
  8601. * @type {Node<float>}
  8602. */
  8603. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8604. /**
  8605. * TSL object that represents the specular of the current material.
  8606. *
  8607. * @type {Node<vec3>}
  8608. */
  8609. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8610. /**
  8611. * TSL object that represents the specular intensity of the current material.
  8612. * The value is composed via `specularIntensity` * `specularMap.a`.
  8613. *
  8614. * @type {Node<float>}
  8615. */
  8616. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8617. /**
  8618. * TSL object that represents the specular color of the current material.
  8619. * The value is composed via `specularColor` * `specularMap.rgb`.
  8620. *
  8621. * @type {Node<vec3>}
  8622. */
  8623. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8624. /**
  8625. * TSL object that represents the specular strength of the current material.
  8626. * The value is composed via `specularMap.r`.
  8627. *
  8628. * @type {Node<float>}
  8629. */
  8630. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8631. /**
  8632. * TSL object that represents the reflectivity of the current material.
  8633. *
  8634. * @type {Node<float>}
  8635. */
  8636. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8637. /**
  8638. * TSL object that represents the roughness of the current material.
  8639. * The value is composed via `roughness` * `roughnessMap.g`
  8640. *
  8641. * @type {Node<float>}
  8642. */
  8643. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8644. /**
  8645. * TSL object that represents the metalness of the current material.
  8646. * The value is composed via `metalness` * `metalnessMap.b`
  8647. *
  8648. * @type {Node<float>}
  8649. */
  8650. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8651. /**
  8652. * TSL object that represents the normal of the current material.
  8653. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8654. *
  8655. * @type {Node<vec3>}
  8656. */
  8657. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  8658. /**
  8659. * TSL object that represents the clearcoat of the current material.
  8660. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8661. *
  8662. * @type {Node<float>}
  8663. */
  8664. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8665. /**
  8666. * TSL object that represents the clearcoat roughness of the current material.
  8667. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`
  8668. *
  8669. * @type {Node<float>}
  8670. */
  8671. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8672. /**
  8673. * TSL object that represents the clearcoat normal of the current material.
  8674. * The value will be either `clearcoatNormalMap` or `normalView`.
  8675. *
  8676. * @type {Node<vec3>}
  8677. */
  8678. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  8679. /**
  8680. * TSL object that represents the rotation of the current sprite material.
  8681. *
  8682. * @type {Node<float>}
  8683. */
  8684. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8685. /**
  8686. * TSL object that represents the sheen color of the current material.
  8687. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8688. *
  8689. * @type {Node<vec3>}
  8690. */
  8691. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8692. /**
  8693. * TSL object that represents the sheen roughness of the current material.
  8694. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a` .
  8695. *
  8696. * @type {Node<float>}
  8697. */
  8698. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8699. /**
  8700. * TSL object that represents the anisotropy of the current material.
  8701. *
  8702. * @type {Node<vec2>}
  8703. */
  8704. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8705. /**
  8706. * TSL object that represents the iridescence of the current material.
  8707. *
  8708. * @type {Node<float>}
  8709. */
  8710. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8711. /**
  8712. * TSL object that represents the iridescence IOR of the current material.
  8713. *
  8714. * @type {Node<float>}
  8715. */
  8716. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8717. /**
  8718. * TSL object that represents the iridescence thickness of the current material.
  8719. *
  8720. * @type {Node<float>}
  8721. */
  8722. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8723. /**
  8724. * TSL object that represents the transmission of the current material.
  8725. * The value is composed via `transmission` * `transmissionMap.r`.
  8726. *
  8727. * @type {Node<float>}
  8728. */
  8729. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8730. /**
  8731. * TSL object that represents the thickness of the current material.
  8732. * The value is composed via `thickness` * `thicknessMap.g`.
  8733. *
  8734. * @type {Node<float>}
  8735. */
  8736. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8737. /**
  8738. * TSL object that represents the IOR of the current material.
  8739. *
  8740. * @type {Node<float>}
  8741. */
  8742. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8743. /**
  8744. * TSL object that represents the attenuation distance of the current material.
  8745. *
  8746. * @type {Node<float>}
  8747. */
  8748. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8749. /**
  8750. * TSL object that represents the attenuation color of the current material.
  8751. *
  8752. * @type {Node<vec3>}
  8753. */
  8754. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8755. /**
  8756. * TSL object that represents the scale of the current dashed line material.
  8757. *
  8758. * @type {Node<float>}
  8759. */
  8760. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8761. /**
  8762. * TSL object that represents the dash size of the current dashed line material.
  8763. *
  8764. * @type {Node<float>}
  8765. */
  8766. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8767. /**
  8768. * TSL object that represents the gap size of the current dashed line material.
  8769. *
  8770. * @type {Node<float>}
  8771. */
  8772. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8773. /**
  8774. * TSL object that represents the line width of the current line material.
  8775. *
  8776. * @type {Node<float>}
  8777. */
  8778. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8779. /**
  8780. * TSL object that represents the dash offset of the current line material.
  8781. *
  8782. * @type {Node<float>}
  8783. */
  8784. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8785. /**
  8786. * TSL object that represents the point width of the current points material.
  8787. *
  8788. * @type {Node<float>}
  8789. */
  8790. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  8791. /**
  8792. * TSL object that represents the dispersion of the current material.
  8793. *
  8794. * @type {Node<float>}
  8795. */
  8796. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  8797. /**
  8798. * TSL object that represents the light map of the current material.
  8799. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  8800. *
  8801. * @type {Node<vec3>}
  8802. */
  8803. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  8804. /**
  8805. * TSL object that represents the ambient occlusion map of the current material.
  8806. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  8807. *
  8808. * @type {Node<float>}
  8809. */
  8810. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  8811. /**
  8812. * TSL object that represents the anisotropy vector of the current material.
  8813. *
  8814. * @type {Node<vec2>}
  8815. */
  8816. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  8817. return frame.material;
  8818. } ).onRenderUpdate( function ( { material } ) {
  8819. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  8820. } );
  8821. /** @module ModelViewProjectionNode **/
  8822. /**
  8823. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  8824. *
  8825. * @type {VaryingNode<vec4>}
  8826. */
  8827. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8828. return builder.context.setupModelViewProjection();
  8829. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  8830. /** @module IndexNode **/
  8831. /**
  8832. * This class represents shader indices of different types. The following predefined node
  8833. * objects cover frequent use cases:
  8834. *
  8835. * - `vertexIndex`: The index of a vertex within a mesh.
  8836. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  8837. * - `drawIndex`: The index of a draw call.
  8838. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  8839. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  8840. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  8841. *
  8842. * @augments Node
  8843. */
  8844. class IndexNode extends Node {
  8845. static get type() {
  8846. return 'IndexNode';
  8847. }
  8848. /**
  8849. * Constructs a new index node.
  8850. *
  8851. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  8852. */
  8853. constructor( scope ) {
  8854. super( 'uint' );
  8855. /**
  8856. * The scope of the index node.
  8857. *
  8858. * @type {String}
  8859. */
  8860. this.scope = scope;
  8861. /**
  8862. * This flag can be used for type testing.
  8863. *
  8864. * @type {Boolean}
  8865. * @readonly
  8866. * @default true
  8867. */
  8868. this.isIndexNode = true;
  8869. }
  8870. generate( builder ) {
  8871. const nodeType = this.getNodeType( builder );
  8872. const scope = this.scope;
  8873. let propertyName;
  8874. if ( scope === IndexNode.VERTEX ) {
  8875. propertyName = builder.getVertexIndex();
  8876. } else if ( scope === IndexNode.INSTANCE ) {
  8877. propertyName = builder.getInstanceIndex();
  8878. } else if ( scope === IndexNode.DRAW ) {
  8879. propertyName = builder.getDrawIndex();
  8880. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  8881. propertyName = builder.getInvocationLocalIndex();
  8882. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  8883. propertyName = builder.getInvocationSubgroupIndex();
  8884. } else if ( scope === IndexNode.SUBGROUP ) {
  8885. propertyName = builder.getSubgroupIndex();
  8886. } else {
  8887. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  8888. }
  8889. let output;
  8890. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  8891. output = propertyName;
  8892. } else {
  8893. const nodeVarying = varying( this );
  8894. output = nodeVarying.build( builder, nodeType );
  8895. }
  8896. return output;
  8897. }
  8898. }
  8899. IndexNode.VERTEX = 'vertex';
  8900. IndexNode.INSTANCE = 'instance';
  8901. IndexNode.SUBGROUP = 'subgroup';
  8902. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  8903. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  8904. IndexNode.DRAW = 'draw';
  8905. /**
  8906. * TSL object that represents the index of a vertex within a mesh.
  8907. *
  8908. * @type {IndexNode}
  8909. */
  8910. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  8911. /**
  8912. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  8913. *
  8914. * @type {IndexNode}
  8915. */
  8916. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  8917. /**
  8918. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  8919. *
  8920. * @type {IndexNode}
  8921. */
  8922. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  8923. /**
  8924. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  8925. *
  8926. * @type {IndexNode}
  8927. */
  8928. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  8929. /**
  8930. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  8931. *
  8932. * @type {IndexNode}
  8933. */
  8934. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  8935. /**
  8936. * TSL object that represents the index of a draw call.
  8937. *
  8938. * @type {IndexNode}
  8939. */
  8940. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  8941. /** @module InstanceNode **/
  8942. /**
  8943. * This node implements the vertex shader logic which is required
  8944. * when rendering 3D objects via instancing. The code makes sure
  8945. * vertex positions, normals and colors can be modified via instanced
  8946. * data.
  8947. *
  8948. * @augments Node
  8949. */
  8950. class InstanceNode extends Node {
  8951. static get type() {
  8952. return 'InstanceNode';
  8953. }
  8954. /**
  8955. * Constructs a new instance node.
  8956. *
  8957. * @param {Number} count - The number of instances.
  8958. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  8959. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  8960. */
  8961. constructor( count, instanceMatrix, instanceColor ) {
  8962. super( 'void' );
  8963. /**
  8964. * The number of instances.
  8965. *
  8966. * @type {Number}
  8967. */
  8968. this.count = count;
  8969. /**
  8970. * Instanced buffer attribute representing the transformation of instances.
  8971. *
  8972. * @type {InstancedBufferAttribute}
  8973. */
  8974. this.instanceMatrix = instanceMatrix;
  8975. /**
  8976. * Instanced buffer attribute representing the color of instances.
  8977. *
  8978. * @type {InstancedBufferAttribute}
  8979. */
  8980. this.instanceColor = instanceColor;
  8981. /**
  8982. * The node that represents the instance matrix data.
  8983. *
  8984. * @type {Node}
  8985. */
  8986. this.instanceMatrixNode = null;
  8987. /**
  8988. * The node that represents the instance color data.
  8989. *
  8990. * @type {Node}
  8991. */
  8992. this.instanceColorNode = null;
  8993. /**
  8994. * The update type is set to `frame` since an update
  8995. * of instanced buffer data must be checked per frame.
  8996. *
  8997. * @type {String}
  8998. * @default 'frame'
  8999. */
  9000. this.updateType = NodeUpdateType.FRAME;
  9001. /**
  9002. * A reference to a buffer that is used by `instanceMatrixNode`.
  9003. *
  9004. * @type {InstancedInterleavedBuffer}
  9005. */
  9006. this.buffer = null;
  9007. /**
  9008. * A reference to a buffer that is used by `instanceColorNode`.
  9009. *
  9010. * @type {InstancedInterleavedBuffer}
  9011. */
  9012. this.bufferColor = null;
  9013. }
  9014. /**
  9015. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9016. * to predefined node variables for accumulation. That follows the same patterns
  9017. * like with morph and skinning nodes.
  9018. *
  9019. * @param {NodeBuilder} builder - The current node builder.
  9020. */
  9021. setup( builder ) {
  9022. const { count, instanceMatrix, instanceColor } = this;
  9023. let { instanceMatrixNode, instanceColorNode } = this;
  9024. if ( instanceMatrixNode === null ) {
  9025. // 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.
  9026. if ( count <= 1000 ) {
  9027. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9028. } else {
  9029. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9030. this.buffer = buffer;
  9031. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9032. const instanceBuffers = [
  9033. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9034. bufferFn( buffer, 'vec4', 16, 0 ),
  9035. bufferFn( buffer, 'vec4', 16, 4 ),
  9036. bufferFn( buffer, 'vec4', 16, 8 ),
  9037. bufferFn( buffer, 'vec4', 16, 12 )
  9038. ];
  9039. instanceMatrixNode = mat4( ...instanceBuffers );
  9040. }
  9041. this.instanceMatrixNode = instanceMatrixNode;
  9042. }
  9043. if ( instanceColor && instanceColorNode === null ) {
  9044. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9045. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9046. this.bufferColor = buffer;
  9047. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9048. this.instanceColorNode = instanceColorNode;
  9049. }
  9050. // POSITION
  9051. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9052. positionLocal.assign( instancePosition );
  9053. // NORMAL
  9054. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9055. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9056. // ASSIGNS
  9057. normalLocal.assign( instanceNormal );
  9058. }
  9059. // COLOR
  9060. if ( this.instanceColorNode !== null ) {
  9061. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9062. }
  9063. }
  9064. /**
  9065. * Checks if the internal buffers required an update.
  9066. *
  9067. * @param {NodeFrame} frame - The current node frame.
  9068. */
  9069. update( /*frame*/ ) {
  9070. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9071. this.buffer.version = this.instanceMatrix.version;
  9072. }
  9073. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9074. this.bufferColor.version = this.instanceColor.version;
  9075. }
  9076. }
  9077. }
  9078. /**
  9079. * TSL function for creating an instance node.
  9080. *
  9081. * @function
  9082. * @param {Number} count - The number of instances.
  9083. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9084. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9085. * @returns {InstanceNode}
  9086. */
  9087. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9088. /** @module InstancedMeshNode **/
  9089. /**
  9090. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9091. * It allows an easier setup of the instance node.
  9092. *
  9093. * @augments module:InstanceNode~InstanceNode
  9094. */
  9095. class InstancedMeshNode extends InstanceNode {
  9096. static get type() {
  9097. return 'InstancedMeshNode';
  9098. }
  9099. /**
  9100. * Constructs a new instanced mesh node.
  9101. *
  9102. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9103. */
  9104. constructor( instancedMesh ) {
  9105. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9106. super( count, instanceMatrix, instanceColor );
  9107. /**
  9108. * A reference to the instanced mesh.
  9109. *
  9110. * @type {InstancedMesh}
  9111. */
  9112. this.instancedMesh = instancedMesh;
  9113. }
  9114. }
  9115. /**
  9116. * TSL function for creating an instanced mesh node.
  9117. *
  9118. * @function
  9119. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9120. * @returns {InstancedMeshNode}
  9121. */
  9122. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9123. /** @module BatchNode **/
  9124. /**
  9125. * This node implements the vertex shader logic which is required
  9126. * when rendering 3D objects via batching. `BatchNode` must be used
  9127. * with instances of {@link BatchedMesh}.
  9128. *
  9129. * @augments Node
  9130. */
  9131. class BatchNode extends Node {
  9132. static get type() {
  9133. return 'BatchNode';
  9134. }
  9135. /**
  9136. * Constructs a new batch node.
  9137. *
  9138. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9139. */
  9140. constructor( batchMesh ) {
  9141. super( 'void' );
  9142. /**
  9143. * A reference to batched mesh.
  9144. *
  9145. * @type {BatchedMesh}
  9146. */
  9147. this.batchMesh = batchMesh;
  9148. /**
  9149. * The batching index node.
  9150. *
  9151. * @type {IndexNode?}
  9152. * @default null
  9153. */
  9154. this.batchingIdNode = null;
  9155. }
  9156. /**
  9157. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9158. * to predefined node variables for accumulation. That follows the same patterns
  9159. * like with morph and skinning nodes.
  9160. *
  9161. * @param {NodeBuilder} builder - The current node builder.
  9162. */
  9163. setup( builder ) {
  9164. if ( this.batchingIdNode === null ) {
  9165. if ( builder.getDrawIndex() === null ) {
  9166. this.batchingIdNode = instanceIndex;
  9167. } else {
  9168. this.batchingIdNode = drawIndex;
  9169. }
  9170. }
  9171. const getIndirectIndex = Fn( ( [ id ] ) => {
  9172. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9173. const x = int( id ).modInt( int( size ) );
  9174. const y = int( id ).div( int( size ) );
  9175. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9176. } ).setLayout( {
  9177. name: 'getIndirectIndex',
  9178. type: 'uint',
  9179. inputs: [
  9180. { name: 'id', type: 'int' }
  9181. ]
  9182. } );
  9183. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9184. const matricesTexture = this.batchMesh._matricesTexture;
  9185. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9186. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9187. const x = j.modInt( size );
  9188. const y = j.div( int( size ) );
  9189. const batchingMatrix = mat4(
  9190. textureLoad( matricesTexture, ivec2( x, y ) ),
  9191. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9192. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9193. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9194. );
  9195. const colorsTexture = this.batchMesh._colorsTexture;
  9196. if ( colorsTexture !== null ) {
  9197. const getBatchingColor = Fn( ( [ id ] ) => {
  9198. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9199. const j = id;
  9200. const x = j.modInt( size );
  9201. const y = j.div( size );
  9202. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9203. } ).setLayout( {
  9204. name: 'getBatchingColor',
  9205. type: 'vec3',
  9206. inputs: [
  9207. { name: 'id', type: 'int' }
  9208. ]
  9209. } );
  9210. const color = getBatchingColor( indirectId );
  9211. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9212. }
  9213. const bm = mat3( batchingMatrix );
  9214. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9215. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9216. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9217. normalLocal.assign( batchingNormal );
  9218. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9219. tangentLocal.mulAssign( bm );
  9220. }
  9221. }
  9222. }
  9223. /**
  9224. * TSL function for creating a batch node.
  9225. *
  9226. * @function
  9227. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9228. * @returns {BatchNode}
  9229. */
  9230. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9231. /** @module SkinningNode **/
  9232. const _frameId = new WeakMap();
  9233. /**
  9234. * This node implements the vertex transformation shader logic which is required
  9235. * for skinning/skeletal animation.
  9236. *
  9237. * @augments Node
  9238. */
  9239. class SkinningNode extends Node {
  9240. static get type() {
  9241. return 'SkinningNode';
  9242. }
  9243. /**
  9244. * Constructs a new skinning node.
  9245. *
  9246. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9247. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9248. */
  9249. constructor( skinnedMesh, useReference = false ) {
  9250. super( 'void' );
  9251. /**
  9252. * The skinned mesh.
  9253. *
  9254. * @type {SkinnedMesh}
  9255. */
  9256. this.skinnedMesh = skinnedMesh;
  9257. /**
  9258. * Whether to use reference nodes for internal skinned mesh related data or not.
  9259. * TODO: Explain the purpose of the property.
  9260. *
  9261. * @type {Boolean}
  9262. */
  9263. this.useReference = useReference;
  9264. /**
  9265. * The update type overwritten since skinning nodes are updated per object.
  9266. *
  9267. * @type {String}
  9268. */
  9269. this.updateType = NodeUpdateType.OBJECT;
  9270. //
  9271. /**
  9272. * The skin index attribute.
  9273. *
  9274. * @type {AttributeNode}
  9275. */
  9276. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9277. /**
  9278. * The skin weight attribute.
  9279. *
  9280. * @type {AttributeNode}
  9281. */
  9282. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9283. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9284. if ( useReference ) {
  9285. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9286. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9287. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9288. } else {
  9289. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9290. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9291. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9292. }
  9293. /**
  9294. * The bind matrix node.
  9295. *
  9296. * @type {Node<mat4>}
  9297. */
  9298. this.bindMatrixNode = bindMatrixNode;
  9299. /**
  9300. * The bind matrix inverse node.
  9301. *
  9302. * @type {Node<mat4>}
  9303. */
  9304. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9305. /**
  9306. * The bind matrices as a uniform buffer node.
  9307. *
  9308. * @type {Node}
  9309. */
  9310. this.boneMatricesNode = boneMatricesNode;
  9311. /**
  9312. * The previous bind matrices as a uniform buffer node.
  9313. * Required for computing motion vectors.
  9314. *
  9315. * @type {Node?}
  9316. * @default null
  9317. */
  9318. this.previousBoneMatricesNode = null;
  9319. }
  9320. /**
  9321. * Transforms the given vertex position via skinning.
  9322. *
  9323. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9324. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9325. * @return {Node<vec3>} The transformed vertex position.
  9326. */
  9327. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9328. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9329. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9330. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9331. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9332. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9333. // POSITION
  9334. const skinVertex = bindMatrixNode.mul( position );
  9335. const skinned = add(
  9336. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9337. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9338. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9339. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9340. );
  9341. return bindMatrixInverseNode.mul( skinned ).xyz;
  9342. }
  9343. /**
  9344. * Transforms the given vertex normal via skinning.
  9345. *
  9346. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9347. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9348. * @return {Node<vec3>} The transformed vertex normal.
  9349. */
  9350. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9351. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9352. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9353. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9354. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9355. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9356. // NORMAL
  9357. let skinMatrix = add(
  9358. skinWeightNode.x.mul( boneMatX ),
  9359. skinWeightNode.y.mul( boneMatY ),
  9360. skinWeightNode.z.mul( boneMatZ ),
  9361. skinWeightNode.w.mul( boneMatW )
  9362. );
  9363. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9364. return skinMatrix.transformDirection( normal ).xyz;
  9365. }
  9366. /**
  9367. * Transforms the given vertex normal via skinning.
  9368. *
  9369. * @param {NodeBuilder} builder - The current node builder.
  9370. * @return {Node<vec3>} The skinned position from the previous frame.
  9371. */
  9372. getPreviousSkinnedPosition( builder ) {
  9373. const skinnedMesh = builder.object;
  9374. if ( this.previousBoneMatricesNode === null ) {
  9375. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9376. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9377. }
  9378. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9379. }
  9380. /**
  9381. * Returns `true` if bone matrices from the previous frame are required.
  9382. *
  9383. * @param {NodeBuilder} builder - The current node builder.
  9384. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9385. */
  9386. needsPreviousBoneMatrices( builder ) {
  9387. const mrt = builder.renderer.getMRT();
  9388. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9389. }
  9390. /**
  9391. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9392. *
  9393. * @param {NodeBuilder} builder - The current node builder.
  9394. */
  9395. setup( builder ) {
  9396. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9397. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9398. }
  9399. const skinPosition = this.getSkinnedPosition();
  9400. positionLocal.assign( skinPosition );
  9401. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9402. const skinNormal = this.getSkinnedNormal();
  9403. normalLocal.assign( skinNormal );
  9404. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9405. tangentLocal.assign( skinNormal );
  9406. }
  9407. }
  9408. }
  9409. /**
  9410. * Generates the code snippet of the skinning node.
  9411. *
  9412. * @param {NodeBuilder} builder - The current node builder.
  9413. * @param {String} output - The current output.
  9414. * @return {String} The generated code snippet.
  9415. */
  9416. generate( builder, output ) {
  9417. if ( output !== 'void' ) {
  9418. return positionLocal.build( builder, output );
  9419. }
  9420. }
  9421. /**
  9422. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9423. *
  9424. * @param {NodeFrame} frame - The current node frame.
  9425. */
  9426. update( frame ) {
  9427. const object = this.useReference ? frame.object : this.skinnedMesh;
  9428. const skeleton = object.skeleton;
  9429. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9430. _frameId.set( skeleton, frame.frameId );
  9431. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9432. skeleton.update();
  9433. }
  9434. }
  9435. /**
  9436. * TSL function for creating a skinning node.
  9437. *
  9438. * @function
  9439. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9440. * @returns {SkinningNode}
  9441. */
  9442. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9443. /**
  9444. * TSL function for creating a skinning node with reference usage.
  9445. *
  9446. * @function
  9447. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9448. * @returns {SkinningNode}
  9449. */
  9450. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9451. /** @module LoopNode **/
  9452. /**
  9453. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9454. * ```js
  9455. * Loop( count, ( { i } ) => {
  9456. *
  9457. * } );
  9458. * ```
  9459. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9460. * ```js
  9461. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9462. *
  9463. * } );
  9464. *```
  9465. * Nested loops can be defined in a compacted form:
  9466. * ```js
  9467. * Loop( 10, 5, ( { i, j } ) => {
  9468. *
  9469. * } );
  9470. * ```
  9471. * Loops that should run backwards can be defined like so:
  9472. * ```js
  9473. * Loop( { start: 10 }, () => {} );
  9474. * ```
  9475. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9476. * @augments Node
  9477. */
  9478. class LoopNode extends Node {
  9479. static get type() {
  9480. return 'LoopNode';
  9481. }
  9482. /**
  9483. * Constructs a new loop node.
  9484. *
  9485. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9486. */
  9487. constructor( params = [] ) {
  9488. super();
  9489. this.params = params;
  9490. }
  9491. /**
  9492. * Returns a loop variable name based on an index. The pattern is
  9493. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9494. *
  9495. * @param {Number} index - The index.
  9496. * @return {String} The loop variable name.
  9497. */
  9498. getVarName( index ) {
  9499. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9500. }
  9501. /**
  9502. * Returns properties about this node.
  9503. *
  9504. * @param {NodeBuilder} builder - The current node builder.
  9505. * @return {Object} The node properties.
  9506. */
  9507. getProperties( builder ) {
  9508. const properties = builder.getNodeProperties( this );
  9509. if ( properties.stackNode !== undefined ) return properties;
  9510. //
  9511. const inputs = {};
  9512. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9513. const param = this.params[ i ];
  9514. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9515. const type = ( param.isNode !== true && param.type ) || 'int';
  9516. inputs[ name ] = expression( name, type );
  9517. }
  9518. const stack = builder.addStack(); // TODO: cache() it
  9519. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9520. properties.stackNode = stack;
  9521. builder.removeStack();
  9522. return properties;
  9523. }
  9524. /**
  9525. * This method is overwritten since the node type is inferred based on the loop configuration.
  9526. *
  9527. * @param {NodeBuilder} builder - The current node builder.
  9528. * @return {String} The node type.
  9529. */
  9530. getNodeType( builder ) {
  9531. const { returnsNode } = this.getProperties( builder );
  9532. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9533. }
  9534. setup( builder ) {
  9535. // setup properties
  9536. this.getProperties( builder );
  9537. }
  9538. generate( builder ) {
  9539. const properties = this.getProperties( builder );
  9540. const params = this.params;
  9541. const stackNode = properties.stackNode;
  9542. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9543. const param = params[ i ];
  9544. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9545. if ( param.isNode ) {
  9546. type = 'int';
  9547. name = this.getVarName( i );
  9548. start = '0';
  9549. end = param.build( builder, type );
  9550. condition = '<';
  9551. } else {
  9552. type = param.type || 'int';
  9553. name = param.name || this.getVarName( i );
  9554. start = param.start;
  9555. end = param.end;
  9556. condition = param.condition;
  9557. update = param.update;
  9558. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9559. else if ( start && start.isNode ) start = start.build( builder, type );
  9560. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9561. else if ( end && end.isNode ) end = end.build( builder, type );
  9562. if ( start !== undefined && end === undefined ) {
  9563. start = start + ' - 1';
  9564. end = '0';
  9565. condition = '>=';
  9566. } else if ( end !== undefined && start === undefined ) {
  9567. start = '0';
  9568. condition = '<';
  9569. }
  9570. if ( condition === undefined ) {
  9571. if ( Number( start ) > Number( end ) ) {
  9572. condition = '>=';
  9573. } else {
  9574. condition = '<';
  9575. }
  9576. }
  9577. }
  9578. const internalParam = { start, end, condition };
  9579. //
  9580. const startSnippet = internalParam.start;
  9581. const endSnippet = internalParam.end;
  9582. let declarationSnippet = '';
  9583. let conditionalSnippet = '';
  9584. let updateSnippet = '';
  9585. if ( ! update ) {
  9586. if ( type === 'int' || type === 'uint' ) {
  9587. if ( condition.includes( '<' ) ) update = '++';
  9588. else update = '--';
  9589. } else {
  9590. if ( condition.includes( '<' ) ) update = '+= 1.';
  9591. else update = '-= 1.';
  9592. }
  9593. }
  9594. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9595. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9596. updateSnippet += name + ' ' + update;
  9597. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9598. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9599. }
  9600. const stackSnippet = stackNode.build( builder, 'void' );
  9601. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9602. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9603. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9604. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9605. }
  9606. builder.addFlowTab();
  9607. return returnsSnippet;
  9608. }
  9609. }
  9610. /**
  9611. * TSL function for creating a loop node.
  9612. *
  9613. * @function
  9614. * @param {...Any} params - A list of parameters.
  9615. * @returns {LoopNode}
  9616. */
  9617. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9618. /**
  9619. * TSL function for creating a `Continue()` expression.
  9620. *
  9621. * @function
  9622. * @returns {ExpressionNode}
  9623. */
  9624. const Continue = () => expression( 'continue' ).append();
  9625. /**
  9626. * TSL function for creating a `Break()` expression.
  9627. *
  9628. * @function
  9629. * @returns {ExpressionNode}
  9630. */
  9631. const Break = () => expression( 'break' ).append();
  9632. //
  9633. const loop = ( ...params ) => { // @deprecated, r168
  9634. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9635. return Loop( ...params );
  9636. };
  9637. /** @module MorphNode **/
  9638. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9639. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9640. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9641. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9642. const y = texelIndex.div( width );
  9643. const x = texelIndex.sub( y.mul( width ) );
  9644. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9645. return bufferAttrib.mul( influence );
  9646. } );
  9647. function getEntry( geometry ) {
  9648. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9649. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9650. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9651. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9652. // into an array of data textures. Each layer represents a single morph target.
  9653. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9654. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9655. let entry = _morphTextures.get( geometry );
  9656. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9657. if ( entry !== undefined ) entry.texture.dispose();
  9658. const morphTargets = geometry.morphAttributes.position || [];
  9659. const morphNormals = geometry.morphAttributes.normal || [];
  9660. const morphColors = geometry.morphAttributes.color || [];
  9661. let vertexDataCount = 0;
  9662. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9663. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9664. if ( hasMorphColors === true ) vertexDataCount = 3;
  9665. let width = geometry.attributes.position.count * vertexDataCount;
  9666. let height = 1;
  9667. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9668. if ( width > maxTextureSize ) {
  9669. height = Math.ceil( width / maxTextureSize );
  9670. width = maxTextureSize;
  9671. }
  9672. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9673. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9674. bufferTexture.type = FloatType;
  9675. bufferTexture.needsUpdate = true;
  9676. // fill buffer
  9677. const vertexDataStride = vertexDataCount * 4;
  9678. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9679. const morphTarget = morphTargets[ i ];
  9680. const morphNormal = morphNormals[ i ];
  9681. const morphColor = morphColors[ i ];
  9682. const offset = width * height * 4 * i;
  9683. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9684. const stride = j * vertexDataStride;
  9685. if ( hasMorphPosition === true ) {
  9686. _morphVec4.fromBufferAttribute( morphTarget, j );
  9687. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9688. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9689. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9690. buffer[ offset + stride + 3 ] = 0;
  9691. }
  9692. if ( hasMorphNormals === true ) {
  9693. _morphVec4.fromBufferAttribute( morphNormal, j );
  9694. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9695. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9696. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9697. buffer[ offset + stride + 7 ] = 0;
  9698. }
  9699. if ( hasMorphColors === true ) {
  9700. _morphVec4.fromBufferAttribute( morphColor, j );
  9701. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9702. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9703. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9704. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9705. }
  9706. }
  9707. }
  9708. entry = {
  9709. count: morphTargetsCount,
  9710. texture: bufferTexture,
  9711. stride: vertexDataCount,
  9712. size: new Vector2( width, height )
  9713. };
  9714. _morphTextures.set( geometry, entry );
  9715. function disposeTexture() {
  9716. bufferTexture.dispose();
  9717. _morphTextures.delete( geometry );
  9718. geometry.removeEventListener( 'dispose', disposeTexture );
  9719. }
  9720. geometry.addEventListener( 'dispose', disposeTexture );
  9721. }
  9722. return entry;
  9723. }
  9724. /**
  9725. * This node implements the vertex transformation shader logic which is required
  9726. * for morph target animation.
  9727. *
  9728. * @augments Node
  9729. */
  9730. class MorphNode extends Node {
  9731. static get type() {
  9732. return 'MorphNode';
  9733. }
  9734. /**
  9735. * Constructs a new morph node.
  9736. *
  9737. * @param {Mesh} mesh - The mesh holding the morph targets.
  9738. */
  9739. constructor( mesh ) {
  9740. super( 'void' );
  9741. /**
  9742. * The mesh holding the morph targets.
  9743. *
  9744. * @type {Mesh}
  9745. */
  9746. this.mesh = mesh;
  9747. /**
  9748. * A uniform node which represents the morph base influence value.
  9749. *
  9750. * @type {UniformNode<float>}
  9751. */
  9752. this.morphBaseInfluence = uniform( 1 );
  9753. /**
  9754. * The update type overwritten since morph nodes are updated per object.
  9755. *
  9756. * @type {String}
  9757. */
  9758. this.updateType = NodeUpdateType.OBJECT;
  9759. }
  9760. /**
  9761. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9762. *
  9763. * @param {NodeBuilder} builder - The current node builder.
  9764. */
  9765. setup( builder ) {
  9766. const { geometry } = builder;
  9767. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9768. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9769. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9770. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9771. // nodes
  9772. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9773. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9774. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9775. const width = int( size.width );
  9776. Loop( morphTargetsCount, ( { i } ) => {
  9777. const influence = float( 0 ).toVar();
  9778. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9779. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9780. } else {
  9781. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9782. }
  9783. if ( hasMorphPosition === true ) {
  9784. positionLocal.addAssign( getMorph( {
  9785. bufferMap,
  9786. influence,
  9787. stride,
  9788. width,
  9789. depth: i,
  9790. offset: int( 0 )
  9791. } ) );
  9792. }
  9793. if ( hasMorphNormals === true ) {
  9794. normalLocal.addAssign( getMorph( {
  9795. bufferMap,
  9796. influence,
  9797. stride,
  9798. width,
  9799. depth: i,
  9800. offset: int( 1 )
  9801. } ) );
  9802. }
  9803. } );
  9804. }
  9805. /**
  9806. * Updates the state of the morphed mesh by updating the base influence.
  9807. *
  9808. * @param {NodeFrame} frame - The current node frame.
  9809. */
  9810. update( /*frame*/ ) {
  9811. const morphBaseInfluence = this.morphBaseInfluence;
  9812. if ( this.mesh.geometry.morphTargetsRelative ) {
  9813. morphBaseInfluence.value = 1;
  9814. } else {
  9815. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  9816. }
  9817. }
  9818. }
  9819. /**
  9820. * TSL function for creating a morph node.
  9821. *
  9822. * @function
  9823. * @param {Mesh} mesh - The mesh holding the morph targets.
  9824. * @returns {MorphNode}
  9825. */
  9826. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  9827. /**
  9828. * Base class for lighting nodes.
  9829. *
  9830. * @augments Node
  9831. */
  9832. class LightingNode extends Node {
  9833. static get type() {
  9834. return 'LightingNode';
  9835. }
  9836. /**
  9837. * Constructs a new lighting node.
  9838. */
  9839. constructor() {
  9840. super( 'vec3' );
  9841. /**
  9842. * This flag can be used for type testing.
  9843. *
  9844. * @type {Boolean}
  9845. * @readonly
  9846. * @default true
  9847. */
  9848. this.isLightingNode = true;
  9849. }
  9850. }
  9851. /**
  9852. * A generic class that can be used by nodes which contribute
  9853. * ambient occlusion to the scene. E.g. an ambient occlusion map
  9854. * node can be used as input for this module. Used in {@link NodeMaterial}.
  9855. *
  9856. * @augments LightingNode
  9857. */
  9858. class AONode extends LightingNode {
  9859. static get type() {
  9860. return 'AONode';
  9861. }
  9862. /**
  9863. * Constructs a new AO node.
  9864. *
  9865. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  9866. */
  9867. constructor( aoNode = null ) {
  9868. super();
  9869. /**
  9870. * The ambient occlusion node.
  9871. *
  9872. * @type {Node<float>?}
  9873. * @default null
  9874. */
  9875. this.aoNode = aoNode;
  9876. }
  9877. setup( builder ) {
  9878. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  9879. }
  9880. }
  9881. /**
  9882. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  9883. * by adding lighting specific context data. It represents the runtime context of
  9884. * {@link LightsNode}.
  9885. *
  9886. * @augments ContextNode
  9887. */
  9888. class LightingContextNode extends ContextNode {
  9889. static get type() {
  9890. return 'LightingContextNode';
  9891. }
  9892. /**
  9893. * Constructs a new lighting context node.
  9894. *
  9895. * @param {LightsNode} node - The lights node.
  9896. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  9897. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  9898. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  9899. */
  9900. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  9901. super( node );
  9902. /**
  9903. * The current lighting model.
  9904. *
  9905. * @type {LightingModel?}
  9906. * @default null
  9907. */
  9908. this.lightingModel = lightingModel;
  9909. /**
  9910. * A backdrop node.
  9911. *
  9912. * @type {Node<vec3>?}
  9913. * @default null
  9914. */
  9915. this.backdropNode = backdropNode;
  9916. /**
  9917. * A backdrop alpha node.
  9918. *
  9919. * @type {Node<float>?}
  9920. * @default null
  9921. */
  9922. this.backdropAlphaNode = backdropAlphaNode;
  9923. this._value = null;
  9924. }
  9925. /**
  9926. * Returns a lighting context object.
  9927. *
  9928. * @return {{
  9929. * radiance: Node<vec3>,
  9930. * irradiance: Node<vec3>,
  9931. * iblIrradiance: Node<vec3>,
  9932. * ambientOcclusion: Node<float>,
  9933. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  9934. * backdrop: Node<vec3>,
  9935. * backdropAlpha: Node<float>
  9936. * }} The lighting context object.
  9937. */
  9938. getContext() {
  9939. const { backdropNode, backdropAlphaNode } = this;
  9940. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  9941. directSpecular = vec3().toVar( 'directSpecular' ),
  9942. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  9943. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  9944. const reflectedLight = {
  9945. directDiffuse,
  9946. directSpecular,
  9947. indirectDiffuse,
  9948. indirectSpecular
  9949. };
  9950. const context = {
  9951. radiance: vec3().toVar( 'radiance' ),
  9952. irradiance: vec3().toVar( 'irradiance' ),
  9953. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  9954. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  9955. reflectedLight,
  9956. backdrop: backdropNode,
  9957. backdropAlpha: backdropAlphaNode
  9958. };
  9959. return context;
  9960. }
  9961. setup( builder ) {
  9962. this.value = this._value || ( this._value = this.getContext() );
  9963. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  9964. return super.setup( builder );
  9965. }
  9966. }
  9967. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  9968. /**
  9969. * A generic class that can be used by nodes which contribute
  9970. * irradiance to the scene. E.g. a light map node can be used
  9971. * as input for this module. Used in {@link NodeMaterial}.
  9972. *
  9973. * @augments LightingNode
  9974. */
  9975. class IrradianceNode extends LightingNode {
  9976. static get type() {
  9977. return 'IrradianceNode';
  9978. }
  9979. /**
  9980. * Constructs a new irradiance node.
  9981. *
  9982. * @param {Node<vec3>} node - A node contributing irradiance.
  9983. */
  9984. constructor( node ) {
  9985. super();
  9986. /**
  9987. * A node contributing irradiance.
  9988. *
  9989. * @type {Node<vec3>}
  9990. */
  9991. this.node = node;
  9992. }
  9993. setup( builder ) {
  9994. builder.context.irradiance.addAssign( this.node );
  9995. }
  9996. }
  9997. /** @module ScreenNode **/
  9998. let screenSizeVec, viewportVec;
  9999. /**
  10000. * This node provides a collection of screen related metrics.
  10001. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10002. * resolution or viewport data as well as fragment or uv coordinates.
  10003. *
  10004. * @augments Node
  10005. */
  10006. class ScreenNode extends Node {
  10007. static get type() {
  10008. return 'ScreenNode';
  10009. }
  10010. /**
  10011. * Constructs a new screen node.
  10012. *
  10013. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10014. */
  10015. constructor( scope ) {
  10016. super();
  10017. /**
  10018. * The node represents different metric depending on which scope is selected.
  10019. *
  10020. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10021. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10022. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10023. * - `ScreenNode.UV`: Normalized coordinates.
  10024. *
  10025. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10026. */
  10027. this.scope = scope;
  10028. /**
  10029. * This flag can be used for type testing.
  10030. *
  10031. * @type {Boolean}
  10032. * @readonly
  10033. * @default true
  10034. */
  10035. this.isViewportNode = true;
  10036. }
  10037. /**
  10038. * This method is overwritten since the node type depends on the selected scope.
  10039. *
  10040. * @return {('vec2'|'vec4')} The node type.
  10041. */
  10042. getNodeType() {
  10043. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10044. else return 'vec2';
  10045. }
  10046. /**
  10047. * This method is overwritten since the node's update type depends on the selected scope.
  10048. *
  10049. * @return {NodeUpdateType} The update type.
  10050. */
  10051. getUpdateType() {
  10052. let updateType = NodeUpdateType.NONE;
  10053. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10054. updateType = NodeUpdateType.RENDER;
  10055. }
  10056. this.updateType = updateType;
  10057. return updateType;
  10058. }
  10059. /**
  10060. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10061. * from the current renderer.
  10062. *
  10063. * @param {NodeFrame} frame - A reference to the current node frame.
  10064. */
  10065. update( { renderer } ) {
  10066. const renderTarget = renderer.getRenderTarget();
  10067. if ( this.scope === ScreenNode.VIEWPORT ) {
  10068. if ( renderTarget !== null ) {
  10069. viewportVec.copy( renderTarget.viewport );
  10070. } else {
  10071. renderer.getViewport( viewportVec );
  10072. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10073. }
  10074. } else {
  10075. if ( renderTarget !== null ) {
  10076. screenSizeVec.width = renderTarget.width;
  10077. screenSizeVec.height = renderTarget.height;
  10078. } else {
  10079. renderer.getDrawingBufferSize( screenSizeVec );
  10080. }
  10081. }
  10082. }
  10083. setup( /*builder*/ ) {
  10084. const scope = this.scope;
  10085. let output = null;
  10086. if ( scope === ScreenNode.SIZE ) {
  10087. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10088. } else if ( scope === ScreenNode.VIEWPORT ) {
  10089. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10090. } else {
  10091. output = vec2( screenCoordinate.div( screenSize ) );
  10092. }
  10093. return output;
  10094. }
  10095. generate( builder ) {
  10096. if ( this.scope === ScreenNode.COORDINATE ) {
  10097. let coord = builder.getFragCoord();
  10098. if ( builder.isFlipY() ) {
  10099. // follow webgpu standards
  10100. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10101. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10102. }
  10103. return coord;
  10104. }
  10105. return super.generate( builder );
  10106. }
  10107. }
  10108. ScreenNode.COORDINATE = 'coordinate';
  10109. ScreenNode.VIEWPORT = 'viewport';
  10110. ScreenNode.SIZE = 'size';
  10111. ScreenNode.UV = 'uv';
  10112. // Screen
  10113. /**
  10114. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10115. *
  10116. * @type {ScreenNode<vec2>}
  10117. */
  10118. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10119. /**
  10120. * TSL object that represents the screen resolution in physical pixel units.
  10121. *
  10122. * @type {ScreenNode<vec2>}
  10123. */
  10124. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10125. /**
  10126. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10127. *
  10128. * @type {ScreenNode<vec2>}
  10129. */
  10130. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10131. // Viewport
  10132. /**
  10133. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10134. *
  10135. * @type {ScreenNode<vec4>}
  10136. */
  10137. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10138. /**
  10139. * TSL object that represents the viewport resolution in physical pixel units.
  10140. *
  10141. * @type {ScreenNode<vec2>}
  10142. */
  10143. const viewportSize = viewport.zw;
  10144. /**
  10145. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10146. *
  10147. * @type {ScreenNode<vec2>}
  10148. */
  10149. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10150. /**
  10151. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10152. *
  10153. * @type {ScreenNode<vec2>}
  10154. */
  10155. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10156. // Deprecated
  10157. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10158. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10159. return screenSize;
  10160. }, 'vec2' ).once() )();
  10161. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10162. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10163. return screenUV;
  10164. }, 'vec2' ).once() )();
  10165. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10166. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10167. return screenUV.flipY();
  10168. }, 'vec2' ).once() )();
  10169. /** @module ViewportTextureNode **/
  10170. const _size$4 = /*@__PURE__*/ new Vector2();
  10171. /**
  10172. * A special type of texture node which represents the data of the current viewport
  10173. * as a texture. The module extracts data from the current bound framebuffer with
  10174. * a copy operation so no extra render pass is required to produce the texture data
  10175. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10176. * variety of effects like refractive or transmissive materials.
  10177. *
  10178. * @augments module:TextureNode~TextureNode
  10179. */
  10180. class ViewportTextureNode extends TextureNode {
  10181. static get type() {
  10182. return 'ViewportTextureNode';
  10183. }
  10184. /**
  10185. * Constructs a new viewport texture node.
  10186. *
  10187. * @param {Node} [uvNode=screenUV] - The uv node.
  10188. * @param {Node?} [levelNode=null] - The level node.
  10189. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10190. */
  10191. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10192. if ( framebufferTexture === null ) {
  10193. framebufferTexture = new FramebufferTexture();
  10194. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10195. }
  10196. super( framebufferTexture, uvNode, levelNode );
  10197. /**
  10198. * Whether to generate mipmaps or not.
  10199. *
  10200. * @type {Boolean}
  10201. * @default false
  10202. */
  10203. this.generateMipmaps = false;
  10204. /**
  10205. * This flag can be used for type testing.
  10206. *
  10207. * @type {Boolean}
  10208. * @readonly
  10209. * @default true
  10210. */
  10211. this.isOutputTextureNode = true;
  10212. /**
  10213. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10214. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10215. *
  10216. * @type {String}
  10217. * @default 'frame'
  10218. */
  10219. this.updateBeforeType = NodeUpdateType.FRAME;
  10220. }
  10221. updateBefore( frame ) {
  10222. const renderer = frame.renderer;
  10223. renderer.getDrawingBufferSize( _size$4 );
  10224. //
  10225. const framebufferTexture = this.value;
  10226. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10227. framebufferTexture.image.width = _size$4.width;
  10228. framebufferTexture.image.height = _size$4.height;
  10229. framebufferTexture.needsUpdate = true;
  10230. }
  10231. //
  10232. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10233. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10234. renderer.copyFramebufferToTexture( framebufferTexture );
  10235. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10236. }
  10237. clone() {
  10238. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10239. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10240. return viewportTextureNode;
  10241. }
  10242. }
  10243. /**
  10244. * TSL function for creating a viewport texture node.
  10245. *
  10246. * @function
  10247. * @param {Node} [uvNode=screenUV] - The uv node.
  10248. * @param {Node?} [levelNode=null] - The level node.
  10249. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10250. * @returns {ViewportTextureNode}
  10251. */
  10252. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10253. /**
  10254. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10255. *
  10256. * @function
  10257. * @param {Node} [uvNode=screenUV] - The uv node.
  10258. * @param {Node?} [levelNode=null] - The level node.
  10259. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10260. * @returns {ViewportTextureNode}
  10261. */
  10262. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10263. /** @module ViewportDepthTextureNode **/
  10264. let sharedDepthbuffer = null;
  10265. /**
  10266. * Represents the depth of the current viewport as a texture. This module
  10267. * can be used in combination with viewport texture to achieve effects
  10268. * that require depth evaluation.
  10269. *
  10270. * @augments module:ViewportTextureNode~ViewportTextureNode
  10271. */
  10272. class ViewportDepthTextureNode extends ViewportTextureNode {
  10273. static get type() {
  10274. return 'ViewportDepthTextureNode';
  10275. }
  10276. /**
  10277. * Constructs a new viewport depth texture node.
  10278. *
  10279. * @param {Node} [uvNode=screenUV] - The uv node.
  10280. * @param {Node?} [levelNode=null] - The level node.
  10281. */
  10282. constructor( uvNode = screenUV, levelNode = null ) {
  10283. if ( sharedDepthbuffer === null ) {
  10284. sharedDepthbuffer = new DepthTexture();
  10285. }
  10286. super( uvNode, levelNode, sharedDepthbuffer );
  10287. }
  10288. }
  10289. /**
  10290. * TSL function for a viewport depth texture node.
  10291. *
  10292. * @function
  10293. * @param {Node} [uvNode=screenUV] - The uv node.
  10294. * @param {Node?} [levelNode=null] - The level node.
  10295. * @returns {ViewportDepthTextureNode}
  10296. */
  10297. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10298. /** @module ViewportDepthNode **/
  10299. /**
  10300. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10301. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10302. * fragment or for depth evaluation purposes.
  10303. *
  10304. * @augments Node
  10305. */
  10306. class ViewportDepthNode extends Node {
  10307. static get type() {
  10308. return 'ViewportDepthNode';
  10309. }
  10310. /**
  10311. * Constructs a new viewport depth node.
  10312. *
  10313. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10314. * @param {Node?} [valueNode=null] - The value node.
  10315. */
  10316. constructor( scope, valueNode = null ) {
  10317. super( 'float' );
  10318. /**
  10319. * The node behaves differently depending on which scope is selected.
  10320. *
  10321. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10322. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10323. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10324. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10325. *
  10326. * @type {('depth'|'depthBase'|'linearDepth')}
  10327. */
  10328. this.scope = scope;
  10329. /**
  10330. * Can be used to define a custom depth value.
  10331. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10332. *
  10333. * @type {Node?}
  10334. * @default null
  10335. */
  10336. this.valueNode = valueNode;
  10337. /**
  10338. * This flag can be used for type testing.
  10339. *
  10340. * @type {Boolean}
  10341. * @readonly
  10342. * @default true
  10343. */
  10344. this.isViewportDepthNode = true;
  10345. }
  10346. generate( builder ) {
  10347. const { scope } = this;
  10348. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10349. return builder.getFragDepth();
  10350. }
  10351. return super.generate( builder );
  10352. }
  10353. setup( { camera } ) {
  10354. const { scope } = this;
  10355. const value = this.valueNode;
  10356. let node = null;
  10357. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10358. if ( value !== null ) {
  10359. node = depthBase().assign( value );
  10360. }
  10361. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10362. if ( camera.isPerspectiveCamera ) {
  10363. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10364. } else {
  10365. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10366. }
  10367. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10368. if ( value !== null ) {
  10369. if ( camera.isPerspectiveCamera ) {
  10370. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10371. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10372. } else {
  10373. node = value;
  10374. }
  10375. } else {
  10376. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10377. }
  10378. }
  10379. return node;
  10380. }
  10381. }
  10382. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10383. ViewportDepthNode.DEPTH = 'depth';
  10384. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10385. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10386. /**
  10387. * TSL function for converting a viewZ value to an orthographic depth value.
  10388. *
  10389. * @function
  10390. * @param {Node<float>} viewZ - The viewZ node.
  10391. * @param {Node<float>} near - The camera's near value.
  10392. * @param {Node<float>} far - The camera's far value.
  10393. * @returns {Node<float>}
  10394. */
  10395. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10396. /**
  10397. * TSL function for converting an orthographic depth value to a viewZ value.
  10398. *
  10399. * @function
  10400. * @param {Node<float>} depth - The orthographic depth.
  10401. * @param {Node<float>} near - The camera's near value.
  10402. * @param {Node<float>} far - The camera's far value.
  10403. * @returns {Node<float>}
  10404. */
  10405. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10406. /**
  10407. * TSL function for converting a viewZ value to a perspective depth value.
  10408. *
  10409. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10410. *
  10411. * @function
  10412. * @param {Node<float>} viewZ - The viewZ node.
  10413. * @param {Node<float>} near - The camera's near value.
  10414. * @param {Node<float>} far - The camera's far value.
  10415. * @returns {Node<float>}
  10416. */
  10417. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10418. /**
  10419. * TSL function for converting a perspective depth value to a viewZ value.
  10420. *
  10421. * @function
  10422. * @param {Node<float>} depth - The perspective depth.
  10423. * @param {Node<float>} near - The camera's near value.
  10424. * @param {Node<float>} far - The camera's far value.
  10425. * @returns {Node<float>}
  10426. */
  10427. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10428. /**
  10429. * TSL function for converting a viewZ value to a logarithmic depth value.
  10430. *
  10431. * @function
  10432. * @param {Node<float>} viewZ - The viewZ node.
  10433. * @param {Node<float>} near - The camera's near value.
  10434. * @param {Node<float>} far - The camera's far value.
  10435. * @returns {Node<float>}
  10436. */
  10437. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10438. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10439. // The final logarithmic depth formula used here is adapted from one described in an
  10440. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10441. // which was an improvement upon an earlier formula one described in an
  10442. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10443. // Ulrich's formula is the following:
  10444. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10445. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10446. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10447. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10448. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10449. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10450. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10451. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10452. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10453. // Outerra eventually made another improvement to their original "C-constant" variant,
  10454. // but it still does not incorporate the camera near plane (for this version,
  10455. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10456. // Here we make 4 changes to Ulrich's formula:
  10457. // 1. Clamp the camera near plane so we don't divide by 0.
  10458. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10459. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10460. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10461. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10462. // so we do the same here, hence the 'viewZ.negate()' call.
  10463. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10464. near = near.max( 1e-6 ).toVar();
  10465. const numerator = log2( viewZ.negate().div( near ) );
  10466. const denominator = log2( far.div( near ) );
  10467. return numerator.div( denominator );
  10468. };
  10469. /**
  10470. * TSL function for converting a logarithmic depth value to a viewZ value.
  10471. *
  10472. * @function
  10473. * @param {Node<float>} depth - The logarithmic depth.
  10474. * @param {Node<float>} near - The camera's near value.
  10475. * @param {Node<float>} far - The camera's far value.
  10476. * @returns {Node<float>}
  10477. */
  10478. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10479. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10480. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10481. // a negative viewZ).
  10482. const exponent = depth.mul( log( far.div( near ) ) );
  10483. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10484. };
  10485. /**
  10486. * TSL function for defining a value for the current fragment's depth.
  10487. *
  10488. * @function
  10489. * @param {Node<float>} value - The depth value to set.
  10490. * @returns {ViewportDepthNode<float>}
  10491. */
  10492. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10493. /**
  10494. * TSL object that represents the depth value for the current fragment.
  10495. *
  10496. * @type {ViewportDepthNode}
  10497. */
  10498. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10499. /**
  10500. * TSL function for converting a perspective depth value to linear depth.
  10501. *
  10502. * @function
  10503. * @param {Node<float>} value - The perspective depth.
  10504. * @returns {ViewportDepthNode<float>}
  10505. */
  10506. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10507. /**
  10508. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10509. *
  10510. * @type {ViewportDepthNode}
  10511. */
  10512. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10513. depth.assign = ( value ) => depthBase( value );
  10514. /** @module BuiltinNode **/
  10515. /**
  10516. * The node allows to set values for built-in shader variables. That is
  10517. * required for features like hardware-accelerated vertex clipping.
  10518. *
  10519. * @augments Node
  10520. */
  10521. class BuiltinNode extends Node {
  10522. /**
  10523. * Constructs a new builtin node.
  10524. *
  10525. * @param {String} name - The name of the built-in shader variable.
  10526. */
  10527. constructor( name ) {
  10528. super( 'float' );
  10529. /**
  10530. * The name of the built-in shader variable.
  10531. *
  10532. * @type {String}
  10533. */
  10534. this.name = name;
  10535. /**
  10536. * This flag can be used for type testing.
  10537. *
  10538. * @type {Boolean}
  10539. * @readonly
  10540. * @default true
  10541. */
  10542. this.isBuiltinNode = true;
  10543. }
  10544. /**
  10545. * Generates the code snippet of the builtin node.
  10546. *
  10547. * @param {NodeBuilder} builder - The current node builder.
  10548. * @return {String} The generated code snippet.
  10549. */
  10550. generate( /* builder */ ) {
  10551. return this.name;
  10552. }
  10553. }
  10554. /**
  10555. * TSL function for creating a builtin node.
  10556. *
  10557. * @function
  10558. * @param {String} name - The name of the built-in shader variable.
  10559. * @returns {BuiltinNode}
  10560. */
  10561. const builtin = nodeProxy( BuiltinNode );
  10562. /** @module ClippingNode **/
  10563. /**
  10564. * ```
  10565. * This node is used in {@link NodeMaterial} to setup the clipping
  10566. * which can happen hardware-accelerated (if supported) and optionally
  10567. * use alpha-to-coverage for anti-aliasing clipped edges.
  10568. * ```
  10569. * @augments Node
  10570. */
  10571. class ClippingNode extends Node {
  10572. static get type() {
  10573. return 'ClippingNode';
  10574. }
  10575. /**
  10576. * Constructs a new clipping node.
  10577. *
  10578. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10579. * the selected scope influences the behavior of the node and what type of code is generated.
  10580. */
  10581. constructor( scope = ClippingNode.DEFAULT ) {
  10582. super();
  10583. /**
  10584. * The node's scope. Similar to other nodes, the selected scope influences
  10585. * the behavior of the node and what type of code is generated.
  10586. *
  10587. * @type {('default'|'hardware'|'alphaToCoverage')}
  10588. */
  10589. this.scope = scope;
  10590. }
  10591. /**
  10592. * Setups the node depending on the selected scope.
  10593. *
  10594. * @param {NodeBuilder} builder - The current node builder.
  10595. * @return {Node} The result node.
  10596. */
  10597. setup( builder ) {
  10598. super.setup( builder );
  10599. const clippingContext = builder.clippingContext;
  10600. const { intersectionPlanes, unionPlanes } = clippingContext;
  10601. this.hardwareClipping = builder.material.hardwareClipping;
  10602. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10603. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10604. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10605. return this.setupHardwareClipping( unionPlanes, builder );
  10606. } else {
  10607. return this.setupDefault( intersectionPlanes, unionPlanes );
  10608. }
  10609. }
  10610. /**
  10611. * Setups alpha to coverage.
  10612. *
  10613. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10614. * @param {Array<Vector4>} unionPlanes - The union planes.
  10615. * @return {Node} The result node.
  10616. */
  10617. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10618. return Fn( () => {
  10619. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10620. const distanceGradient = float().toVar( 'distanceToGradient' );
  10621. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10622. const numUnionPlanes = unionPlanes.length;
  10623. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10624. const clippingPlanes = uniformArray( unionPlanes );
  10625. Loop( numUnionPlanes, ( { i } ) => {
  10626. const plane = clippingPlanes.element( i );
  10627. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10628. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10629. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10630. } );
  10631. }
  10632. const numIntersectionPlanes = intersectionPlanes.length;
  10633. if ( numIntersectionPlanes > 0 ) {
  10634. const clippingPlanes = uniformArray( intersectionPlanes );
  10635. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10636. Loop( numIntersectionPlanes, ( { i } ) => {
  10637. const plane = clippingPlanes.element( i );
  10638. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10639. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10640. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10641. } );
  10642. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10643. }
  10644. diffuseColor.a.mulAssign( clipOpacity );
  10645. diffuseColor.a.equal( 0.0 ).discard();
  10646. } )();
  10647. }
  10648. /**
  10649. * Setups the default clipping.
  10650. *
  10651. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10652. * @param {Array<Vector4>} unionPlanes - The union planes.
  10653. * @return {Node} The result node.
  10654. */
  10655. setupDefault( intersectionPlanes, unionPlanes ) {
  10656. return Fn( () => {
  10657. const numUnionPlanes = unionPlanes.length;
  10658. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10659. const clippingPlanes = uniformArray( unionPlanes );
  10660. Loop( numUnionPlanes, ( { i } ) => {
  10661. const plane = clippingPlanes.element( i );
  10662. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10663. } );
  10664. }
  10665. const numIntersectionPlanes = intersectionPlanes.length;
  10666. if ( numIntersectionPlanes > 0 ) {
  10667. const clippingPlanes = uniformArray( intersectionPlanes );
  10668. const clipped = bool( true ).toVar( 'clipped' );
  10669. Loop( numIntersectionPlanes, ( { i } ) => {
  10670. const plane = clippingPlanes.element( i );
  10671. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10672. } );
  10673. clipped.discard();
  10674. }
  10675. } )();
  10676. }
  10677. /**
  10678. * Setups hardware clipping.
  10679. *
  10680. * @param {Array<Vector4>} unionPlanes - The union planes.
  10681. * @param {NodeBuilder} builder - The current node builder.
  10682. * @return {Node} The result node.
  10683. */
  10684. setupHardwareClipping( unionPlanes, builder ) {
  10685. const numUnionPlanes = unionPlanes.length;
  10686. builder.enableHardwareClipping( numUnionPlanes );
  10687. return Fn( () => {
  10688. const clippingPlanes = uniformArray( unionPlanes );
  10689. const hw_clip_distances = builtin( builder.getClipDistance() );
  10690. Loop( numUnionPlanes, ( { i } ) => {
  10691. const plane = clippingPlanes.element( i );
  10692. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10693. hw_clip_distances.element( i ).assign( distance );
  10694. } );
  10695. } )();
  10696. }
  10697. }
  10698. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10699. ClippingNode.DEFAULT = 'default';
  10700. ClippingNode.HARDWARE = 'hardware';
  10701. /**
  10702. * TSL function for setting up the default clipping logic.
  10703. *
  10704. * @function
  10705. * @returns {ClippingNode}
  10706. */
  10707. const clipping = () => nodeObject( new ClippingNode() );
  10708. /**
  10709. * TSL function for setting up alpha to coverage.
  10710. *
  10711. * @function
  10712. * @returns {ClippingNode}
  10713. */
  10714. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10715. /**
  10716. * TSL function for setting up hardware-based clipping.
  10717. *
  10718. * @function
  10719. * @returns {ClippingNode}
  10720. */
  10721. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10722. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10723. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10724. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10725. 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 ) ) ) ) ) );
  10726. } );
  10727. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10728. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10729. } );
  10730. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10731. // Find the discretized derivatives of our coordinates
  10732. const maxDeriv = max$1(
  10733. length( dFdx( position.xyz ) ),
  10734. length( dFdy( position.xyz ) )
  10735. );
  10736. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10737. // Find two nearest log-discretized noise scales
  10738. const pixScales = vec2(
  10739. exp2( floor( log2( pixScale ) ) ),
  10740. exp2( ceil( log2( pixScale ) ) )
  10741. );
  10742. // Compute alpha thresholds at our two noise scales
  10743. const alpha = vec2(
  10744. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10745. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10746. );
  10747. // Factor to interpolate lerp with
  10748. const lerpFactor = fract( log2( pixScale ) );
  10749. // Interpolate alpha threshold from noise at two scales
  10750. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10751. // Pass into CDF to compute uniformly distrib threshold
  10752. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10753. const cases = vec3(
  10754. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10755. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10756. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10757. // Find our final, uniformly distributed alpha threshold (ατ)
  10758. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10759. // Avoids ατ == 0. Could also do ατ =1-ατ
  10760. return clamp( threshold, 1.0e-6, 1.0 );
  10761. } ).setLayout( {
  10762. name: 'getAlphaHashThreshold',
  10763. type: 'float',
  10764. inputs: [
  10765. { name: 'position', type: 'vec3' }
  10766. ]
  10767. } );
  10768. /**
  10769. * Base class for all node materials.
  10770. *
  10771. * @augments Material
  10772. */
  10773. class NodeMaterial extends Material {
  10774. static get type() {
  10775. return 'NodeMaterial';
  10776. }
  10777. /**
  10778. * Represents the type of the node material.
  10779. *
  10780. * @type {String}
  10781. */
  10782. get type() {
  10783. return this.constructor.type;
  10784. }
  10785. set type( _value ) { /* */ }
  10786. /**
  10787. * Constructs a new node material.
  10788. */
  10789. constructor() {
  10790. super();
  10791. /**
  10792. * This flag can be used for type testing.
  10793. *
  10794. * @type {Boolean}
  10795. * @readonly
  10796. * @default true
  10797. */
  10798. this.isNodeMaterial = true;
  10799. /**
  10800. * Whether this material is affected by fog or not.
  10801. *
  10802. * @type {Boolean}
  10803. * @default true
  10804. */
  10805. this.fog = true;
  10806. /**
  10807. * Whether this material is affected by lights or not.
  10808. *
  10809. * @type {Boolean}
  10810. * @default false
  10811. */
  10812. this.lights = false;
  10813. /**
  10814. * Whether this material uses hardware clipping or not.
  10815. * This property is managed by the engine and should not be
  10816. * modified by apps.
  10817. *
  10818. * @type {Boolean}
  10819. * @default false
  10820. */
  10821. this.hardwareClipping = false;
  10822. /**
  10823. * Node materials which set their `lights` property to `true`
  10824. * are affected by all lights of the scene. Sometimes selective
  10825. * lighting is wanted which means only _some_ lights in the scene
  10826. * affect a material. This can be achieved by creating an instance
  10827. * of {@link module:LightsNode~LightsNode} with a list of selective
  10828. * lights and assign the node to this property.
  10829. *
  10830. * ```js
  10831. * const customLightsNode = lights( [ light1, light2 ] );
  10832. * material.lightsNode = customLightsNode;
  10833. * ```
  10834. *
  10835. * @type {LightsNode?}
  10836. * @default null
  10837. */
  10838. this.lightsNode = null;
  10839. /**
  10840. * The environment of node materials can be defined by an environment
  10841. * map assigned to the `envMap` property or by `Scene.environment`
  10842. * if the node material is a PBR material. This node property allows to overwrite
  10843. * the default behavior and define the environment with a custom node.
  10844. *
  10845. * ```js
  10846. * material.envNode = pmremTexture( renderTarget.texture );
  10847. * ```
  10848. *
  10849. * @type {Node<vec3>?}
  10850. * @default null
  10851. */
  10852. this.envNode = null;
  10853. /**
  10854. * The lighting of node materials might be influenced by ambient occlusion.
  10855. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  10856. * and the respective `aoMapIntensity`. This node property allows to overwrite
  10857. * the default and define the ambient occlusion with a custom node instead.
  10858. *
  10859. * If you don't want to overwrite the diffuse color but modify the existing
  10860. * values instead, use {@link module:MaterialNode.materialAO}.
  10861. *
  10862. * @type {Node<float>?}
  10863. * @default null
  10864. */
  10865. this.aoNode = null;
  10866. /**
  10867. * The diffuse color of node materials is by default inferred from the
  10868. * `color` and `map` properties. This node property allows to overwrite the default
  10869. * and define the diffuse color with a node instead.
  10870. *
  10871. * ```js
  10872. * material.colorNode = color( 0xff0000 ); // define red color
  10873. * ```
  10874. *
  10875. * If you don't want to overwrite the diffuse color but modify the existing
  10876. * values instead, use {@link module:MaterialNode.materialColor}.
  10877. *
  10878. * ```js
  10879. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  10880. * ```
  10881. *
  10882. * @type {Node<vec3>?}
  10883. * @default null
  10884. */
  10885. this.colorNode = null;
  10886. /**
  10887. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  10888. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  10889. * and define the normals with a node instead.
  10890. *
  10891. * If you don't want to overwrite the normals but modify the existing values instead,
  10892. * use {@link module:MaterialNode.materialNormal}.
  10893. *
  10894. * @type {Node<vec3>?}
  10895. * @default null
  10896. */
  10897. this.normalNode = null;
  10898. /**
  10899. * The opacity of node materials is by default inferred from the `opacity`
  10900. * and `alphaMap` properties. This node property allows to overwrite the default
  10901. * and define the opacity with a node instead.
  10902. *
  10903. * If you don't want to overwrite the normals but modify the existing
  10904. * value instead, use {@link module:MaterialNode.materialOpacity}.
  10905. *
  10906. * @type {Node<float>?}
  10907. * @default null
  10908. */
  10909. this.opacityNode = null;
  10910. /**
  10911. * This node can be used to to implement a variety of filter-like effects. The idea is
  10912. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  10913. * to create an arbitrary effect and then assign the node composition to this property.
  10914. * Everything behind the object using this material will now be affected by a filter.
  10915. *
  10916. * ```js
  10917. * const material = new NodeMaterial()
  10918. * material.transparent = true;
  10919. *
  10920. * // everything behind the object will be monochromatic
  10921. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  10922. * ```
  10923. *
  10924. * Backdrop computations are part of the lighting so only lit materials can use this property.
  10925. *
  10926. * @type {Node<vec3>?}
  10927. * @default null
  10928. */
  10929. this.backdropNode = null;
  10930. /**
  10931. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  10932. *
  10933. * @type {Node<float>?}
  10934. * @default null
  10935. */
  10936. this.backdropAlphaNode = null;
  10937. /**
  10938. * The alpha test of node materials is by default inferred from the `alphaTest`
  10939. * property. This node property allows to overwrite the default and define the
  10940. * alpha test with a node instead.
  10941. *
  10942. * If you don't want to overwrite the alpha test but modify the existing
  10943. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  10944. *
  10945. * @type {Node<float>?}
  10946. * @default null
  10947. */
  10948. this.alphaTestNode = null;
  10949. /**
  10950. * The local vertex positions are computed based on multiple factors like the
  10951. * attribute data, morphing or skinning. This node property allows to overwrite
  10952. * the default and define local vertex positions with nodes instead.
  10953. *
  10954. * If you don't want to overwrite the vertex positions but modify the existing
  10955. * values instead, use {@link module:Position.positionLocal}.
  10956. *
  10957. *```js
  10958. * material.positionNode = positionLocal.add( displace );
  10959. * ```
  10960. *
  10961. * @type {Node<vec3>?}
  10962. * @default null
  10963. */
  10964. this.positionNode = null;
  10965. /**
  10966. * This node property is intended for logic which modifies geometry data once or per animation step.
  10967. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  10968. * `geometryNode` is intended as a dedicated API so there is an intended spot where goemetry modiciations
  10969. * can be implemented.
  10970. *
  10971. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  10972. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  10973. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  10974. * eventually assigned to `geometryNode`.
  10975. *
  10976. * @type {Function}
  10977. * @default null
  10978. */
  10979. this.geometryNode = null;
  10980. /**
  10981. * Allows to overwrite depth values in the fragment shader.
  10982. *
  10983. * @type {Node<float>?}
  10984. * @default null
  10985. */
  10986. this.depthNode = null;
  10987. /**
  10988. * Allows to overwrite the position used for shadow map rendering which
  10989. * is by default {@link module:Position.positionWorld}, the vertex position
  10990. * in world space.
  10991. *
  10992. * @type {Node<float>?}
  10993. * @default null
  10994. */
  10995. this.shadowPositionNode = null;
  10996. /**
  10997. * This node can be used to influence how an object using this node material
  10998. * receive shadows.
  10999. *
  11000. * ```js
  11001. * const totalShadows = float( 1 ).toVar();
  11002. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11003. * totalShadows.mulAssign( shadow );
  11004. * //return float( 1 ); // bypass received shadows
  11005. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11006. * } );
  11007. *
  11008. * @type {Node<vec4>?}
  11009. * @default null
  11010. */
  11011. this.receivedShadowNode = null;
  11012. /**
  11013. * This node can be used to influence how an object using this node material
  11014. * casts shadows. To apply a color to shadows, you can simply do:
  11015. *
  11016. * ```js
  11017. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11018. * ```
  11019. *
  11020. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11021. * is also common to use the property with `Fn` function so checks are performed
  11022. * per fragment.
  11023. *
  11024. * ```js
  11025. * materialCustomShadow.castShadowNode = Fn( () => {
  11026. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11027. * return materialColor;
  11028. * } )();
  11029. * ```
  11030. *
  11031. * @type {Node<vec4>?}
  11032. * @default null
  11033. */
  11034. this.castShadowNode = null;
  11035. /**
  11036. * This node can be used to define the final output of the material.
  11037. *
  11038. * TODO: Explain the differences to `fragmentNode`.
  11039. *
  11040. * @type {Node<vec4>?}
  11041. * @default null
  11042. */
  11043. this.outputNode = null;
  11044. /**
  11045. * MRT configuration is done on renderer or pass level. This node allows to
  11046. * overwrite what values are written into MRT targets on material level. This
  11047. * can be useful for implementing selective FX features that should only affect
  11048. * specific objects.
  11049. *
  11050. * @type {MRTNode?}
  11051. * @default null
  11052. */
  11053. this.mrtNode = null;
  11054. /**
  11055. * This node property can be used if you need complete freedom in implementing
  11056. * the fragment shader. Assigning a node will replace the built-in material
  11057. * logic used in the fragment stage.
  11058. *
  11059. * @type {Node<vec4>?}
  11060. * @default null
  11061. */
  11062. this.fragmentNode = null;
  11063. /**
  11064. * This node property can be used if you need complete freedom in implementing
  11065. * the vertex shader. Assigning a node will replace the built-in material logic
  11066. * used in the vertex stage.
  11067. *
  11068. * @type {Node<vec4>?}
  11069. * @default null
  11070. */
  11071. this.vertexNode = null;
  11072. }
  11073. /**
  11074. * Allows to define a custom cache key that influence the material key computation
  11075. * for render objects.
  11076. *
  11077. * @return {String} The custom cache key.
  11078. */
  11079. customProgramCacheKey() {
  11080. return this.type + getCacheKey$1( this );
  11081. }
  11082. /**
  11083. * Builds this material with the given node builder.
  11084. *
  11085. * @param {NodeBuilder} builder - The current node builder.
  11086. */
  11087. build( builder ) {
  11088. this.setup( builder );
  11089. }
  11090. /**
  11091. * Setups a node material observer with the given builder.
  11092. *
  11093. * @param {NodeBuilder} builder - The current node builder.
  11094. * @return {NodeMaterialObserver} The node material observer.
  11095. */
  11096. setupObserver( builder ) {
  11097. return new NodeMaterialObserver( builder );
  11098. }
  11099. /**
  11100. * Setups the vertex and fragment stage of this node material.
  11101. *
  11102. * @param {NodeBuilder} builder - The current node builder.
  11103. */
  11104. setup( builder ) {
  11105. builder.context.setupNormal = () => this.setupNormal( builder );
  11106. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11107. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11108. const renderer = builder.renderer;
  11109. const renderTarget = renderer.getRenderTarget();
  11110. // < VERTEX STAGE >
  11111. builder.addStack();
  11112. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11113. builder.stack.outputNode = vertexNode;
  11114. this.setupHardwareClipping( builder );
  11115. if ( this.geometryNode !== null ) {
  11116. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11117. }
  11118. builder.addFlow( 'vertex', builder.removeStack() );
  11119. // < FRAGMENT STAGE >
  11120. builder.addStack();
  11121. let resultNode;
  11122. const clippingNode = this.setupClipping( builder );
  11123. if ( this.depthWrite === true ) {
  11124. // only write depth if depth buffer is configured
  11125. if ( renderTarget !== null ) {
  11126. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11127. } else {
  11128. if ( renderer.depth === true ) this.setupDepth( builder );
  11129. }
  11130. }
  11131. if ( this.fragmentNode === null ) {
  11132. this.setupDiffuseColor( builder );
  11133. this.setupVariants( builder );
  11134. const outgoingLightNode = this.setupLighting( builder );
  11135. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11136. // force unsigned floats - useful for RenderTargets
  11137. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11138. resultNode = this.setupOutput( builder, basicOutput );
  11139. // OUTPUT NODE
  11140. output.assign( resultNode );
  11141. //
  11142. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11143. // MRT
  11144. if ( renderTarget !== null ) {
  11145. const mrt = renderer.getMRT();
  11146. const materialMRT = this.mrtNode;
  11147. if ( mrt !== null ) {
  11148. resultNode = mrt;
  11149. if ( materialMRT !== null ) {
  11150. resultNode = mrt.merge( materialMRT );
  11151. }
  11152. } else if ( materialMRT !== null ) {
  11153. resultNode = materialMRT;
  11154. }
  11155. }
  11156. } else {
  11157. let fragmentNode = this.fragmentNode;
  11158. if ( fragmentNode.isOutputStructNode !== true ) {
  11159. fragmentNode = vec4( fragmentNode );
  11160. }
  11161. resultNode = this.setupOutput( builder, fragmentNode );
  11162. }
  11163. builder.stack.outputNode = resultNode;
  11164. builder.addFlow( 'fragment', builder.removeStack() );
  11165. // < MONITOR >
  11166. builder.monitor = this.setupObserver( builder );
  11167. }
  11168. /**
  11169. * Setups the clipping node.
  11170. *
  11171. * @param {NodeBuilder} builder - The current node builder.
  11172. * @return {ClippingNode} The clipping node.
  11173. */
  11174. setupClipping( builder ) {
  11175. if ( builder.clippingContext === null ) return null;
  11176. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11177. let result = null;
  11178. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11179. const samples = builder.renderer.samples;
  11180. if ( this.alphaToCoverage && samples > 1 ) {
  11181. // to be added to flow when the color/alpha value has been determined
  11182. result = clippingAlpha();
  11183. } else {
  11184. builder.stack.add( clipping() );
  11185. }
  11186. }
  11187. return result;
  11188. }
  11189. /**
  11190. * Setups the hardware clipping if available on the current device.
  11191. *
  11192. * @param {NodeBuilder} builder - The current node builder.
  11193. */
  11194. setupHardwareClipping( builder ) {
  11195. this.hardwareClipping = false;
  11196. if ( builder.clippingContext === null ) return;
  11197. const candidateCount = builder.clippingContext.unionPlanes.length;
  11198. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11199. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11200. builder.stack.add( hardwareClipping() );
  11201. this.hardwareClipping = true;
  11202. }
  11203. return;
  11204. }
  11205. /**
  11206. * Setups the depth of this material.
  11207. *
  11208. * @param {NodeBuilder} builder - The current node builder.
  11209. */
  11210. setupDepth( builder ) {
  11211. const { renderer, camera } = builder;
  11212. // Depth
  11213. let depthNode = this.depthNode;
  11214. if ( depthNode === null ) {
  11215. const mrt = renderer.getMRT();
  11216. if ( mrt && mrt.has( 'depth' ) ) {
  11217. depthNode = mrt.get( 'depth' );
  11218. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11219. if ( camera.isPerspectiveCamera ) {
  11220. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11221. } else {
  11222. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11223. }
  11224. }
  11225. }
  11226. if ( depthNode !== null ) {
  11227. depth.assign( depthNode ).append();
  11228. }
  11229. }
  11230. /**
  11231. * Setups the position node in view space. This method exists
  11232. * so derived node materials can modifiy the implementation e.g. sprite materials.
  11233. *
  11234. * @param {NodeBuilder} builder - The current node builder.
  11235. * @return {Node<vec3>} The position in view space.
  11236. */
  11237. setupPositionView( /*builder*/ ) {
  11238. return modelViewMatrix.mul( positionLocal ).xyz;
  11239. }
  11240. /**
  11241. * Setups the position in clip space.
  11242. *
  11243. * @param {NodeBuilder} builder - The current node builder.
  11244. * @return {Node<vec4>} The position in view space.
  11245. */
  11246. setupModelViewProjection( /*builder*/ ) {
  11247. return cameraProjectionMatrix.mul( positionView );
  11248. }
  11249. /**
  11250. * Setups the logic for the vertex stage.
  11251. *
  11252. * @param {NodeBuilder} builder - The current node builder.
  11253. * @return {Node<vec4>} The position in clip space.
  11254. */
  11255. setupVertex( builder ) {
  11256. builder.addStack();
  11257. this.setupPosition( builder );
  11258. builder.context.vertex = builder.removeStack();
  11259. return modelViewProjection;
  11260. }
  11261. /**
  11262. * Setups the computation of the position in local space.
  11263. *
  11264. * @param {NodeBuilder} builder - The current node builder.
  11265. * @return {Node<vec3>} The position in local space.
  11266. */
  11267. setupPosition( builder ) {
  11268. const { object, geometry } = builder;
  11269. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11270. morphReference( object ).append();
  11271. }
  11272. if ( object.isSkinnedMesh === true ) {
  11273. skinningReference( object ).append();
  11274. }
  11275. if ( this.displacementMap ) {
  11276. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11277. const displacementScale = materialReference( 'displacementScale', 'float' );
  11278. const displacementBias = materialReference( 'displacementBias', 'float' );
  11279. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11280. }
  11281. if ( object.isBatchedMesh ) {
  11282. batch( object ).append();
  11283. }
  11284. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11285. instancedMesh( object ).append();
  11286. }
  11287. if ( this.positionNode !== null ) {
  11288. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11289. }
  11290. return positionLocal;
  11291. }
  11292. /**
  11293. * Setups the computation of the material's diffuse color.
  11294. *
  11295. * @param {NodeBuilder} builder - The current node builder.
  11296. * @param {BufferGeometry} geometry - The geometry.
  11297. */
  11298. setupDiffuseColor( { object, geometry } ) {
  11299. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11300. // VERTEX COLORS
  11301. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11302. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11303. }
  11304. // Instanced colors
  11305. if ( object.instanceColor ) {
  11306. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11307. colorNode = instanceColor.mul( colorNode );
  11308. }
  11309. if ( object.isBatchedMesh && object._colorsTexture ) {
  11310. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11311. colorNode = batchColor.mul( colorNode );
  11312. }
  11313. // COLOR
  11314. diffuseColor.assign( colorNode );
  11315. // OPACITY
  11316. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11317. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11318. // ALPHA TEST
  11319. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11320. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11321. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11322. }
  11323. // ALPHA HASH
  11324. if ( this.alphaHash === true ) {
  11325. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11326. }
  11327. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11328. diffuseColor.a.assign( 1.0 );
  11329. }
  11330. }
  11331. /**
  11332. * Abstract interface method that can be implemented by derived materials
  11333. * to setup material-specific node variables.
  11334. *
  11335. * @abstract
  11336. * @param {NodeBuilder} builder - The current node builder.
  11337. */
  11338. setupVariants( /*builder*/ ) {
  11339. // Interface function.
  11340. }
  11341. /**
  11342. * Setups the outgoing light node variable
  11343. *
  11344. * @return {Node<vec3>} The outgoing light node.
  11345. */
  11346. setupOutgoingLight() {
  11347. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11348. }
  11349. /**
  11350. * Setups the normal node from the material.
  11351. *
  11352. * @return {Node<vec3>} The normal node.
  11353. */
  11354. setupNormal() {
  11355. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11356. }
  11357. /**
  11358. * Setups the environment node from the material.
  11359. *
  11360. * @param {NodeBuilder} builder - The current node builder.
  11361. * @return {Node<vec4>} The environment node.
  11362. */
  11363. setupEnvironment( /*builder*/ ) {
  11364. let node = null;
  11365. if ( this.envNode ) {
  11366. node = this.envNode;
  11367. } else if ( this.envMap ) {
  11368. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11369. }
  11370. return node;
  11371. }
  11372. /**
  11373. * Setups the light map node from the material.
  11374. *
  11375. * @param {NodeBuilder} builder - The current node builder.
  11376. * @return {Node<vec3>} The light map node.
  11377. */
  11378. setupLightMap( builder ) {
  11379. let node = null;
  11380. if ( builder.material.lightMap ) {
  11381. node = new IrradianceNode( materialLightMap );
  11382. }
  11383. return node;
  11384. }
  11385. /**
  11386. * Setups the lights node based on the scene, environment and material.
  11387. *
  11388. * @param {NodeBuilder} builder - The current node builder.
  11389. * @return {LightsNode} The lights node.
  11390. */
  11391. setupLights( builder ) {
  11392. const materialLightsNode = [];
  11393. //
  11394. const envNode = this.setupEnvironment( builder );
  11395. if ( envNode && envNode.isLightingNode ) {
  11396. materialLightsNode.push( envNode );
  11397. }
  11398. const lightMapNode = this.setupLightMap( builder );
  11399. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11400. materialLightsNode.push( lightMapNode );
  11401. }
  11402. if ( this.aoNode !== null || builder.material.aoMap ) {
  11403. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11404. materialLightsNode.push( new AONode( aoNode ) );
  11405. }
  11406. let lightsN = this.lightsNode || builder.lightsNode;
  11407. if ( materialLightsNode.length > 0 ) {
  11408. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11409. }
  11410. return lightsN;
  11411. }
  11412. /**
  11413. * This method should be implemented by most derived materials
  11414. * since it defines the material's lighting model.
  11415. *
  11416. * @abstract
  11417. * @param {NodeBuilder} builder - The current node builder.
  11418. * @return {LightingModel} The lighting model.
  11419. */
  11420. setupLightingModel( /*builder*/ ) {
  11421. // Interface function.
  11422. }
  11423. /**
  11424. * Setups the outgoing light node.
  11425. *
  11426. * @param {NodeBuilder} builder - The current node builder.
  11427. * @return {Node<vec3>} The outgoing light node.
  11428. */
  11429. setupLighting( builder ) {
  11430. const { material } = builder;
  11431. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11432. // OUTGOING LIGHT
  11433. const lights = this.lights === true || this.lightsNode !== null;
  11434. const lightsNode = lights ? this.setupLights( builder ) : null;
  11435. let outgoingLightNode = this.setupOutgoingLight( builder );
  11436. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11437. const lightingModel = this.setupLightingModel( builder );
  11438. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11439. } else if ( backdropNode !== null ) {
  11440. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11441. }
  11442. // EMISSIVE
  11443. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11444. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11445. outgoingLightNode = outgoingLightNode.add( emissive );
  11446. }
  11447. return outgoingLightNode;
  11448. }
  11449. /**
  11450. * Setups the output node.
  11451. *
  11452. * @param {NodeBuilder} builder - The current node builder.
  11453. * @param {Node<vec4>} outputNode - The existing output node.
  11454. * @return {Node<vec4>} The output node.
  11455. */
  11456. setupOutput( builder, outputNode ) {
  11457. // FOG
  11458. if ( this.fog === true ) {
  11459. const fogNode = builder.fogNode;
  11460. if ( fogNode ) {
  11461. output.assign( outputNode );
  11462. outputNode = vec4( fogNode );
  11463. }
  11464. }
  11465. return outputNode;
  11466. }
  11467. /**
  11468. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11469. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11470. * defining all material properties of the classic type in the node type.
  11471. *
  11472. * @param {Material} material - The material to copy properties with their values to this node material.
  11473. */
  11474. setDefaultValues( material ) {
  11475. // This approach is to reuse the native refreshUniforms*
  11476. // and turn available the use of features like transmission and environment in core
  11477. for ( const property in material ) {
  11478. const value = material[ property ];
  11479. if ( this[ property ] === undefined ) {
  11480. this[ property ] = value;
  11481. if ( value && value.clone ) this[ property ] = value.clone();
  11482. }
  11483. }
  11484. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11485. for ( const key in descriptors ) {
  11486. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11487. descriptors[ key ].get !== undefined ) {
  11488. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11489. }
  11490. }
  11491. }
  11492. /**
  11493. * Serializes this material to JSON.
  11494. *
  11495. * @param {(Object|String)?} meta - The meta information for serialization.
  11496. * @return {Object} The serialized node.
  11497. */
  11498. toJSON( meta ) {
  11499. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11500. if ( isRoot ) {
  11501. meta = {
  11502. textures: {},
  11503. images: {},
  11504. nodes: {}
  11505. };
  11506. }
  11507. const data = Material.prototype.toJSON.call( this, meta );
  11508. const nodeChildren = getNodeChildren( this );
  11509. data.inputNodes = {};
  11510. for ( const { property, childNode } of nodeChildren ) {
  11511. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11512. }
  11513. // TODO: Copied from Object3D.toJSON
  11514. function extractFromCache( cache ) {
  11515. const values = [];
  11516. for ( const key in cache ) {
  11517. const data = cache[ key ];
  11518. delete data.metadata;
  11519. values.push( data );
  11520. }
  11521. return values;
  11522. }
  11523. if ( isRoot ) {
  11524. const textures = extractFromCache( meta.textures );
  11525. const images = extractFromCache( meta.images );
  11526. const nodes = extractFromCache( meta.nodes );
  11527. if ( textures.length > 0 ) data.textures = textures;
  11528. if ( images.length > 0 ) data.images = images;
  11529. if ( nodes.length > 0 ) data.nodes = nodes;
  11530. }
  11531. return data;
  11532. }
  11533. /**
  11534. * Copies the properties of the given node material to this instance.
  11535. *
  11536. * @param {NodeMaterial} source - The material to copy.
  11537. * @return {NodeMaterial} A reference to this node material.
  11538. */
  11539. copy( source ) {
  11540. this.lightsNode = source.lightsNode;
  11541. this.envNode = source.envNode;
  11542. this.colorNode = source.colorNode;
  11543. this.normalNode = source.normalNode;
  11544. this.opacityNode = source.opacityNode;
  11545. this.backdropNode = source.backdropNode;
  11546. this.backdropAlphaNode = source.backdropAlphaNode;
  11547. this.alphaTestNode = source.alphaTestNode;
  11548. this.positionNode = source.positionNode;
  11549. this.geometryNode = source.geometryNode;
  11550. this.depthNode = source.depthNode;
  11551. this.shadowPositionNode = source.shadowPositionNode;
  11552. this.receivedShadowNode = source.receivedShadowNode;
  11553. this.castShadowNode = source.castShadowNode;
  11554. this.outputNode = source.outputNode;
  11555. this.mrtNode = source.mrtNode;
  11556. this.fragmentNode = source.fragmentNode;
  11557. this.vertexNode = source.vertexNode;
  11558. return super.copy( source );
  11559. }
  11560. }
  11561. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  11562. /**
  11563. * Unlike WebGL, WebGPU can render point primitives only with a size
  11564. * of one pixel. This type node material can be used to mimic the WebGL
  11565. * points rendering by rendering small planes via instancing.
  11566. *
  11567. * This material should be used with {@link InstancedPointsGeometry}.
  11568. *
  11569. * @augments NodeMaterial
  11570. */
  11571. class InstancedPointsNodeMaterial extends NodeMaterial {
  11572. static get type() {
  11573. return 'InstancedPointsNodeMaterial';
  11574. }
  11575. /**
  11576. * Constructs a new instanced points node material.
  11577. *
  11578. * @param {Object?} parameters - The configuration parameter.
  11579. */
  11580. constructor( parameters = {} ) {
  11581. super();
  11582. /**
  11583. * This flag can be used for type testing.
  11584. *
  11585. * @type {Boolean}
  11586. * @readonly
  11587. * @default true
  11588. */
  11589. this.isInstancedPointsNodeMaterial = true;
  11590. /**
  11591. * Whether vertex colors should be used or not. If set to `true`,
  11592. * each point instance can receive a custom color value.
  11593. *
  11594. * @type {Boolean}
  11595. * @default false
  11596. */
  11597. this.useColor = parameters.vertexColors;
  11598. /**
  11599. * The points width in pixels.
  11600. *
  11601. * @type {Number}
  11602. * @default 1
  11603. */
  11604. this.pointWidth = 1;
  11605. /**
  11606. * This node can be used to define the colors for each instance.
  11607. *
  11608. * @type {Node<vec3>?}
  11609. * @default null
  11610. */
  11611. this.pointColorNode = null;
  11612. /**
  11613. * This node can be used to define the width for each point instance.
  11614. *
  11615. * @type {Node<float>?}
  11616. * @default null
  11617. */
  11618. this.pointWidthNode = null;
  11619. this._useAlphaToCoverage = true;
  11620. this.setDefaultValues( _defaultValues$e );
  11621. this.setValues( parameters );
  11622. }
  11623. /**
  11624. * Setups the vertex and fragment stage of this node material.
  11625. *
  11626. * @param {NodeBuilder} builder - The current node builder.
  11627. */
  11628. setup( builder ) {
  11629. const { renderer } = builder;
  11630. const useAlphaToCoverage = this._useAlphaToCoverage;
  11631. const useColor = this.useColor;
  11632. this.vertexNode = Fn( () => {
  11633. const instancePosition = attribute( 'instancePosition' ).xyz;
  11634. // camera space
  11635. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  11636. const aspect = viewport.z.div( viewport.w );
  11637. // clip space
  11638. const clipPos = cameraProjectionMatrix.mul( mvPos );
  11639. // offset in ndc space
  11640. const offset = positionGeometry.xy.toVar();
  11641. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  11642. offset.assign( offset.div( viewport.z ) );
  11643. offset.y.assign( offset.y.mul( aspect ) );
  11644. // back to clip space
  11645. offset.assign( offset.mul( clipPos.w ) );
  11646. //clipPos.xy += offset;
  11647. clipPos.addAssign( vec4( offset, 0, 0 ) );
  11648. return clipPos;
  11649. } )();
  11650. this.fragmentNode = Fn( () => {
  11651. const alpha = float( 1 ).toVar();
  11652. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  11653. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  11654. const dlen = float( len2.fwidth() ).toVar();
  11655. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  11656. } else {
  11657. len2.greaterThan( 1.0 ).discard();
  11658. }
  11659. let pointColorNode;
  11660. if ( this.pointColorNode ) {
  11661. pointColorNode = this.pointColorNode;
  11662. } else {
  11663. if ( useColor ) {
  11664. const instanceColor = attribute( 'instanceColor' );
  11665. pointColorNode = instanceColor.mul( materialColor );
  11666. } else {
  11667. pointColorNode = materialColor;
  11668. }
  11669. }
  11670. alpha.mulAssign( materialOpacity );
  11671. return vec4( pointColorNode, alpha );
  11672. } )();
  11673. super.setup( builder );
  11674. }
  11675. /**
  11676. * Whether alpha to coverage should be used or not.
  11677. *
  11678. * @type {Boolean}
  11679. * @default true
  11680. */
  11681. get alphaToCoverage() {
  11682. return this._useAlphaToCoverage;
  11683. }
  11684. set alphaToCoverage( value ) {
  11685. if ( this._useAlphaToCoverage !== value ) {
  11686. this._useAlphaToCoverage = value;
  11687. this.needsUpdate = true;
  11688. }
  11689. }
  11690. }
  11691. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11692. /**
  11693. * Node material version of `LineBasicMaterial`.
  11694. *
  11695. * @augments NodeMaterial
  11696. */
  11697. class LineBasicNodeMaterial extends NodeMaterial {
  11698. static get type() {
  11699. return 'LineBasicNodeMaterial';
  11700. }
  11701. /**
  11702. * Constructs a new line basic node material.
  11703. *
  11704. * @param {Object?} parameters - The configuration parameter.
  11705. */
  11706. constructor( parameters ) {
  11707. super();
  11708. /**
  11709. * This flag can be used for type testing.
  11710. *
  11711. * @type {Boolean}
  11712. * @readonly
  11713. * @default true
  11714. */
  11715. this.isLineBasicNodeMaterial = true;
  11716. this.setDefaultValues( _defaultValues$d );
  11717. this.setValues( parameters );
  11718. }
  11719. }
  11720. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11721. /**
  11722. * Node material version of `LineDashedMaterial`.
  11723. *
  11724. * @augments NodeMaterial
  11725. */
  11726. class LineDashedNodeMaterial extends NodeMaterial {
  11727. static get type() {
  11728. return 'LineDashedNodeMaterial';
  11729. }
  11730. /**
  11731. * Constructs a new line dashed node material.
  11732. *
  11733. * @param {Object?} parameters - The configuration parameter.
  11734. */
  11735. constructor( parameters ) {
  11736. super();
  11737. /**
  11738. * This flag can be used for type testing.
  11739. *
  11740. * @type {Boolean}
  11741. * @readonly
  11742. * @default true
  11743. */
  11744. this.isLineDashedNodeMaterial = true;
  11745. this.setDefaultValues( _defaultValues$c );
  11746. /**
  11747. * The dash offset.
  11748. *
  11749. * @type {Number}
  11750. * @default 0
  11751. */
  11752. this.dashOffset = 0;
  11753. /**
  11754. * The offset of dash materials is by default inferred from the `dashOffset`
  11755. * property. This node property allows to overwrite the default
  11756. * and define the offset with a node instead.
  11757. *
  11758. * If you don't want to overwrite the offset but modify the existing
  11759. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11760. *
  11761. * @type {Node<float>?}
  11762. * @default null
  11763. */
  11764. this.offsetNode = null;
  11765. /**
  11766. * The scale of dash materials is by default inferred from the `scale`
  11767. * property. This node property allows to overwrite the default
  11768. * and define the scale with a node instead.
  11769. *
  11770. * If you don't want to overwrite the scale but modify the existing
  11771. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11772. *
  11773. * @type {Node<float>?}
  11774. * @default null
  11775. */
  11776. this.dashScaleNode = null;
  11777. /**
  11778. * The dash size of dash materials is by default inferred from the `dashSize`
  11779. * property. This node property allows to overwrite the default
  11780. * and define the dash size with a node instead.
  11781. *
  11782. * If you don't want to overwrite the dash size but modify the existing
  11783. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11784. *
  11785. * @type {Node<float>?}
  11786. * @default null
  11787. */
  11788. this.dashSizeNode = null;
  11789. /**
  11790. * The gap size of dash materials is by default inferred from the `gapSize`
  11791. * property. This node property allows to overwrite the default
  11792. * and define the gap size with a node instead.
  11793. *
  11794. * If you don't want to overwrite the gap size but modify the existing
  11795. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11796. *
  11797. * @type {Node<float>?}
  11798. * @default null
  11799. */
  11800. this.gapSizeNode = null;
  11801. this.setValues( parameters );
  11802. }
  11803. /**
  11804. * Setups the dash specific node variables.
  11805. *
  11806. * @param {NodeBuilder} builder - The current node builder.
  11807. */
  11808. setupVariants( /* builder */ ) {
  11809. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  11810. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11811. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11812. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11813. dashSize.assign( dashSizeNode );
  11814. gapSize.assign( gapSizeNode );
  11815. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11816. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11817. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11818. }
  11819. }
  11820. /** @module ViewportSharedTextureNode **/
  11821. let _sharedFramebuffer = null;
  11822. /**
  11823. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11824. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11825. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11826. *
  11827. * @augments module:ViewportTextureNode~ViewportTextureNode
  11828. */
  11829. class ViewportSharedTextureNode extends ViewportTextureNode {
  11830. static get type() {
  11831. return 'ViewportSharedTextureNode';
  11832. }
  11833. /**
  11834. * Constructs a new viewport shared texture node.
  11835. *
  11836. * @param {Node} [uvNode=screenUV] - The uv node.
  11837. * @param {Node?} [levelNode=null] - The level node.
  11838. */
  11839. constructor( uvNode = screenUV, levelNode = null ) {
  11840. if ( _sharedFramebuffer === null ) {
  11841. _sharedFramebuffer = new FramebufferTexture();
  11842. }
  11843. super( uvNode, levelNode, _sharedFramebuffer );
  11844. }
  11845. updateReference() {
  11846. return this;
  11847. }
  11848. }
  11849. /**
  11850. * TSL function for creating a shared viewport texture node.
  11851. *
  11852. * @function
  11853. * @param {Node} [uvNode=screenUV] - The uv node.
  11854. * @param {Node?} [levelNode=null] - The level node.
  11855. * @returns {ViewportSharedTextureNode}
  11856. */
  11857. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11858. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11859. /**
  11860. * This node material can be used to render lines with a size larger than one
  11861. * by representing them as instanced meshes.
  11862. *
  11863. * @augments NodeMaterial
  11864. */
  11865. class Line2NodeMaterial extends NodeMaterial {
  11866. static get type() {
  11867. return 'Line2NodeMaterial';
  11868. }
  11869. /**
  11870. * Constructs a new node material for wide line rendering.
  11871. *
  11872. * @param {Object?} parameters - The configuration parameter.
  11873. */
  11874. constructor( parameters = {} ) {
  11875. super();
  11876. /**
  11877. * This flag can be used for type testing.
  11878. *
  11879. * @type {Boolean}
  11880. * @readonly
  11881. * @default true
  11882. */
  11883. this.isLine2NodeMaterial = true;
  11884. this.setDefaultValues( _defaultValues$b );
  11885. /**
  11886. * Whether vertex colors should be used or not.
  11887. *
  11888. * @type {Boolean}
  11889. * @default false
  11890. */
  11891. this.useColor = parameters.vertexColors;
  11892. /**
  11893. * The dash offset.
  11894. *
  11895. * @type {Number}
  11896. * @default 0
  11897. */
  11898. this.dashOffset = 0;
  11899. /**
  11900. * The line width.
  11901. *
  11902. * @type {Number}
  11903. * @default 0
  11904. */
  11905. this.lineWidth = 1;
  11906. /**
  11907. * Defines the lines color.
  11908. *
  11909. * @type {Node<vec3>?}
  11910. * @default null
  11911. */
  11912. this.lineColorNode = null;
  11913. /**
  11914. * Defines the offset.
  11915. *
  11916. * @type {Node<float>?}
  11917. * @default null
  11918. */
  11919. this.offsetNode = null;
  11920. /**
  11921. * Defines the dash scale.
  11922. *
  11923. * @type {Node<float>?}
  11924. * @default null
  11925. */
  11926. this.dashScaleNode = null;
  11927. /**
  11928. * Defines the dash size.
  11929. *
  11930. * @type {Node<float>?}
  11931. * @default null
  11932. */
  11933. this.dashSizeNode = null;
  11934. /**
  11935. * Defines the gap size.
  11936. *
  11937. * @type {Node<float>?}
  11938. * @default null
  11939. */
  11940. this.gapSizeNode = null;
  11941. /**
  11942. * Blending is set to `NoBlending` since transparency
  11943. * is not supported, yet.
  11944. *
  11945. * @type {Number}
  11946. * @default 0
  11947. */
  11948. this.blending = NoBlending;
  11949. this._useDash = parameters.dashed;
  11950. this._useAlphaToCoverage = true;
  11951. this._useWorldUnits = false;
  11952. this.setValues( parameters );
  11953. }
  11954. /**
  11955. * Setups the vertex and fragment stage of this node material.
  11956. *
  11957. * @param {NodeBuilder} builder - The current node builder.
  11958. */
  11959. setup( builder ) {
  11960. const { renderer } = builder;
  11961. const useAlphaToCoverage = this._useAlphaToCoverage;
  11962. const useColor = this.useColor;
  11963. const useDash = this._useDash;
  11964. const useWorldUnits = this._useWorldUnits;
  11965. const trimSegment = Fn( ( { start, end } ) => {
  11966. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  11967. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  11968. const nearEstimate = b.mul( - 0.5 ).div( a );
  11969. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  11970. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  11971. } ).setLayout( {
  11972. name: 'trimSegment',
  11973. type: 'vec4',
  11974. inputs: [
  11975. { name: 'start', type: 'vec4' },
  11976. { name: 'end', type: 'vec4' }
  11977. ]
  11978. } );
  11979. this.vertexNode = Fn( () => {
  11980. const instanceStart = attribute( 'instanceStart' );
  11981. const instanceEnd = attribute( 'instanceEnd' );
  11982. // camera space
  11983. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  11984. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  11985. if ( useDash ) {
  11986. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11987. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11988. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  11989. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  11990. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  11991. lineDistance = lineDistance.add( offsetNode );
  11992. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  11993. }
  11994. if ( useWorldUnits ) {
  11995. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  11996. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  11997. }
  11998. const aspect = viewport.z.div( viewport.w );
  11999. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12000. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12001. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12002. // perhaps there is a more elegant solution -- WestLangley
  12003. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12004. If( perspective, () => {
  12005. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12006. end.assign( trimSegment( { start: start, end: end } ) );
  12007. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12008. start.assign( trimSegment( { start: end, end: start } ) );
  12009. } );
  12010. } );
  12011. // clip space
  12012. const clipStart = cameraProjectionMatrix.mul( start );
  12013. const clipEnd = cameraProjectionMatrix.mul( end );
  12014. // ndc space
  12015. const ndcStart = clipStart.xyz.div( clipStart.w );
  12016. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12017. // direction
  12018. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12019. // account for clip-space aspect ratio
  12020. dir.x.assign( dir.x.mul( aspect ) );
  12021. dir.assign( dir.normalize() );
  12022. const clip = vec4().toVar();
  12023. if ( useWorldUnits ) {
  12024. // get the offset direction as perpendicular to the view vector
  12025. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12026. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12027. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12028. const worldFwd = worldDir.cross( worldUp );
  12029. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12030. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12031. // height offset
  12032. const hw = materialLineWidth.mul( 0.5 );
  12033. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12034. // don't extend the line if we're rendering dashes because we
  12035. // won't be rendering the endcaps
  12036. if ( ! useDash ) {
  12037. // cap extension
  12038. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12039. // add width to the box
  12040. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12041. // endcaps
  12042. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12043. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12044. } );
  12045. }
  12046. // project the worldpos
  12047. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12048. // shift the depth of the projected points so the line
  12049. // segments overlap neatly
  12050. const clipPose = vec3().toVar();
  12051. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12052. clip.z.assign( clipPose.z.mul( clip.w ) );
  12053. } else {
  12054. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12055. // undo aspect ratio adjustment
  12056. dir.x.assign( dir.x.div( aspect ) );
  12057. offset.x.assign( offset.x.div( aspect ) );
  12058. // sign flip
  12059. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12060. // endcaps
  12061. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12062. offset.assign( offset.sub( dir ) );
  12063. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12064. offset.assign( offset.add( dir ) );
  12065. } );
  12066. // adjust for linewidth
  12067. offset.assign( offset.mul( materialLineWidth ) );
  12068. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12069. offset.assign( offset.div( viewport.w ) );
  12070. // select end
  12071. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12072. // back to clip space
  12073. offset.assign( offset.mul( clip.w ) );
  12074. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12075. }
  12076. return clip;
  12077. } )();
  12078. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12079. const p13 = p1.sub( p3 );
  12080. const p43 = p4.sub( p3 );
  12081. const p21 = p2.sub( p1 );
  12082. const d1343 = p13.dot( p43 );
  12083. const d4321 = p43.dot( p21 );
  12084. const d1321 = p13.dot( p21 );
  12085. const d4343 = p43.dot( p43 );
  12086. const d2121 = p21.dot( p21 );
  12087. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12088. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12089. const mua = numer.div( denom ).clamp();
  12090. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12091. return vec2( mua, mub );
  12092. } );
  12093. this.colorNode = Fn( () => {
  12094. const vUv = uv();
  12095. if ( useDash ) {
  12096. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12097. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12098. dashSize.assign( dashSizeNode );
  12099. gapSize.assign( gapSizeNode );
  12100. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12101. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12102. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12103. }
  12104. const alpha = float( 1 ).toVar( 'alpha' );
  12105. if ( useWorldUnits ) {
  12106. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12107. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12108. // Find the closest points on the view ray and the line segment
  12109. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12110. const lineDir = worldEnd.sub( worldStart );
  12111. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12112. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12113. const p2 = rayEnd.mul( params.y );
  12114. const delta = p1.sub( p2 );
  12115. const len = delta.length();
  12116. const norm = len.div( materialLineWidth );
  12117. if ( ! useDash ) {
  12118. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12119. const dnorm = norm.fwidth();
  12120. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12121. } else {
  12122. norm.greaterThan( 0.5 ).discard();
  12123. }
  12124. }
  12125. } else {
  12126. // round endcaps
  12127. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12128. const a = vUv.x;
  12129. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12130. const len2 = a.mul( a ).add( b.mul( b ) );
  12131. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12132. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12133. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12134. } );
  12135. } else {
  12136. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12137. const a = vUv.x;
  12138. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12139. const len2 = a.mul( a ).add( b.mul( b ) );
  12140. len2.greaterThan( 1.0 ).discard();
  12141. } );
  12142. }
  12143. }
  12144. let lineColorNode;
  12145. if ( this.lineColorNode ) {
  12146. lineColorNode = this.lineColorNode;
  12147. } else {
  12148. if ( useColor ) {
  12149. const instanceColorStart = attribute( 'instanceColorStart' );
  12150. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12151. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12152. lineColorNode = instanceColor.mul( materialColor );
  12153. } else {
  12154. lineColorNode = materialColor;
  12155. }
  12156. }
  12157. return vec4( lineColorNode, alpha );
  12158. } )();
  12159. if ( this.transparent ) {
  12160. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12161. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12162. }
  12163. super.setup( builder );
  12164. }
  12165. /**
  12166. * Whether the lines should sized in world units or not.
  12167. * When set to `false` the unit is pixel.
  12168. *
  12169. * @type {Boolean}
  12170. * @default false
  12171. */
  12172. get worldUnits() {
  12173. return this._useWorldUnits;
  12174. }
  12175. set worldUnits( value ) {
  12176. if ( this._useWorldUnits !== value ) {
  12177. this._useWorldUnits = value;
  12178. this.needsUpdate = true;
  12179. }
  12180. }
  12181. /**
  12182. * Whether the lines should be dashed or not.
  12183. *
  12184. * @type {Boolean}
  12185. * @default false
  12186. */
  12187. get dashed() {
  12188. return this._useDash;
  12189. }
  12190. set dashed( value ) {
  12191. if ( this._useDash !== value ) {
  12192. this._useDash = value;
  12193. this.needsUpdate = true;
  12194. }
  12195. }
  12196. /**
  12197. * Whether alpha to coverage should be used or not.
  12198. *
  12199. * @type {Boolean}
  12200. * @default true
  12201. */
  12202. get alphaToCoverage() {
  12203. return this._useAlphaToCoverage;
  12204. }
  12205. set alphaToCoverage( value ) {
  12206. if ( this._useAlphaToCoverage !== value ) {
  12207. this._useAlphaToCoverage = value;
  12208. this.needsUpdate = true;
  12209. }
  12210. }
  12211. }
  12212. /** @module Packing **/
  12213. /**
  12214. * Packs a direction vector into a color value.
  12215. *
  12216. * @method
  12217. * @param {Node<vec3>} node - The direction to pack.
  12218. * @return {Node<vec3>} The color.
  12219. */
  12220. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12221. /**
  12222. * Unpacks a color value into a direction vector.
  12223. *
  12224. * @method
  12225. * @param {Node<vec3>} node - The color to unpack.
  12226. * @return {Node<vec3>} The direction.
  12227. */
  12228. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12229. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12230. /**
  12231. * Node material version of `MeshNormalMaterial`.
  12232. *
  12233. * @augments NodeMaterial
  12234. */
  12235. class MeshNormalNodeMaterial extends NodeMaterial {
  12236. static get type() {
  12237. return 'MeshNormalNodeMaterial';
  12238. }
  12239. /**
  12240. * Constructs a new mesh normal node material.
  12241. *
  12242. * @param {Object?} parameters - The configuration parameter.
  12243. */
  12244. constructor( parameters ) {
  12245. super();
  12246. /**
  12247. * This flag can be used for type testing.
  12248. *
  12249. * @type {Boolean}
  12250. * @readonly
  12251. * @default true
  12252. */
  12253. this.isMeshNormalNodeMaterial = true;
  12254. this.setDefaultValues( _defaultValues$a );
  12255. this.setValues( parameters );
  12256. }
  12257. /**
  12258. * Overwrites the default implementation by computing the diffuse color
  12259. * based on the normal data.
  12260. */
  12261. setupDiffuseColor() {
  12262. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12263. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12264. }
  12265. }
  12266. /** @module EquirectUVNode **/
  12267. /**
  12268. * Can be used to compute texture coordinates for projecting an
  12269. * equirectangular texture onto a mesh for using it as the scene's
  12270. * background.
  12271. *
  12272. * ```js
  12273. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12274. * ```
  12275. *
  12276. * @augments TempNode
  12277. */
  12278. class EquirectUVNode extends TempNode {
  12279. static get type() {
  12280. return 'EquirectUVNode';
  12281. }
  12282. /**
  12283. * Constructs a new equirect uv node.
  12284. *
  12285. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12286. */
  12287. constructor( dirNode = positionWorldDirection ) {
  12288. super( 'vec2' );
  12289. /**
  12290. * A direction vector for sampling why is by default `positionWorldDirection`.
  12291. *
  12292. * @type {Node<vec3>}
  12293. */
  12294. this.dirNode = dirNode;
  12295. }
  12296. setup() {
  12297. const dir = this.dirNode;
  12298. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12299. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12300. return vec2( u, v );
  12301. }
  12302. }
  12303. /**
  12304. * TSL function for creating an equirect uv node.
  12305. *
  12306. * @function
  12307. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12308. * @returns {EquirectUVNode}
  12309. */
  12310. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12311. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12312. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12313. constructor( size = 1, options = {} ) {
  12314. super( size, options );
  12315. this.isCubeRenderTarget = true;
  12316. }
  12317. fromEquirectangularTexture( renderer, texture$1 ) {
  12318. const currentMinFilter = texture$1.minFilter;
  12319. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12320. texture$1.generateMipmaps = true;
  12321. this.texture.type = texture$1.type;
  12322. this.texture.colorSpace = texture$1.colorSpace;
  12323. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12324. this.texture.minFilter = texture$1.minFilter;
  12325. this.texture.magFilter = texture$1.magFilter;
  12326. const geometry = new BoxGeometry( 5, 5, 5 );
  12327. const uvNode = equirectUV( positionWorldDirection );
  12328. const material = new NodeMaterial();
  12329. material.colorNode = texture( texture$1, uvNode, 0 );
  12330. material.side = BackSide;
  12331. material.blending = NoBlending;
  12332. const mesh = new Mesh( geometry, material );
  12333. const scene = new Scene();
  12334. scene.add( mesh );
  12335. // Avoid blurred poles
  12336. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12337. const camera = new CubeCamera( 1, 10, this );
  12338. const currentMRT = renderer.getMRT();
  12339. renderer.setMRT( null );
  12340. camera.update( renderer, scene );
  12341. renderer.setMRT( currentMRT );
  12342. texture$1.minFilter = currentMinFilter;
  12343. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12344. mesh.geometry.dispose();
  12345. mesh.material.dispose();
  12346. return this;
  12347. }
  12348. }
  12349. /** @module CubeMapNode **/
  12350. const _cache$1 = new WeakMap();
  12351. /**
  12352. * This node can be used to automatically convert environment maps in the
  12353. * equirectangular format into the cube map format.
  12354. *
  12355. * @augments TempNode
  12356. */
  12357. class CubeMapNode extends TempNode {
  12358. static get type() {
  12359. return 'CubeMapNode';
  12360. }
  12361. /**
  12362. * Constructs a new cube map node.
  12363. *
  12364. * @param {Node} envNode - The node representing the environment map.
  12365. */
  12366. constructor( envNode ) {
  12367. super( 'vec3' );
  12368. /**
  12369. * The node representing the environment map.
  12370. *
  12371. * @type {Node}
  12372. */
  12373. this.envNode = envNode;
  12374. /**
  12375. * A reference to the internal cube texture.
  12376. *
  12377. * @private
  12378. * @type {CubeTexture}
  12379. * @default null
  12380. */
  12381. this._cubeTexture = null;
  12382. /**
  12383. * A reference to the internal cube texture node.
  12384. *
  12385. * @private
  12386. * @type {CubeTextureNode}
  12387. */
  12388. this._cubeTextureNode = cubeTexture();
  12389. const defaultTexture = new CubeTexture();
  12390. defaultTexture.isRenderTargetTexture = true;
  12391. /**
  12392. * A default cube texture that acts as a placeholder.
  12393. * It is used when the conversion from equirectangular to cube
  12394. * map has not finished yet for a given texture.
  12395. *
  12396. * @private
  12397. * @type {CubeTexture}
  12398. */
  12399. this._defaultTexture = defaultTexture;
  12400. /**
  12401. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12402. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12403. *
  12404. * @type {String}
  12405. * @default 'render'
  12406. */
  12407. this.updateBeforeType = NodeUpdateType.RENDER;
  12408. }
  12409. updateBefore( frame ) {
  12410. const { renderer, material } = frame;
  12411. const envNode = this.envNode;
  12412. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12413. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12414. if ( texture && texture.isTexture ) {
  12415. const mapping = texture.mapping;
  12416. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12417. // check for converted cubemap map
  12418. if ( _cache$1.has( texture ) ) {
  12419. const cubeMap = _cache$1.get( texture );
  12420. mapTextureMapping( cubeMap, texture.mapping );
  12421. this._cubeTexture = cubeMap;
  12422. } else {
  12423. // create cube map from equirectangular map
  12424. const image = texture.image;
  12425. if ( isEquirectangularMapReady$1( image ) ) {
  12426. const renderTarget = new CubeRenderTarget( image.height );
  12427. renderTarget.fromEquirectangularTexture( renderer, texture );
  12428. mapTextureMapping( renderTarget.texture, texture.mapping );
  12429. this._cubeTexture = renderTarget.texture;
  12430. _cache$1.set( texture, renderTarget.texture );
  12431. texture.addEventListener( 'dispose', onTextureDispose );
  12432. } else {
  12433. // default cube texture as fallback when equirectangular texture is not yet loaded
  12434. this._cubeTexture = this._defaultTexture;
  12435. }
  12436. }
  12437. //
  12438. this._cubeTextureNode.value = this._cubeTexture;
  12439. } else {
  12440. // envNode already refers to a cube map
  12441. this._cubeTextureNode = this.envNode;
  12442. }
  12443. }
  12444. }
  12445. }
  12446. setup( builder ) {
  12447. this.updateBefore( builder );
  12448. return this._cubeTextureNode;
  12449. }
  12450. }
  12451. /**
  12452. * Returns true if the given equirectangular image has been fully loaded
  12453. * and is ready for further processing.
  12454. *
  12455. * @private
  12456. * @param {Image} image - The equirectangular image to check.
  12457. * @return {Boolean} Whether the image is ready or not.
  12458. */
  12459. function isEquirectangularMapReady$1( image ) {
  12460. if ( image === null || image === undefined ) return false;
  12461. return image.height > 0;
  12462. }
  12463. /**
  12464. * This function is executed when `dispose()` is called on the equirectangular
  12465. * texture. In this case, the generated cube map with its render target
  12466. * is deleted as well.
  12467. *
  12468. * @private
  12469. * @param {Object} event - The event object.
  12470. */
  12471. function onTextureDispose( event ) {
  12472. const texture = event.target;
  12473. texture.removeEventListener( 'dispose', onTextureDispose );
  12474. const renderTarget = _cache$1.get( texture );
  12475. if ( renderTarget !== undefined ) {
  12476. _cache$1.delete( texture );
  12477. renderTarget.dispose();
  12478. }
  12479. }
  12480. /**
  12481. * This function makes sure the generated cube map uses the correct
  12482. * texture mapping that corresponds to the equirectangular original.
  12483. *
  12484. * @private
  12485. * @param {Texture} texture - The cube texture.
  12486. * @param {Number} mapping - The original texture mapping.
  12487. */
  12488. function mapTextureMapping( texture, mapping ) {
  12489. if ( mapping === EquirectangularReflectionMapping ) {
  12490. texture.mapping = CubeReflectionMapping;
  12491. } else if ( mapping === EquirectangularRefractionMapping ) {
  12492. texture.mapping = CubeRefractionMapping;
  12493. }
  12494. }
  12495. /**
  12496. * TSL function for creating a cube map node.
  12497. *
  12498. * @function
  12499. * @param {Node} envNode - The node representing the environment map.
  12500. * @returns {CubeMapNode}
  12501. */
  12502. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12503. /**
  12504. * Represents a basic model for Image-based lighting (IBL). The environment
  12505. * is defined via environment maps in the equirectangular or cube map format.
  12506. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12507. * or {@link MeshPhongNodeMaterial}.
  12508. *
  12509. * @augments LightingNode
  12510. */
  12511. class BasicEnvironmentNode extends LightingNode {
  12512. static get type() {
  12513. return 'BasicEnvironmentNode';
  12514. }
  12515. /**
  12516. * Constructs a new basic environment node.
  12517. *
  12518. * @param {Node} [envNode=null] - A node representing the environment.
  12519. */
  12520. constructor( envNode = null ) {
  12521. super();
  12522. /**
  12523. * A node representing the environment.
  12524. *
  12525. * @type {Node}
  12526. * @default null
  12527. */
  12528. this.envNode = envNode;
  12529. }
  12530. setup( builder ) {
  12531. // environment property is used in the finish() method of BasicLightingModel
  12532. builder.context.environment = cubeMapNode( this.envNode );
  12533. }
  12534. }
  12535. /**
  12536. * A specific version of {@link IrradianceNode} that is only relevant
  12537. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12538. * requires a special scaling factor for the light map.
  12539. *
  12540. * @augments LightingNode
  12541. */
  12542. class BasicLightMapNode extends LightingNode {
  12543. static get type() {
  12544. return 'BasicLightMapNode';
  12545. }
  12546. /**
  12547. * Constructs a new basic light map node.
  12548. *
  12549. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12550. */
  12551. constructor( lightMapNode = null ) {
  12552. super();
  12553. /**
  12554. * The light map node.
  12555. *
  12556. * @type {Node<vec3>?}
  12557. */
  12558. this.lightMapNode = lightMapNode;
  12559. }
  12560. setup( builder ) {
  12561. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12562. const RECIPROCAL_PI = float( 1 / Math.PI );
  12563. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12564. }
  12565. }
  12566. /**
  12567. * Abstract class for implementing lighting models. The module defines
  12568. * multiple methods that concrete lighting models can implement. These
  12569. * methods are executed at different points during the light evaluation
  12570. * process.
  12571. */
  12572. class LightingModel {
  12573. /**
  12574. * This method is intended for setting up lighting model and context data
  12575. * which are later used in the evaluation process.
  12576. *
  12577. * @abstract
  12578. * @param {ContextNode} input - The current node context.
  12579. * @param {StackNode} stack - The current stack.
  12580. * @param {NodeBuilder} builder - The current node builder.
  12581. */
  12582. start( /*input, stack, builder*/ ) { }
  12583. /**
  12584. * This method is intended for executing final tasks like final updates
  12585. * to the outgoing light.
  12586. *
  12587. * @abstract
  12588. * @param {ContextNode} input - The current node context.
  12589. * @param {StackNode} stack - The current stack.
  12590. * @param {NodeBuilder} builder - The current node builder.
  12591. */
  12592. finish( /*input, stack, builder*/ ) { }
  12593. /**
  12594. * This method is intended for implementing the direct light term and
  12595. * executed during the build process of directional, point and spot light nodes.
  12596. *
  12597. * @abstract
  12598. * @param {Object} input - The input data.
  12599. * @param {StackNode} stack - The current stack.
  12600. * @param {NodeBuilder} builder - The current node builder.
  12601. */
  12602. direct( /*input, stack, builder*/ ) { }
  12603. /**
  12604. * This method is intended for implementing the direct light term for
  12605. * rect area light nodes.
  12606. *
  12607. * @abstract
  12608. * @param {Object} input - The input data.
  12609. * @param {StackNode} stack - The current stack.
  12610. * @param {NodeBuilder} builder - The current node builder.
  12611. */
  12612. directRectArea( /*input, stack, builder*/ ) {}
  12613. /**
  12614. * This method is intended for implementing the indirect light term.
  12615. *
  12616. * @abstract
  12617. * @param {ContextNode} input - The current node context.
  12618. * @param {StackNode} stack - The current stack.
  12619. * @param {NodeBuilder} builder - The current node builder.
  12620. */
  12621. indirect( /*input, stack, builder*/ ) { }
  12622. /**
  12623. * This method is intended for implementing the ambient occlusion term.
  12624. * Unlike other methods, this method must be called manually by the lighting
  12625. * model in its indirect term.
  12626. *
  12627. * @abstract
  12628. * @param {ContextNode} input - The current node context.
  12629. * @param {StackNode} stack - The current stack.
  12630. * @param {NodeBuilder} builder - The current node builder.
  12631. */
  12632. ambientOcclusion( /*input, stack, builder*/ ) { }
  12633. }
  12634. /**
  12635. * Represents the lighting model for unlit materials. The only light contribution
  12636. * is baked indirect lighting modulated with ambient occlusion and the material's
  12637. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12638. *
  12639. * @augments LightingModel
  12640. */
  12641. class BasicLightingModel extends LightingModel {
  12642. /**
  12643. * Constructs a new basic lighting model.
  12644. */
  12645. constructor() {
  12646. super();
  12647. }
  12648. /**
  12649. * Implements the baked indirect lighting with its modulation.
  12650. *
  12651. * @param {ContextNode} context - The current node context.
  12652. * @param {StackNode} stack - The current stack.
  12653. * @param {NodeBuilder} builder - The current node builder.
  12654. */
  12655. indirect( context, stack, builder ) {
  12656. const ambientOcclusion = context.ambientOcclusion;
  12657. const reflectedLight = context.reflectedLight;
  12658. const irradianceLightMap = builder.context.irradianceLightMap;
  12659. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12660. // accumulation (baked indirect lighting only)
  12661. if ( irradianceLightMap ) {
  12662. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12663. } else {
  12664. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12665. }
  12666. // modulation
  12667. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12668. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12669. }
  12670. /**
  12671. * Implements the environment mapping.
  12672. *
  12673. * @param {ContextNode} context - The current node context.
  12674. * @param {StackNode} stack - The current stack.
  12675. * @param {NodeBuilder} builder - The current node builder.
  12676. */
  12677. finish( context, stack, builder ) {
  12678. const material = builder.material;
  12679. const outgoingLight = context.outgoingLight;
  12680. const envNode = builder.context.environment;
  12681. if ( envNode ) {
  12682. switch ( material.combine ) {
  12683. case MultiplyOperation:
  12684. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12685. break;
  12686. case MixOperation:
  12687. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12688. break;
  12689. case AddOperation:
  12690. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12691. break;
  12692. default:
  12693. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12694. break;
  12695. }
  12696. }
  12697. }
  12698. }
  12699. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12700. /**
  12701. * Node material version of `MeshBasicMaterial`.
  12702. *
  12703. * @augments NodeMaterial
  12704. */
  12705. class MeshBasicNodeMaterial extends NodeMaterial {
  12706. static get type() {
  12707. return 'MeshBasicNodeMaterial';
  12708. }
  12709. /**
  12710. * Constructs a new mesh basic node material.
  12711. *
  12712. * @param {Object?} parameters - The configuration parameter.
  12713. */
  12714. constructor( parameters ) {
  12715. super();
  12716. /**
  12717. * This flag can be used for type testing.
  12718. *
  12719. * @type {Boolean}
  12720. * @readonly
  12721. * @default true
  12722. */
  12723. this.isMeshBasicNodeMaterial = true;
  12724. /**
  12725. * Although the basic material is by definition unlit, we set
  12726. * this property to `true` since we use a lighting model to compute
  12727. * the outgoing light of the fragment shader.
  12728. *
  12729. * @type {Boolean}
  12730. * @default true
  12731. */
  12732. this.lights = true;
  12733. this.setDefaultValues( _defaultValues$9 );
  12734. this.setValues( parameters );
  12735. }
  12736. /**
  12737. * Basic materials are not affected by normal and bump maps so we
  12738. * return by default {@link module:Normal.normalView}.
  12739. *
  12740. * @return {Node<vec3>} The normal node.
  12741. */
  12742. setupNormal() {
  12743. return normalView; // see #28839
  12744. }
  12745. /**
  12746. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12747. * to implement the default environment mapping.
  12748. *
  12749. * @param {NodeBuilder} builder - The current node builder.
  12750. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12751. */
  12752. setupEnvironment( builder ) {
  12753. const envNode = super.setupEnvironment( builder );
  12754. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12755. }
  12756. /**
  12757. * This method must be overwriten since light maps are evaluated
  12758. * with a special scaling factor for basic materials.
  12759. *
  12760. * @param {NodeBuilder} builder - The current node builder.
  12761. * @return {BasicLightMapNode<vec3>?} The light map node.
  12762. */
  12763. setupLightMap( builder ) {
  12764. let node = null;
  12765. if ( builder.material.lightMap ) {
  12766. node = new BasicLightMapNode( materialLightMap );
  12767. }
  12768. return node;
  12769. }
  12770. /**
  12771. * The material overwrites this method because `lights` is set to `true` but
  12772. * we still want to return the diffuse color as the outgoing light.
  12773. *
  12774. * @return {Node<vec3>} The outgoing light node.
  12775. */
  12776. setupOutgoingLight() {
  12777. return diffuseColor.rgb;
  12778. }
  12779. /**
  12780. * Setups the lighting model.
  12781. *
  12782. * @return {BasicLightingModel} The lighting model.
  12783. */
  12784. setupLightingModel() {
  12785. return new BasicLightingModel();
  12786. }
  12787. }
  12788. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12789. // Original approximation by Christophe Schlick '94
  12790. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12791. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12792. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12793. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12794. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12795. } ); // validated
  12796. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12797. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12798. } ); // validated
  12799. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12800. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12801. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12802. } );
  12803. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12804. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12805. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12806. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12807. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12808. const G = G_BlinnPhong_Implicit();
  12809. const D = D_BlinnPhong( { dotNH } );
  12810. return F.mul( G ).mul( D );
  12811. } );
  12812. /**
  12813. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12814. *
  12815. * @augments BasicLightingModel
  12816. */
  12817. class PhongLightingModel extends BasicLightingModel {
  12818. /**
  12819. * Constructs a new phong lighting model.
  12820. *
  12821. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12822. */
  12823. constructor( specular = true ) {
  12824. super();
  12825. /**
  12826. * Whether specular is supported or not. Set this to `false` if you are
  12827. * looking for a Lambert-like material meaning a material for non-shiny
  12828. * surfaces, without specular highlights.
  12829. *
  12830. * @type {Boolean}
  12831. * @default true
  12832. */
  12833. this.specular = specular;
  12834. }
  12835. /**
  12836. * Implements the direct lighting. The specular portion is optional an can be controlled
  12837. * with the {@link PhongLightingModel#specular} flag.
  12838. *
  12839. * @param {Object} input - The input data.
  12840. * @param {StackNode} stack - The current stack.
  12841. * @param {NodeBuilder} builder - The current node builder.
  12842. */
  12843. direct( { lightDirection, lightColor, reflectedLight } ) {
  12844. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12845. const irradiance = dotNL.mul( lightColor );
  12846. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12847. if ( this.specular === true ) {
  12848. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12849. }
  12850. }
  12851. /**
  12852. * Implements the indirect lighting.
  12853. *
  12854. * @param {ContextNode} input - The current node context.
  12855. * @param {StackNode} stack - The current stack.
  12856. * @param {NodeBuilder} builder - The current node builder.
  12857. */
  12858. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12859. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12860. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12861. }
  12862. }
  12863. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12864. /**
  12865. * Node material version of `MeshLambertMaterial`.
  12866. *
  12867. * @augments NodeMaterial
  12868. */
  12869. class MeshLambertNodeMaterial extends NodeMaterial {
  12870. static get type() {
  12871. return 'MeshLambertNodeMaterial';
  12872. }
  12873. /**
  12874. * Constructs a new mesh lambert node material.
  12875. *
  12876. * @param {Object?} parameters - The configuration parameter.
  12877. */
  12878. constructor( parameters ) {
  12879. super();
  12880. /**
  12881. * This flag can be used for type testing.
  12882. *
  12883. * @type {Boolean}
  12884. * @readonly
  12885. * @default true
  12886. */
  12887. this.isMeshLambertNodeMaterial = true;
  12888. /**
  12889. * Set to `true` because lambert materials react on lights.
  12890. *
  12891. * @type {Boolean}
  12892. * @default true
  12893. */
  12894. this.lights = true;
  12895. this.setDefaultValues( _defaultValues$8 );
  12896. this.setValues( parameters );
  12897. }
  12898. /**
  12899. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12900. * to implement the default environment mapping.
  12901. *
  12902. * @param {NodeBuilder} builder - The current node builder.
  12903. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12904. */
  12905. setupEnvironment( builder ) {
  12906. const envNode = super.setupEnvironment( builder );
  12907. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12908. }
  12909. /**
  12910. * Setups the lighting model.
  12911. *
  12912. * @return {PhongLightingModel} The lighting model.
  12913. */
  12914. setupLightingModel( /*builder*/ ) {
  12915. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  12916. }
  12917. }
  12918. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  12919. /**
  12920. * Node material version of `MeshPhongMaterial`.
  12921. *
  12922. * @augments NodeMaterial
  12923. */
  12924. class MeshPhongNodeMaterial extends NodeMaterial {
  12925. static get type() {
  12926. return 'MeshPhongNodeMaterial';
  12927. }
  12928. /**
  12929. * Constructs a new mesh lambert node material.
  12930. *
  12931. * @param {Object?} parameters - The configuration parameter.
  12932. */
  12933. constructor( parameters ) {
  12934. super();
  12935. /**
  12936. * This flag can be used for type testing.
  12937. *
  12938. * @type {Boolean}
  12939. * @readonly
  12940. * @default true
  12941. */
  12942. this.isMeshPhongNodeMaterial = true;
  12943. /**
  12944. * Set to `true` because phong materials react on lights.
  12945. *
  12946. * @type {Boolean}
  12947. * @default true
  12948. */
  12949. this.lights = true;
  12950. /**
  12951. * The shininess of phong materials is by default inferred from the `shininess`
  12952. * property. This node property allows to overwrite the default
  12953. * and define the shininess with a node instead.
  12954. *
  12955. * If you don't want to overwrite the shininess but modify the existing
  12956. * value instead, use {@link module:MaterialNode.materialShininess}.
  12957. *
  12958. * @type {Node<float>?}
  12959. * @default null
  12960. */
  12961. this.shininessNode = null;
  12962. /**
  12963. * The specular color of phong materials is by default inferred from the
  12964. * `specular` property. This node property allows to overwrite the default
  12965. * and define the specular color with a node instead.
  12966. *
  12967. * If you don't want to overwrite the specular color but modify the existing
  12968. * value instead, use {@link module:MaterialNode.materialSpecular}.
  12969. *
  12970. * @type {Node<vec3>?}
  12971. * @default null
  12972. */
  12973. this.specularNode = null;
  12974. this.setDefaultValues( _defaultValues$7 );
  12975. this.setValues( parameters );
  12976. }
  12977. /**
  12978. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12979. * to implement the default environment mapping.
  12980. *
  12981. * @param {NodeBuilder} builder - The current node builder.
  12982. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12983. */
  12984. setupEnvironment( builder ) {
  12985. const envNode = super.setupEnvironment( builder );
  12986. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12987. }
  12988. /**
  12989. * Setups the lighting model.
  12990. *
  12991. * @return {PhongLightingModel} The lighting model.
  12992. */
  12993. setupLightingModel( /*builder*/ ) {
  12994. return new PhongLightingModel();
  12995. }
  12996. /**
  12997. * Setups the phong specific node variables.
  12998. *
  12999. * @param {NodeBuilder} builder - The current node builder.
  13000. */
  13001. setupVariants( /*builder*/ ) {
  13002. // SHININESS
  13003. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13004. shininess.assign( shininessNode );
  13005. // SPECULAR COLOR
  13006. const specularNode = this.specularNode || materialSpecular;
  13007. specularColor.assign( specularNode );
  13008. }
  13009. copy( source ) {
  13010. this.shininessNode = source.shininessNode;
  13011. this.specularNode = source.specularNode;
  13012. return super.copy( source );
  13013. }
  13014. }
  13015. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13016. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13017. return float( 0 );
  13018. }
  13019. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13020. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13021. return geometryRoughness;
  13022. } );
  13023. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13024. const { roughness } = inputs;
  13025. const geometryRoughness = getGeometryRoughness();
  13026. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13027. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13028. roughnessFactor = roughnessFactor.min( 1.0 );
  13029. return roughnessFactor;
  13030. } );
  13031. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13032. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13033. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13034. const a2 = alpha.pow2();
  13035. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13036. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13037. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13038. } ).setLayout( {
  13039. name: 'V_GGX_SmithCorrelated',
  13040. type: 'float',
  13041. inputs: [
  13042. { name: 'alpha', type: 'float' },
  13043. { name: 'dotNL', type: 'float' },
  13044. { name: 'dotNV', type: 'float' }
  13045. ]
  13046. } ); // validated
  13047. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13048. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13049. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13050. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13051. const v = div( 0.5, gv.add( gl ) );
  13052. return v.saturate();
  13053. } ).setLayout( {
  13054. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13055. type: 'float',
  13056. inputs: [
  13057. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13058. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13059. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13060. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13061. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13062. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13063. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13064. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13065. ]
  13066. } );
  13067. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13068. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13069. // alpha is "roughness squared" in Disney’s reparameterization
  13070. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13071. const a2 = alpha.pow2();
  13072. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13073. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13074. } ).setLayout( {
  13075. name: 'D_GGX',
  13076. type: 'float',
  13077. inputs: [
  13078. { name: 'alpha', type: 'float' },
  13079. { name: 'dotNH', type: 'float' }
  13080. ]
  13081. } ); // validated
  13082. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13083. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13084. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13085. const a2 = alphaT.mul( alphaB );
  13086. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13087. const v2 = v.dot( v );
  13088. const w2 = a2.div( v2 );
  13089. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13090. } ).setLayout( {
  13091. name: 'D_GGX_Anisotropic',
  13092. type: 'float',
  13093. inputs: [
  13094. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13095. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13096. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13097. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13098. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13099. ]
  13100. } );
  13101. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13102. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13103. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13104. const normalView = inputs.normalView || transformedNormalView;
  13105. const alpha = roughness.pow2(); // UE4's roughness
  13106. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13107. const dotNL = normalView.dot( lightDirection ).clamp();
  13108. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13109. const dotNH = normalView.dot( halfDir ).clamp();
  13110. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13111. let F = F_Schlick( { f0, f90, dotVH } );
  13112. let V, D;
  13113. if ( defined( USE_IRIDESCENCE ) ) {
  13114. F = iridescence.mix( F, f );
  13115. }
  13116. if ( defined( USE_ANISOTROPY ) ) {
  13117. const dotTL = anisotropyT.dot( lightDirection );
  13118. const dotTV = anisotropyT.dot( positionViewDirection );
  13119. const dotTH = anisotropyT.dot( halfDir );
  13120. const dotBL = anisotropyB.dot( lightDirection );
  13121. const dotBV = anisotropyB.dot( positionViewDirection );
  13122. const dotBH = anisotropyB.dot( halfDir );
  13123. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13124. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13125. } else {
  13126. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13127. D = D_GGX( { alpha, dotNH } );
  13128. }
  13129. return F.mul( V ).mul( D );
  13130. } ); // validated
  13131. // Analytical approximation of the DFG LUT, one half of the
  13132. // split-sum approximation used in indirect specular lighting.
  13133. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13134. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13135. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13136. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13137. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13138. const r = roughness.mul( c0 ).add( c1 );
  13139. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13140. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13141. return fab;
  13142. } ).setLayout( {
  13143. name: 'DFGApprox',
  13144. type: 'vec2',
  13145. inputs: [
  13146. { name: 'roughness', type: 'float' },
  13147. { name: 'dotNV', type: 'vec3' }
  13148. ]
  13149. } );
  13150. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13151. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13152. const fab = DFGApprox( { dotNV, roughness } );
  13153. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13154. } );
  13155. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13156. const x = dotVH.oneMinus().saturate();
  13157. const x2 = x.mul( x );
  13158. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13159. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13160. } ).setLayout( {
  13161. name: 'Schlick_to_F0',
  13162. type: 'vec3',
  13163. inputs: [
  13164. { name: 'f', type: 'vec3' },
  13165. { name: 'f90', type: 'float' },
  13166. { name: 'dotVH', type: 'float' }
  13167. ]
  13168. } );
  13169. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13170. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13171. const alpha = roughness.pow2();
  13172. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13173. const invAlpha = float( 1.0 ).div( alpha );
  13174. const cos2h = dotNH.pow2();
  13175. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13176. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13177. } ).setLayout( {
  13178. name: 'D_Charlie',
  13179. type: 'float',
  13180. inputs: [
  13181. { name: 'roughness', type: 'float' },
  13182. { name: 'dotNH', type: 'float' }
  13183. ]
  13184. } );
  13185. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13186. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13187. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13188. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13189. } ).setLayout( {
  13190. name: 'V_Neubelt',
  13191. type: 'float',
  13192. inputs: [
  13193. { name: 'dotNV', type: 'float' },
  13194. { name: 'dotNL', type: 'float' }
  13195. ]
  13196. } );
  13197. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13198. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13199. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13200. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13201. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13202. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13203. const V = V_Neubelt( { dotNV, dotNL } );
  13204. return sheen.mul( D ).mul( V );
  13205. } );
  13206. // Rect Area Light
  13207. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13208. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13209. // code: https://github.com/selfshadow/ltc_code/
  13210. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13211. const LUT_SIZE = 64.0;
  13212. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13213. const LUT_BIAS = 0.5 / LUT_SIZE;
  13214. const dotNV = N.dot( V ).saturate();
  13215. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13216. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13217. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13218. return uv;
  13219. } ).setLayout( {
  13220. name: 'LTC_Uv',
  13221. type: 'vec2',
  13222. inputs: [
  13223. { name: 'N', type: 'vec3' },
  13224. { name: 'V', type: 'vec3' },
  13225. { name: 'roughness', type: 'float' }
  13226. ]
  13227. } );
  13228. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13229. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13230. // An approximation of the form factor of a horizon-clipped rectangle.
  13231. const l = f.length();
  13232. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13233. } ).setLayout( {
  13234. name: 'LTC_ClippedSphereFormFactor',
  13235. type: 'float',
  13236. inputs: [
  13237. { name: 'f', type: 'vec3' }
  13238. ]
  13239. } );
  13240. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13241. const x = v1.dot( v2 );
  13242. const y = x.abs().toVar();
  13243. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13244. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13245. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13246. const v = a.div( b );
  13247. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13248. return v1.cross( v2 ).mul( theta_sintheta );
  13249. } ).setLayout( {
  13250. name: 'LTC_EdgeVectorFormFactor',
  13251. type: 'vec3',
  13252. inputs: [
  13253. { name: 'v1', type: 'vec3' },
  13254. { name: 'v2', type: 'vec3' }
  13255. ]
  13256. } );
  13257. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13258. // bail if point is on back side of plane of light
  13259. // assumes ccw winding order of light vertices
  13260. const v1 = p1.sub( p0 ).toVar();
  13261. const v2 = p3.sub( p0 ).toVar();
  13262. const lightNormal = v1.cross( v2 );
  13263. const result = vec3().toVar();
  13264. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13265. // construct orthonormal basis around N
  13266. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13267. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13268. // compute transform
  13269. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13270. // transform rect
  13271. // & project rect onto sphere
  13272. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13273. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13274. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13275. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13276. // calculate vector form factor
  13277. const vectorFormFactor = vec3( 0 ).toVar();
  13278. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13279. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13280. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13281. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13282. // adjust for horizon clipping
  13283. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13284. } );
  13285. return result;
  13286. } ).setLayout( {
  13287. name: 'LTC_Evaluate',
  13288. type: 'vec3',
  13289. inputs: [
  13290. { name: 'N', type: 'vec3' },
  13291. { name: 'V', type: 'vec3' },
  13292. { name: 'P', type: 'vec3' },
  13293. { name: 'mInv', type: 'mat3' },
  13294. { name: 'p0', type: 'vec3' },
  13295. { name: 'p1', type: 'vec3' },
  13296. { name: 'p2', type: 'vec3' },
  13297. { name: 'p3', type: 'vec3' }
  13298. ]
  13299. } );
  13300. /** @module TextureBicubic **/
  13301. // Mipped Bicubic Texture Filtering by N8
  13302. // https://www.shadertoy.com/view/Dl2SDW
  13303. const bC = 1.0 / 6.0;
  13304. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13305. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13306. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13307. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13308. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13309. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13310. // h0 and h1 are the two offset functions
  13311. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13312. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13313. const bicubic = ( textureNode, texelSize, lod ) => {
  13314. const uv = textureNode.uvNode;
  13315. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13316. const iuv = floor( uvScaled );
  13317. const fuv = fract( uvScaled );
  13318. const g0x = g0( fuv.x );
  13319. const g1x = g1( fuv.x );
  13320. const h0x = h0( fuv.x );
  13321. const h1x = h1( fuv.x );
  13322. const h0y = h0( fuv.y );
  13323. const h1y = h1( fuv.y );
  13324. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13325. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13326. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13327. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13328. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13329. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13330. return a.add( b );
  13331. };
  13332. /**
  13333. * Applies mipped bicubic texture filtering to the given texture node.
  13334. *
  13335. * @method
  13336. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13337. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13338. * @return {Node} The filtered texture sample.
  13339. */
  13340. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13341. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13342. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13343. const fLodSizeInv = div( 1.0, fLodSize );
  13344. const cLodSizeInv = div( 1.0, cLodSize );
  13345. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13346. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13347. return fract( lodNode ).mix( fSample, cSample );
  13348. } );
  13349. //
  13350. // Transmission
  13351. //
  13352. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13353. // Direction of refracted light.
  13354. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13355. // Compute rotation-independent scaling of the model matrix.
  13356. const modelScale = vec3(
  13357. length( modelMatrix[ 0 ].xyz ),
  13358. length( modelMatrix[ 1 ].xyz ),
  13359. length( modelMatrix[ 2 ].xyz )
  13360. );
  13361. // The thickness is specified in local space.
  13362. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13363. } ).setLayout( {
  13364. name: 'getVolumeTransmissionRay',
  13365. type: 'vec3',
  13366. inputs: [
  13367. { name: 'n', type: 'vec3' },
  13368. { name: 'v', type: 'vec3' },
  13369. { name: 'thickness', type: 'float' },
  13370. { name: 'ior', type: 'float' },
  13371. { name: 'modelMatrix', type: 'mat4' }
  13372. ]
  13373. } );
  13374. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13375. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13376. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13377. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13378. } ).setLayout( {
  13379. name: 'applyIorToRoughness',
  13380. type: 'float',
  13381. inputs: [
  13382. { name: 'roughness', type: 'float' },
  13383. { name: 'ior', type: 'float' }
  13384. ]
  13385. } );
  13386. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13387. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13388. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13389. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13390. const transmissionSample = vTexture.sample( fragCoord );
  13391. //const transmissionSample = viewportMipTexture( fragCoord );
  13392. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13393. return textureBicubic( transmissionSample, lod );
  13394. } );
  13395. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13396. If( attenuationDistance.notEqual( 0 ), () => {
  13397. // Compute light attenuation using Beer's law.
  13398. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13399. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13400. return transmittance;
  13401. } );
  13402. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13403. return vec3( 1.0 );
  13404. } ).setLayout( {
  13405. name: 'volumeAttenuation',
  13406. type: 'vec3',
  13407. inputs: [
  13408. { name: 'transmissionDistance', type: 'float' },
  13409. { name: 'attenuationColor', type: 'vec3' },
  13410. { name: 'attenuationDistance', type: 'float' }
  13411. ]
  13412. } );
  13413. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13414. let transmittedLight, transmittance;
  13415. if ( dispersion ) {
  13416. transmittedLight = vec4().toVar();
  13417. transmittance = vec3().toVar();
  13418. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13419. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13420. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13421. const ior = iors.element( i );
  13422. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13423. const refractedRayExit = position.add( transmissionRay );
  13424. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13425. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13426. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13427. refractionCoords.addAssign( 1.0 );
  13428. refractionCoords.divAssign( 2.0 );
  13429. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13430. // Sample framebuffer to get pixel the refracted ray hits.
  13431. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13432. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13433. transmittedLight.a.addAssign( transmissionSample.a );
  13434. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13435. } );
  13436. transmittedLight.a.divAssign( 3.0 );
  13437. } else {
  13438. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13439. const refractedRayExit = position.add( transmissionRay );
  13440. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13441. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13442. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13443. refractionCoords.addAssign( 1.0 );
  13444. refractionCoords.divAssign( 2.0 );
  13445. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13446. // Sample framebuffer to get pixel the refracted ray hits.
  13447. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13448. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13449. }
  13450. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13451. const dotNV = n.dot( v ).clamp();
  13452. // Get the specular component.
  13453. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13454. dotNV,
  13455. specularColor,
  13456. specularF90,
  13457. roughness
  13458. } ) );
  13459. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13460. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13461. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13462. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13463. } );
  13464. //
  13465. // Iridescence
  13466. //
  13467. // XYZ to linear-sRGB color space
  13468. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13469. 3.2404542, - 0.9692660, 0.0556434,
  13470. - 1.5371385, 1.8760108, - 0.2040259,
  13471. - 0.4985314, 0.0415560, 1.0572252
  13472. );
  13473. // Assume air interface for top
  13474. // Note: We don't handle the case fresnel0 == 1
  13475. const Fresnel0ToIor = ( fresnel0 ) => {
  13476. const sqrtF0 = fresnel0.sqrt();
  13477. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13478. };
  13479. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13480. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13481. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13482. };
  13483. // Fresnel equations for dielectric/dielectric interfaces.
  13484. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13485. // Evaluation XYZ sensitivity curves in Fourier space
  13486. const evalSensitivity = ( OPD, shift ) => {
  13487. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13488. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13489. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13490. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13491. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  13492. 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() );
  13493. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13494. const rgb = XYZ_TO_REC709.mul( xyz );
  13495. return rgb;
  13496. };
  13497. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13498. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13499. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13500. // Evaluate the cosTheta on the base layer (Snell law)
  13501. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13502. // Handle TIR:
  13503. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13504. If( cosTheta2Sq.lessThan( 0 ), () => {
  13505. return vec3( 1.0 );
  13506. } );
  13507. const cosTheta2 = cosTheta2Sq.sqrt();
  13508. // First interface
  13509. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13510. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13511. //const R21 = R12;
  13512. const T121 = R12.oneMinus();
  13513. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13514. const phi21 = float( Math.PI ).sub( phi12 );
  13515. // Second interface
  13516. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13517. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13518. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13519. const phi23 = vec3(
  13520. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13521. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13522. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13523. );
  13524. // Phase shift
  13525. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13526. const phi = vec3( phi21 ).add( phi23 );
  13527. // Compound terms
  13528. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13529. const r123 = R123.sqrt();
  13530. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13531. // Reflectance term for m = 0 (DC term amplitude)
  13532. const C0 = R12.add( Rs );
  13533. const I = C0.toVar();
  13534. // Reflectance term for m > 0 (pairs of diracs)
  13535. const Cm = Rs.sub( T121 ).toVar();
  13536. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13537. Cm.mulAssign( r123 );
  13538. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13539. I.addAssign( Cm.mul( Sm ) );
  13540. } );
  13541. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13542. return I.max( vec3( 0.0 ) );
  13543. } ).setLayout( {
  13544. name: 'evalIridescence',
  13545. type: 'vec3',
  13546. inputs: [
  13547. { name: 'outsideIOR', type: 'float' },
  13548. { name: 'eta2', type: 'float' },
  13549. { name: 'cosTheta1', type: 'float' },
  13550. { name: 'thinFilmThickness', type: 'float' },
  13551. { name: 'baseF0', type: 'vec3' }
  13552. ]
  13553. } );
  13554. //
  13555. // Sheen
  13556. //
  13557. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13558. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13559. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13560. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13561. const dotNV = normal.dot( viewDir ).saturate();
  13562. const r2 = roughness.pow2();
  13563. const a = select(
  13564. roughness.lessThan( 0.25 ),
  13565. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13566. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13567. );
  13568. const b = select(
  13569. roughness.lessThan( 0.25 ),
  13570. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13571. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13572. );
  13573. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13574. return DG.mul( 1.0 / Math.PI ).saturate();
  13575. } );
  13576. const clearcoatF0 = vec3( 0.04 );
  13577. const clearcoatF90 = float( 1 );
  13578. /**
  13579. * Represents the lighting model for a PBR material.
  13580. *
  13581. * @augments LightingModel
  13582. */
  13583. class PhysicalLightingModel extends LightingModel {
  13584. /**
  13585. * Constructs a new physical lighting model.
  13586. *
  13587. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13588. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13589. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13590. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13591. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13592. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13593. */
  13594. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13595. super();
  13596. /**
  13597. * Whether clearcoat is supported or not.
  13598. *
  13599. * @type {Boolean}
  13600. * @default false
  13601. */
  13602. this.clearcoat = clearcoat;
  13603. /**
  13604. * Whether sheen is supported or not.
  13605. *
  13606. * @type {Boolean}
  13607. * @default false
  13608. */
  13609. this.sheen = sheen;
  13610. /**
  13611. * Whether iridescence is supported or not.
  13612. *
  13613. * @type {Boolean}
  13614. * @default false
  13615. */
  13616. this.iridescence = iridescence;
  13617. /**
  13618. * Whether anisotropy is supported or not.
  13619. *
  13620. * @type {Boolean}
  13621. * @default false
  13622. */
  13623. this.anisotropy = anisotropy;
  13624. /**
  13625. * Whether transmission is supported or not.
  13626. *
  13627. * @type {Boolean}
  13628. * @default false
  13629. */
  13630. this.transmission = transmission;
  13631. /**
  13632. * Whether dispersion is supported or not.
  13633. *
  13634. * @type {Boolean}
  13635. * @default false
  13636. */
  13637. this.dispersion = dispersion;
  13638. /**
  13639. * The clear coat radiance.
  13640. *
  13641. * @type {Node?}
  13642. * @default null
  13643. */
  13644. this.clearcoatRadiance = null;
  13645. /**
  13646. * The clear coat specular direct.
  13647. *
  13648. * @type {Node?}
  13649. * @default null
  13650. */
  13651. this.clearcoatSpecularDirect = null;
  13652. /**
  13653. * The clear coat specular indirect.
  13654. *
  13655. * @type {Node?}
  13656. * @default null
  13657. */
  13658. this.clearcoatSpecularIndirect = null;
  13659. /**
  13660. * The sheen specular direct.
  13661. *
  13662. * @type {Node?}
  13663. * @default null
  13664. */
  13665. this.sheenSpecularDirect = null;
  13666. /**
  13667. * The sheen specular indirect.
  13668. *
  13669. * @type {Node?}
  13670. * @default null
  13671. */
  13672. this.sheenSpecularIndirect = null;
  13673. /**
  13674. * The iridescence Fresnel.
  13675. *
  13676. * @type {Node?}
  13677. * @default null
  13678. */
  13679. this.iridescenceFresnel = null;
  13680. /**
  13681. * The iridescence F0.
  13682. *
  13683. * @type {Node?}
  13684. * @default null
  13685. */
  13686. this.iridescenceF0 = null;
  13687. }
  13688. /**
  13689. * Depending on what features are requested, the method prepares certain node variables
  13690. * which are later used for lighting computations.
  13691. *
  13692. * @param {ContextNode} context - The current node context.
  13693. */
  13694. start( context ) {
  13695. if ( this.clearcoat === true ) {
  13696. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13697. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13698. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13699. }
  13700. if ( this.sheen === true ) {
  13701. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13702. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13703. }
  13704. if ( this.iridescence === true ) {
  13705. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13706. this.iridescenceFresnel = evalIridescence( {
  13707. outsideIOR: float( 1.0 ),
  13708. eta2: iridescenceIOR,
  13709. cosTheta1: dotNVi,
  13710. thinFilmThickness: iridescenceThickness,
  13711. baseF0: specularColor
  13712. } );
  13713. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13714. }
  13715. if ( this.transmission === true ) {
  13716. const position = positionWorld;
  13717. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13718. const n = transformedNormalWorld;
  13719. context.backdrop = getIBLVolumeRefraction(
  13720. n,
  13721. v,
  13722. roughness,
  13723. diffuseColor,
  13724. specularColor,
  13725. specularF90, // specularF90
  13726. position, // positionWorld
  13727. modelWorldMatrix, // modelMatrix
  13728. cameraViewMatrix, // viewMatrix
  13729. cameraProjectionMatrix, // projMatrix
  13730. ior,
  13731. thickness,
  13732. attenuationColor,
  13733. attenuationDistance,
  13734. this.dispersion ? dispersion : null
  13735. );
  13736. context.backdropAlpha = transmission;
  13737. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13738. }
  13739. }
  13740. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13741. // Approximates multi-scattering in order to preserve energy.
  13742. // http://www.jcgt.org/published/0008/01/03/
  13743. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13744. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13745. const fab = DFGApprox( { roughness, dotNV } );
  13746. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13747. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13748. const Ess = fab.x.add( fab.y );
  13749. const Ems = Ess.oneMinus();
  13750. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13751. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13752. singleScatter.addAssign( FssEss );
  13753. multiScatter.addAssign( Fms.mul( Ems ) );
  13754. }
  13755. /**
  13756. * Implements the direct light.
  13757. *
  13758. * @param {Object} input - The input data.
  13759. * @param {StackNode} stack - The current stack.
  13760. * @param {NodeBuilder} builder - The current node builder.
  13761. */
  13762. direct( { lightDirection, lightColor, reflectedLight } ) {
  13763. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13764. const irradiance = dotNL.mul( lightColor );
  13765. if ( this.sheen === true ) {
  13766. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13767. }
  13768. if ( this.clearcoat === true ) {
  13769. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13770. const ccIrradiance = dotNLcc.mul( lightColor );
  13771. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13772. }
  13773. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13774. 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 } ) ) );
  13775. }
  13776. /**
  13777. * This method is intended for implementing the direct light term for
  13778. * rect area light nodes.
  13779. *
  13780. * @param {Object} input - The input data.
  13781. * @param {StackNode} stack - The current stack.
  13782. * @param {NodeBuilder} builder - The current node builder.
  13783. */
  13784. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13785. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13786. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13787. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13788. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13789. const N = transformedNormalView;
  13790. const V = positionViewDirection;
  13791. const P = positionView.toVar();
  13792. const uv = LTC_Uv( { N, V, roughness } );
  13793. const t1 = ltc_1.sample( uv ).toVar();
  13794. const t2 = ltc_2.sample( uv ).toVar();
  13795. const mInv = mat3(
  13796. vec3( t1.x, 0, t1.y ),
  13797. vec3( 0, 1, 0 ),
  13798. vec3( t1.z, 0, t1.w )
  13799. ).toVar();
  13800. // LTC Fresnel Approximation by Stephen Hill
  13801. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13802. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13803. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13804. 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 } ) ) );
  13805. }
  13806. /**
  13807. * Implements the indirect lighting.
  13808. *
  13809. * @param {ContextNode} context - The current node context.
  13810. * @param {StackNode} stack - The current stack.
  13811. * @param {NodeBuilder} builder - The current node builder.
  13812. */
  13813. indirect( context, stack, builder ) {
  13814. this.indirectDiffuse( context, stack, builder );
  13815. this.indirectSpecular( context, stack, builder );
  13816. this.ambientOcclusion( context, stack, builder );
  13817. }
  13818. /**
  13819. * Implements the indirect diffuse term.
  13820. *
  13821. * @param {ContextNode} input - The current node context.
  13822. * @param {StackNode} stack - The current stack.
  13823. * @param {NodeBuilder} builder - The current node builder.
  13824. */
  13825. indirectDiffuse( { irradiance, reflectedLight } ) {
  13826. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13827. }
  13828. /**
  13829. * Implements the indirect specular term.
  13830. *
  13831. * @param {ContextNode} input - The current node context.
  13832. * @param {StackNode} stack - The current stack.
  13833. * @param {NodeBuilder} builder - The current node builder.
  13834. */
  13835. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13836. if ( this.sheen === true ) {
  13837. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13838. sheen,
  13839. IBLSheenBRDF( {
  13840. normal: transformedNormalView,
  13841. viewDir: positionViewDirection,
  13842. roughness: sheenRoughness
  13843. } )
  13844. ) );
  13845. }
  13846. if ( this.clearcoat === true ) {
  13847. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13848. const clearcoatEnv = EnvironmentBRDF( {
  13849. dotNV: dotNVcc,
  13850. specularColor: clearcoatF0,
  13851. specularF90: clearcoatF90,
  13852. roughness: clearcoatRoughness
  13853. } );
  13854. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13855. }
  13856. // Both indirect specular and indirect diffuse light accumulate here
  13857. const singleScattering = vec3().toVar( 'singleScattering' );
  13858. const multiScattering = vec3().toVar( 'multiScattering' );
  13859. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13860. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13861. const totalScattering = singleScattering.add( multiScattering );
  13862. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13863. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13864. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13865. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13866. }
  13867. /**
  13868. * Implements the ambient occlusion term.
  13869. *
  13870. * @param {ContextNode} input - The current node context.
  13871. * @param {StackNode} stack - The current stack.
  13872. * @param {NodeBuilder} builder - The current node builder.
  13873. */
  13874. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13875. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13876. const aoNV = dotNV.add( ambientOcclusion );
  13877. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13878. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13879. if ( this.clearcoat === true ) {
  13880. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13881. }
  13882. if ( this.sheen === true ) {
  13883. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13884. }
  13885. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13886. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13887. }
  13888. /**
  13889. * Used for final lighting accumulations depending on the requested features.
  13890. *
  13891. * @param {ContextNode} context - The current node context.
  13892. * @param {StackNode} stack - The current stack.
  13893. * @param {NodeBuilder} builder - The current node builder.
  13894. */
  13895. finish( context ) {
  13896. const { outgoingLight } = context;
  13897. if ( this.clearcoat === true ) {
  13898. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13899. const Fcc = F_Schlick( {
  13900. dotVH: dotNVcc,
  13901. f0: clearcoatF0,
  13902. f90: clearcoatF90
  13903. } );
  13904. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  13905. outgoingLight.assign( clearcoatLight );
  13906. }
  13907. if ( this.sheen === true ) {
  13908. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  13909. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  13910. outgoingLight.assign( sheenLight );
  13911. }
  13912. }
  13913. }
  13914. // These defines must match with PMREMGenerator
  13915. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  13916. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  13917. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  13918. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  13919. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  13920. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  13921. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  13922. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  13923. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  13924. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  13925. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  13926. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  13927. // These shader functions convert between the UV coordinates of a single face of
  13928. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  13929. // sampling a textureCube (not generally normalized ).
  13930. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  13931. const absDirection = vec3( abs( direction ) ).toVar();
  13932. const face = float( - 1.0 ).toVar();
  13933. If( absDirection.x.greaterThan( absDirection.z ), () => {
  13934. If( absDirection.x.greaterThan( absDirection.y ), () => {
  13935. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  13936. } ).Else( () => {
  13937. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  13938. } );
  13939. } ).Else( () => {
  13940. If( absDirection.z.greaterThan( absDirection.y ), () => {
  13941. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  13942. } ).Else( () => {
  13943. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  13944. } );
  13945. } );
  13946. return face;
  13947. } ).setLayout( {
  13948. name: 'getFace',
  13949. type: 'float',
  13950. inputs: [
  13951. { name: 'direction', type: 'vec3' }
  13952. ]
  13953. } );
  13954. // RH coordinate system; PMREM face-indexing convention
  13955. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  13956. const uv = vec2().toVar();
  13957. If( face.equal( 0.0 ), () => {
  13958. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  13959. } ).ElseIf( face.equal( 1.0 ), () => {
  13960. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  13961. } ).ElseIf( face.equal( 2.0 ), () => {
  13962. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  13963. } ).ElseIf( face.equal( 3.0 ), () => {
  13964. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  13965. } ).ElseIf( face.equal( 4.0 ), () => {
  13966. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  13967. } ).Else( () => {
  13968. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  13969. } );
  13970. return mul( 0.5, uv.add( 1.0 ) );
  13971. } ).setLayout( {
  13972. name: 'getUV',
  13973. type: 'vec2',
  13974. inputs: [
  13975. { name: 'direction', type: 'vec3' },
  13976. { name: 'face', type: 'float' }
  13977. ]
  13978. } );
  13979. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  13980. const mip = float( 0.0 ).toVar();
  13981. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  13982. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  13983. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  13984. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  13985. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  13986. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  13987. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  13988. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  13989. } ).Else( () => {
  13990. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  13991. } );
  13992. return mip;
  13993. } ).setLayout( {
  13994. name: 'roughnessToMip',
  13995. type: 'float',
  13996. inputs: [
  13997. { name: 'roughness', type: 'float' }
  13998. ]
  13999. } );
  14000. // RH coordinate system; PMREM face-indexing convention
  14001. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14002. const uv = uv_immutable.toVar();
  14003. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14004. const direction = vec3( uv, 1.0 ).toVar();
  14005. If( face.equal( 0.0 ), () => {
  14006. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14007. } ).ElseIf( face.equal( 1.0 ), () => {
  14008. direction.assign( direction.xzy );
  14009. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14010. } ).ElseIf( face.equal( 2.0 ), () => {
  14011. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14012. } ).ElseIf( face.equal( 3.0 ), () => {
  14013. direction.assign( direction.zyx );
  14014. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14015. } ).ElseIf( face.equal( 4.0 ), () => {
  14016. direction.assign( direction.xzy );
  14017. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14018. } ).ElseIf( face.equal( 5.0 ), () => {
  14019. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14020. } );
  14021. return direction;
  14022. } ).setLayout( {
  14023. name: 'getDirection',
  14024. type: 'vec3',
  14025. inputs: [
  14026. { name: 'uv', type: 'vec2' },
  14027. { name: 'face', type: 'float' }
  14028. ]
  14029. } );
  14030. //
  14031. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14032. const roughness = float( roughness_immutable );
  14033. const sampleDir = vec3( sampleDir_immutable );
  14034. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14035. const mipF = fract( mip );
  14036. const mipInt = floor( mip );
  14037. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14038. If( mipF.notEqual( 0.0 ), () => {
  14039. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14040. color0.assign( mix( color0, color1, mipF ) );
  14041. } );
  14042. return color0;
  14043. } );
  14044. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14045. const mipInt = float( mipInt_immutable ).toVar();
  14046. const direction = vec3( direction_immutable );
  14047. const face = float( getFace( direction ) ).toVar();
  14048. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14049. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14050. const faceSize = float( exp2( mipInt ) ).toVar();
  14051. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14052. If( face.greaterThan( 2.0 ), () => {
  14053. uv.y.addAssign( faceSize );
  14054. face.subAssign( 3.0 );
  14055. } );
  14056. uv.x.addAssign( face.mul( faceSize ) );
  14057. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14058. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14059. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14060. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14061. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14062. } );
  14063. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14064. const cosTheta = cos( theta );
  14065. // Rodrigues' axis-angle rotation
  14066. const sampleDirection = outputDirection.mul( cosTheta )
  14067. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14068. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14069. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14070. } );
  14071. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14072. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14073. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14074. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14075. } );
  14076. axis.assign( normalize( axis ) );
  14077. const gl_FragColor = vec3().toVar();
  14078. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14079. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14080. If( i.greaterThanEqual( samples ), () => {
  14081. Break();
  14082. } );
  14083. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14084. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14085. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14086. } );
  14087. return vec4( gl_FragColor, 1 );
  14088. } );
  14089. /** @module PMREMNode **/
  14090. let _generator = null;
  14091. const _cache = new WeakMap();
  14092. /**
  14093. * Generates the cubeUV size based on the given image height.
  14094. *
  14095. * @private
  14096. * @param {Number} imageHeight - The image height.
  14097. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14098. */
  14099. function _generateCubeUVSize( imageHeight ) {
  14100. const maxMip = Math.log2( imageHeight ) - 2;
  14101. const texelHeight = 1.0 / imageHeight;
  14102. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14103. return { texelWidth, texelHeight, maxMip };
  14104. }
  14105. /**
  14106. * Generates a PMREM from the given texture .
  14107. *
  14108. * @private
  14109. * @param {Texture} texture - The texture to create the PMREM for.
  14110. * @return {Texture} The PMREM.
  14111. */
  14112. function _getPMREMFromTexture( texture ) {
  14113. let cacheTexture = _cache.get( texture );
  14114. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14115. if ( pmremVersion !== texture.pmremVersion ) {
  14116. const image = texture.image;
  14117. if ( texture.isCubeTexture ) {
  14118. if ( isCubeMapReady( image ) ) {
  14119. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14120. } else {
  14121. return null;
  14122. }
  14123. } else {
  14124. if ( isEquirectangularMapReady( image ) ) {
  14125. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14126. } else {
  14127. return null;
  14128. }
  14129. }
  14130. cacheTexture.pmremVersion = texture.pmremVersion;
  14131. _cache.set( texture, cacheTexture );
  14132. }
  14133. return cacheTexture.texture;
  14134. }
  14135. /**
  14136. * This node represents a PMREM which is a special type of preprocessed
  14137. * environment map intended for PBR materials.
  14138. *
  14139. * ```js
  14140. * const material = new MeshStandardNodeMaterial();
  14141. * material.envNode = pmremTexture( envMap );
  14142. * ```
  14143. *
  14144. * @augments TempNode
  14145. */
  14146. class PMREMNode extends TempNode {
  14147. static get type() {
  14148. return 'PMREMNode';
  14149. }
  14150. /**
  14151. * Constructs a new function overloading node.
  14152. *
  14153. * @param {Texture} value - The input texture.
  14154. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14155. * @param {Node<float>} [levelNode=null] - The level node.
  14156. */
  14157. constructor( value, uvNode = null, levelNode = null ) {
  14158. super( 'vec3' );
  14159. /**
  14160. * Reference to the input texture.
  14161. *
  14162. * @private
  14163. * @type {Texture}
  14164. */
  14165. this._value = value;
  14166. /**
  14167. * Reference to the generated PMREM.
  14168. *
  14169. * @private
  14170. * @type {Texture | null}
  14171. * @default null
  14172. */
  14173. this._pmrem = null;
  14174. /**
  14175. * The uv node.
  14176. *
  14177. * @type {Node<vec2>}
  14178. */
  14179. this.uvNode = uvNode;
  14180. /**
  14181. * The level node.
  14182. *
  14183. * @type {Node<float>}
  14184. */
  14185. this.levelNode = levelNode;
  14186. /**
  14187. * Reference to a PMREM generator.
  14188. *
  14189. * @private
  14190. * @type {PMREMGenerator}
  14191. * @default null
  14192. */
  14193. this._generator = null;
  14194. const defaultTexture = new Texture();
  14195. defaultTexture.isRenderTargetTexture = true;
  14196. /**
  14197. * The texture node holding the generated PMREM.
  14198. *
  14199. * @private
  14200. * @type {TextureNode}
  14201. */
  14202. this._texture = texture( defaultTexture );
  14203. /**
  14204. * A uniform representing the PMREM's width.
  14205. *
  14206. * @private
  14207. * @type {UniformNode<float>}
  14208. */
  14209. this._width = uniform( 0 );
  14210. /**
  14211. * A uniform representing the PMREM's height.
  14212. *
  14213. * @private
  14214. * @type {UniformNode<float>}
  14215. */
  14216. this._height = uniform( 0 );
  14217. /**
  14218. * A uniform representing the PMREM's max Mip.
  14219. *
  14220. * @private
  14221. * @type {UniformNode<float>}
  14222. */
  14223. this._maxMip = uniform( 0 );
  14224. /**
  14225. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14226. *
  14227. * @type {String}
  14228. * @default 'render'
  14229. */
  14230. this.updateBeforeType = NodeUpdateType.RENDER;
  14231. }
  14232. set value( value ) {
  14233. this._value = value;
  14234. this._pmrem = null;
  14235. }
  14236. /**
  14237. * The node's texture value.
  14238. *
  14239. * @type {Texture}
  14240. */
  14241. get value() {
  14242. return this._value;
  14243. }
  14244. /**
  14245. * Uses the given PMREM texture to update internal values.
  14246. *
  14247. * @param {Texture} texture - The PMREM texture.
  14248. */
  14249. updateFromTexture( texture ) {
  14250. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14251. this._texture.value = texture;
  14252. this._width.value = cubeUVSize.texelWidth;
  14253. this._height.value = cubeUVSize.texelHeight;
  14254. this._maxMip.value = cubeUVSize.maxMip;
  14255. }
  14256. updateBefore() {
  14257. let pmrem = this._pmrem;
  14258. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14259. const texture = this._value;
  14260. if ( pmremVersion !== texture.pmremVersion ) {
  14261. if ( texture.isPMREMTexture === true ) {
  14262. pmrem = texture;
  14263. } else {
  14264. pmrem = _getPMREMFromTexture( texture );
  14265. }
  14266. if ( pmrem !== null ) {
  14267. this._pmrem = pmrem;
  14268. this.updateFromTexture( pmrem );
  14269. }
  14270. }
  14271. }
  14272. setup( builder ) {
  14273. if ( _generator === null ) {
  14274. _generator = builder.createPMREMGenerator();
  14275. }
  14276. //
  14277. this.updateBefore( builder );
  14278. //
  14279. let uvNode = this.uvNode;
  14280. if ( uvNode === null && builder.context.getUV ) {
  14281. uvNode = builder.context.getUV( this );
  14282. }
  14283. //
  14284. const texture = this.value;
  14285. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14286. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14287. }
  14288. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14289. //
  14290. let levelNode = this.levelNode;
  14291. if ( levelNode === null && builder.context.getTextureLevel ) {
  14292. levelNode = builder.context.getTextureLevel( this );
  14293. }
  14294. //
  14295. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14296. }
  14297. }
  14298. /**
  14299. * Returns `true` if the given cube map image has been fully loaded.
  14300. *
  14301. * @private
  14302. * @param {Array<(Image|Object)>} image - The cube map image.
  14303. * @return {Boolean} Whether the given cube map is ready or not.
  14304. */
  14305. function isCubeMapReady( image ) {
  14306. if ( image === null || image === undefined ) return false;
  14307. let count = 0;
  14308. const length = 6;
  14309. for ( let i = 0; i < length; i ++ ) {
  14310. if ( image[ i ] !== undefined ) count ++;
  14311. }
  14312. return count === length;
  14313. }
  14314. /**
  14315. * Returns `true` if the given equirectangular image has been fully loaded.
  14316. *
  14317. * @private
  14318. * @param {(Image|Object)} image - The equirectangular image.
  14319. * @return {Boolean} Whether the given cube map is ready or not.
  14320. */
  14321. function isEquirectangularMapReady( image ) {
  14322. if ( image === null || image === undefined ) return false;
  14323. return image.height > 0;
  14324. }
  14325. /**
  14326. * TSL function for creating a PMREM node.
  14327. *
  14328. * @function
  14329. * @param {Texture} value - The input texture.
  14330. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14331. * @param {Node<float>} [levelNode=null] - The level node.
  14332. * @returns {PMREMNode}
  14333. */
  14334. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14335. const _envNodeCache = new WeakMap();
  14336. /**
  14337. * Represents a physical model for Image-based lighting (IBL). The environment
  14338. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14339. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14340. *
  14341. * @augments LightingNode
  14342. */
  14343. class EnvironmentNode extends LightingNode {
  14344. static get type() {
  14345. return 'EnvironmentNode';
  14346. }
  14347. /**
  14348. * Constructs a new environment node.
  14349. *
  14350. * @param {Node} [envNode=null] - A node representing the environment.
  14351. */
  14352. constructor( envNode = null ) {
  14353. super();
  14354. /**
  14355. * A node representing the environment.
  14356. *
  14357. * @type {Node?}
  14358. * @default null
  14359. */
  14360. this.envNode = envNode;
  14361. }
  14362. setup( builder ) {
  14363. const { material } = builder;
  14364. let envNode = this.envNode;
  14365. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14366. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14367. let cacheEnvNode = _envNodeCache.get( value );
  14368. if ( cacheEnvNode === undefined ) {
  14369. cacheEnvNode = pmremTexture( value );
  14370. _envNodeCache.set( value, cacheEnvNode );
  14371. }
  14372. envNode = cacheEnvNode;
  14373. }
  14374. //
  14375. const envMap = material.envMap;
  14376. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14377. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14378. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14379. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14380. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14381. const isolateRadiance = cache( radiance );
  14382. const isolateIrradiance = cache( irradiance );
  14383. //
  14384. builder.context.radiance.addAssign( isolateRadiance );
  14385. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14386. //
  14387. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14388. if ( clearcoatRadiance ) {
  14389. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14390. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14391. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14392. }
  14393. }
  14394. }
  14395. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14396. let reflectVec = null;
  14397. return {
  14398. getUV: () => {
  14399. if ( reflectVec === null ) {
  14400. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14401. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14402. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14403. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14404. }
  14405. return reflectVec;
  14406. },
  14407. getTextureLevel: () => {
  14408. return roughnessNode;
  14409. }
  14410. };
  14411. };
  14412. const createIrradianceContext = ( normalWorldNode ) => {
  14413. return {
  14414. getUV: () => {
  14415. return normalWorldNode;
  14416. },
  14417. getTextureLevel: () => {
  14418. return float( 1.0 );
  14419. }
  14420. };
  14421. };
  14422. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14423. /**
  14424. * Node material version of `MeshStandardMaterial`.
  14425. *
  14426. * @augments NodeMaterial
  14427. */
  14428. class MeshStandardNodeMaterial extends NodeMaterial {
  14429. static get type() {
  14430. return 'MeshStandardNodeMaterial';
  14431. }
  14432. /**
  14433. * Constructs a new mesh standard node material.
  14434. *
  14435. * @param {Object?} parameters - The configuration parameter.
  14436. */
  14437. constructor( parameters ) {
  14438. super();
  14439. /**
  14440. * This flag can be used for type testing.
  14441. *
  14442. * @type {Boolean}
  14443. * @readonly
  14444. * @default true
  14445. */
  14446. this.isMeshStandardNodeMaterial = true;
  14447. /**
  14448. * Set to `true` because standard materials react on lights.
  14449. *
  14450. * @type {Boolean}
  14451. * @default true
  14452. */
  14453. this.lights = true;
  14454. /**
  14455. * The emissive color of standard materials is by default inferred from the `emissive`,
  14456. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14457. * overwrite the default and define the emissive color with a node instead.
  14458. *
  14459. * If you don't want to overwrite the emissive color but modify the existing
  14460. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14461. *
  14462. * @type {Node<vec3>?}
  14463. * @default null
  14464. */
  14465. this.emissiveNode = null;
  14466. /**
  14467. * The metalness of standard materials is by default inferred from the `metalness`,
  14468. * and `metalnessMap` properties. This node property allows to
  14469. * overwrite the default and define the metalness with a node instead.
  14470. *
  14471. * If you don't want to overwrite the metalness but modify the existing
  14472. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14473. *
  14474. * @type {Node<float>?}
  14475. * @default null
  14476. */
  14477. this.metalnessNode = null;
  14478. /**
  14479. * The roughness of standard materials is by default inferred from the `roughness`,
  14480. * and `roughnessMap` properties. This node property allows to
  14481. * overwrite the default and define the roughness with a node instead.
  14482. *
  14483. * If you don't want to overwrite the roughness but modify the existing
  14484. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14485. *
  14486. * @type {Node<float>?}
  14487. * @default null
  14488. */
  14489. this.roughnessNode = null;
  14490. this.setDefaultValues( _defaultValues$6 );
  14491. this.setValues( parameters );
  14492. }
  14493. /**
  14494. * Overwritten since this type of material uses {@link EnvironmentNode}
  14495. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14496. * method honors `Scene.environment`.
  14497. *
  14498. * @param {NodeBuilder} builder - The current node builder.
  14499. * @return {EnvironmentNode<vec3>?} The environment node.
  14500. */
  14501. setupEnvironment( builder ) {
  14502. let envNode = super.setupEnvironment( builder );
  14503. if ( envNode === null && builder.environmentNode ) {
  14504. envNode = builder.environmentNode;
  14505. }
  14506. return envNode ? new EnvironmentNode( envNode ) : null;
  14507. }
  14508. /**
  14509. * Setups the lighting model.
  14510. *
  14511. * @return {PhysicalLightingModel} The lighting model.
  14512. */
  14513. setupLightingModel( /*builder*/ ) {
  14514. return new PhysicalLightingModel();
  14515. }
  14516. /**
  14517. * Setups the specular related node variables.
  14518. */
  14519. setupSpecular() {
  14520. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14521. specularColor.assign( specularColorNode );
  14522. specularF90.assign( 1.0 );
  14523. }
  14524. /**
  14525. * Setups the standard specific node variables.
  14526. *
  14527. * @param {NodeBuilder} builder - The current node builder.
  14528. */
  14529. setupVariants() {
  14530. // METALNESS
  14531. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14532. metalness.assign( metalnessNode );
  14533. // ROUGHNESS
  14534. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14535. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14536. roughness.assign( roughnessNode );
  14537. // SPECULAR COLOR
  14538. this.setupSpecular();
  14539. // DIFFUSE COLOR
  14540. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14541. }
  14542. copy( source ) {
  14543. this.emissiveNode = source.emissiveNode;
  14544. this.metalnessNode = source.metalnessNode;
  14545. this.roughnessNode = source.roughnessNode;
  14546. return super.copy( source );
  14547. }
  14548. }
  14549. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14550. /**
  14551. * Node material version of `MeshPhysicalMaterial`.
  14552. *
  14553. * @augments MeshStandardNodeMaterial
  14554. */
  14555. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14556. static get type() {
  14557. return 'MeshPhysicalNodeMaterial';
  14558. }
  14559. /**
  14560. * Constructs a new mesh physical node material.
  14561. *
  14562. * @param {Object?} parameters - The configuration parameter.
  14563. */
  14564. constructor( parameters ) {
  14565. super();
  14566. /**
  14567. * This flag can be used for type testing.
  14568. *
  14569. * @type {Boolean}
  14570. * @readonly
  14571. * @default true
  14572. */
  14573. this.isMeshPhysicalNodeMaterial = true;
  14574. /**
  14575. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14576. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14577. * and define the clearcoat with a node instead.
  14578. *
  14579. * If you don't want to overwrite the clearcoat but modify the existing
  14580. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14581. *
  14582. * @type {Node<float>?}
  14583. * @default null
  14584. */
  14585. this.clearcoatNode = null;
  14586. /**
  14587. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14588. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14589. * and define the clearcoat roughness with a node instead.
  14590. *
  14591. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14592. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14593. *
  14594. * @type {Node<float>?}
  14595. * @default null
  14596. */
  14597. this.clearcoatRoughnessNode = null;
  14598. /**
  14599. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14600. * property. This node property allows to overwrite the default
  14601. * and define the clearcoat normal with a node instead.
  14602. *
  14603. * If you don't want to overwrite the clearcoat normal but modify the existing
  14604. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14605. *
  14606. * @type {Node<vec3>?}
  14607. * @default null
  14608. */
  14609. this.clearcoatNormalNode = null;
  14610. /**
  14611. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14612. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14613. * and define the sheen with a node instead.
  14614. *
  14615. * If you don't want to overwrite the sheen but modify the existing
  14616. * value instead, use {@link module:MaterialNode.materialSheen}.
  14617. *
  14618. * @type {Node<vec3>?}
  14619. * @default null
  14620. */
  14621. this.sheenNode = null;
  14622. /**
  14623. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14624. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14625. * and define the sheen roughness with a node instead.
  14626. *
  14627. * If you don't want to overwrite the sheen roughness but modify the existing
  14628. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14629. *
  14630. * @type {Node<float>?}
  14631. * @default null
  14632. */
  14633. this.sheenRoughnessNode = null;
  14634. /**
  14635. * The iridescence of physical materials is by default inferred from the `iridescence`
  14636. * property. This node property allows to overwrite the default
  14637. * and define the iridescence with a node instead.
  14638. *
  14639. * If you don't want to overwrite the iridescence but modify the existing
  14640. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14641. *
  14642. * @type {Node<float>?}
  14643. * @default null
  14644. */
  14645. this.iridescenceNode = null;
  14646. /**
  14647. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14648. * property. This node property allows to overwrite the default
  14649. * and define the iridescence IOR with a node instead.
  14650. *
  14651. * If you don't want to overwrite the iridescence IOR but modify the existing
  14652. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14653. *
  14654. * @type {Node<float>?}
  14655. * @default null
  14656. */
  14657. this.iridescenceIORNode = null;
  14658. /**
  14659. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14660. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14661. * and define the iridescence thickness with a node instead.
  14662. *
  14663. * If you don't want to overwrite the iridescence thickness but modify the existing
  14664. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14665. *
  14666. * @type {Node<float>?}
  14667. * @default null
  14668. */
  14669. this.iridescenceThicknessNode = null;
  14670. /**
  14671. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14672. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14673. * and define the specular intensity with a node instead.
  14674. *
  14675. * If you don't want to overwrite the specular intensity but modify the existing
  14676. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14677. *
  14678. * @type {Node<float>?}
  14679. * @default null
  14680. */
  14681. this.specularIntensityNode = null;
  14682. /**
  14683. * The specular color of physical materials is by default inferred from the `specularColor`
  14684. * and `specularColorMap` properties. This node property allows to overwrite the default
  14685. * and define the specular color with a node instead.
  14686. *
  14687. * If you don't want to overwrite the specular color but modify the existing
  14688. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14689. *
  14690. * @type {Node<vec3>?}
  14691. * @default null
  14692. */
  14693. this.specularColorNode = null;
  14694. /**
  14695. * The ior of physical materials is by default inferred from the `ior`
  14696. * property. This node property allows to overwrite the default
  14697. * and define the ior with a node instead.
  14698. *
  14699. * If you don't want to overwrite the ior but modify the existing
  14700. * value instead, use {@link module:MaterialNode.materialIOR}.
  14701. *
  14702. * @type {Node<float>?}
  14703. * @default null
  14704. */
  14705. this.iorNode = null;
  14706. /**
  14707. * The transmission of physical materials is by default inferred from the `transmission` and
  14708. * `transmissionMap` properties. This node property allows to overwrite the default
  14709. * and define the transmission with a node instead.
  14710. *
  14711. * If you don't want to overwrite the transmission but modify the existing
  14712. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14713. *
  14714. * @type {Node<float>?}
  14715. * @default null
  14716. */
  14717. this.transmissionNode = null;
  14718. /**
  14719. * The thickness of physical materials is by default inferred from the `thickness` and
  14720. * `thicknessMap` properties. This node property allows to overwrite the default
  14721. * and define the thickness with a node instead.
  14722. *
  14723. * If you don't want to overwrite the thickness but modify the existing
  14724. * value instead, use {@link module:MaterialNode.materialThickness}.
  14725. *
  14726. * @type {Node<float>?}
  14727. * @default null
  14728. */
  14729. this.thicknessNode = null;
  14730. /**
  14731. * The attenuation distance of physical materials is by default inferred from the
  14732. * `attenuationDistance` property. This node property allows to overwrite the default
  14733. * and define the attenuation distance with a node instead.
  14734. *
  14735. * If you don't want to overwrite the attenuation distance but modify the existing
  14736. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14737. *
  14738. * @type {Node<float>?}
  14739. * @default null
  14740. */
  14741. this.attenuationDistanceNode = null;
  14742. /**
  14743. * The attenuation color of physical materials is by default inferred from the
  14744. * `attenuationColor` property. This node property allows to overwrite the default
  14745. * and define the attenuation color with a node instead.
  14746. *
  14747. * If you don't want to overwrite the attenuation color but modify the existing
  14748. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14749. *
  14750. * @type {Node<vec3>?}
  14751. * @default null
  14752. */
  14753. this.attenuationColorNode = null;
  14754. /**
  14755. * The dispersion of physical materials is by default inferred from the
  14756. * `dispersion` property. This node property allows to overwrite the default
  14757. * and define the dispersion with a node instead.
  14758. *
  14759. * If you don't want to overwrite the dispersion but modify the existing
  14760. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14761. *
  14762. * @type {Node<float>?}
  14763. * @default null
  14764. */
  14765. this.dispersionNode = null;
  14766. /**
  14767. * The anisotropy of physical materials is by default inferred from the
  14768. * `anisotropy` property. This node property allows to overwrite the default
  14769. * and define the anisotropy with a node instead.
  14770. *
  14771. * If you don't want to overwrite the anisotropy but modify the existing
  14772. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14773. *
  14774. * @type {Node<float>?}
  14775. * @default null
  14776. */
  14777. this.anisotropyNode = null;
  14778. this.setDefaultValues( _defaultValues$5 );
  14779. this.setValues( parameters );
  14780. }
  14781. /**
  14782. * Whether the lighting model should use clearcoat or not.
  14783. *
  14784. * @type {Boolean}
  14785. * @default true
  14786. */
  14787. get useClearcoat() {
  14788. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14789. }
  14790. /**
  14791. * Whether the lighting model should use iridescence or not.
  14792. *
  14793. * @type {Boolean}
  14794. * @default true
  14795. */
  14796. get useIridescence() {
  14797. return this.iridescence > 0 || this.iridescenceNode !== null;
  14798. }
  14799. /**
  14800. * Whether the lighting model should use sheen or not.
  14801. *
  14802. * @type {Boolean}
  14803. * @default true
  14804. */
  14805. get useSheen() {
  14806. return this.sheen > 0 || this.sheenNode !== null;
  14807. }
  14808. /**
  14809. * Whether the lighting model should use anisotropy or not.
  14810. *
  14811. * @type {Boolean}
  14812. * @default true
  14813. */
  14814. get useAnisotropy() {
  14815. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14816. }
  14817. /**
  14818. * Whether the lighting model should use transmission or not.
  14819. *
  14820. * @type {Boolean}
  14821. * @default true
  14822. */
  14823. get useTransmission() {
  14824. return this.transmission > 0 || this.transmissionNode !== null;
  14825. }
  14826. /**
  14827. * Whether the lighting model should use dispersion or not.
  14828. *
  14829. * @type {Boolean}
  14830. * @default true
  14831. */
  14832. get useDispersion() {
  14833. return this.dispersion > 0 || this.dispersionNode !== null;
  14834. }
  14835. /**
  14836. * Setups the specular related node variables.
  14837. */
  14838. setupSpecular() {
  14839. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14840. ior.assign( iorNode );
  14841. 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 ) );
  14842. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14843. }
  14844. /**
  14845. * Setups the lighting model.
  14846. *
  14847. * @return {PhysicalLightingModel} The lighting model.
  14848. */
  14849. setupLightingModel( /*builder*/ ) {
  14850. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14851. }
  14852. /**
  14853. * Setups the physical specific node variables.
  14854. *
  14855. * @param {NodeBuilder} builder - The current node builder.
  14856. */
  14857. setupVariants( builder ) {
  14858. super.setupVariants( builder );
  14859. // CLEARCOAT
  14860. if ( this.useClearcoat ) {
  14861. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14862. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14863. clearcoat.assign( clearcoatNode );
  14864. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14865. }
  14866. // SHEEN
  14867. if ( this.useSheen ) {
  14868. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14869. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14870. sheen.assign( sheenNode );
  14871. sheenRoughness.assign( sheenRoughnessNode );
  14872. }
  14873. // IRIDESCENCE
  14874. if ( this.useIridescence ) {
  14875. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14876. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14877. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14878. iridescence.assign( iridescenceNode );
  14879. iridescenceIOR.assign( iridescenceIORNode );
  14880. iridescenceThickness.assign( iridescenceThicknessNode );
  14881. }
  14882. // ANISOTROPY
  14883. if ( this.useAnisotropy ) {
  14884. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14885. anisotropy.assign( anisotropyV.length() );
  14886. If( anisotropy.equal( 0.0 ), () => {
  14887. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14888. } ).Else( () => {
  14889. anisotropyV.divAssign( vec2( anisotropy ) );
  14890. anisotropy.assign( anisotropy.saturate() );
  14891. } );
  14892. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14893. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14894. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14895. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  14896. }
  14897. // TRANSMISSION
  14898. if ( this.useTransmission ) {
  14899. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  14900. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  14901. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  14902. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  14903. transmission.assign( transmissionNode );
  14904. thickness.assign( thicknessNode );
  14905. attenuationDistance.assign( attenuationDistanceNode );
  14906. attenuationColor.assign( attenuationColorNode );
  14907. if ( this.useDispersion ) {
  14908. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  14909. dispersion.assign( dispersionNode );
  14910. }
  14911. }
  14912. }
  14913. /**
  14914. * Setups the clearcoat normal node.
  14915. *
  14916. * @return {Node<vec3>} The clearcoat noraml.
  14917. */
  14918. setupClearcoatNormal() {
  14919. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  14920. }
  14921. setup( builder ) {
  14922. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  14923. super.setup( builder );
  14924. }
  14925. copy( source ) {
  14926. this.clearcoatNode = source.clearcoatNode;
  14927. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  14928. this.clearcoatNormalNode = source.clearcoatNormalNode;
  14929. this.sheenNode = source.sheenNode;
  14930. this.sheenRoughnessNode = source.sheenRoughnessNode;
  14931. this.iridescenceNode = source.iridescenceNode;
  14932. this.iridescenceIORNode = source.iridescenceIORNode;
  14933. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  14934. this.specularIntensityNode = source.specularIntensityNode;
  14935. this.specularColorNode = source.specularColorNode;
  14936. this.transmissionNode = source.transmissionNode;
  14937. this.thicknessNode = source.thicknessNode;
  14938. this.attenuationDistanceNode = source.attenuationDistanceNode;
  14939. this.attenuationColorNode = source.attenuationColorNode;
  14940. this.dispersionNode = source.dispersionNode;
  14941. this.anisotropyNode = source.anisotropyNode;
  14942. return super.copy( source );
  14943. }
  14944. }
  14945. /** @module MeshSSSNodeMaterial **/
  14946. /**
  14947. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  14948. *
  14949. * @augments PhysicalLightingModel
  14950. */
  14951. class SSSLightingModel extends PhysicalLightingModel {
  14952. /**
  14953. * Constructs a new physical lighting model.
  14954. *
  14955. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  14956. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  14957. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  14958. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  14959. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  14960. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  14961. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  14962. */
  14963. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  14964. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  14965. /**
  14966. * Whether the lighting model should use SSS or not.
  14967. *
  14968. * @type {Boolean}
  14969. * @default false
  14970. */
  14971. this.useSSS = sss;
  14972. }
  14973. /**
  14974. * Extends the default implementation with a SSS term.
  14975. *
  14976. * 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/}
  14977. *
  14978. * @param {Object} input - The input data.
  14979. * @param {StackNode} stack - The current stack.
  14980. * @param {NodeBuilder} builder - The current node builder.
  14981. */
  14982. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  14983. if ( this.useSSS === true ) {
  14984. const material = builder.material;
  14985. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  14986. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  14987. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  14988. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  14989. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  14990. }
  14991. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  14992. }
  14993. }
  14994. /**
  14995. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  14996. * that implements a Subsurface scattering (SSS) term.
  14997. *
  14998. * @augments MeshPhysicalNodeMaterial
  14999. */
  15000. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15001. static get type() {
  15002. return 'MeshSSSNodeMaterial';
  15003. }
  15004. /**
  15005. * Constructs a new mesh SSS node material.
  15006. *
  15007. * @param {Object?} parameters - The configuration parameter.
  15008. */
  15009. constructor( parameters ) {
  15010. super( parameters );
  15011. /**
  15012. * Represents the thickness color.
  15013. *
  15014. * @type {Node<vec3>?}
  15015. * @default null
  15016. */
  15017. this.thicknessColorNode = null;
  15018. /**
  15019. * Represents the distortion factor.
  15020. *
  15021. * @type {Node<float>?}
  15022. */
  15023. this.thicknessDistortionNode = float( 0.1 );
  15024. /**
  15025. * Represents the thickness ambient factor.
  15026. *
  15027. * @type {Node<float>?}
  15028. */
  15029. this.thicknessAmbientNode = float( 0.0 );
  15030. /**
  15031. * Represents the thickness attenuation.
  15032. *
  15033. * @type {Node<float>?}
  15034. */
  15035. this.thicknessAttenuationNode = float( .1 );
  15036. /**
  15037. * Represents the thickness power.
  15038. *
  15039. * @type {Node<float>?}
  15040. */
  15041. this.thicknessPowerNode = float( 2.0 );
  15042. /**
  15043. * Represents the thickness scale.
  15044. *
  15045. * @type {Node<float>?}
  15046. */
  15047. this.thicknessScaleNode = float( 10.0 );
  15048. }
  15049. /**
  15050. * Whether the lighting model should use SSS or not.
  15051. *
  15052. * @type {Boolean}
  15053. * @default true
  15054. */
  15055. get useSSS() {
  15056. return this.thicknessColorNode !== null;
  15057. }
  15058. /**
  15059. * Setups the lighting model.
  15060. *
  15061. * @return {SSSLightingModel} The lighting model.
  15062. */
  15063. setupLightingModel( /*builder*/ ) {
  15064. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15065. }
  15066. copy( source ) {
  15067. this.thicknessColorNode = source.thicknessColorNode;
  15068. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15069. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15070. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15071. this.thicknessPowerNode = source.thicknessPowerNode;
  15072. this.thicknessScaleNode = source.thicknessScaleNode;
  15073. return super.copy( source );
  15074. }
  15075. }
  15076. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15077. // dotNL will be from -1.0 to 1.0
  15078. const dotNL = normal.dot( lightDirection );
  15079. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15080. if ( builder.material.gradientMap ) {
  15081. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15082. return vec3( gradientMap.r );
  15083. } else {
  15084. const fw = coord.fwidth().mul( 0.5 );
  15085. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15086. }
  15087. } );
  15088. /**
  15089. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15090. *
  15091. * @augments LightingModel
  15092. */
  15093. class ToonLightingModel extends LightingModel {
  15094. /**
  15095. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15096. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15097. *
  15098. * @param {Object} input - The input data.
  15099. * @param {StackNode} stack - The current stack.
  15100. * @param {NodeBuilder} builder - The current node builder.
  15101. */
  15102. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15103. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15104. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15105. }
  15106. /**
  15107. * Implements the indirect lighting.
  15108. *
  15109. * @param {ContextNode} input - The current node context.
  15110. * @param {StackNode} stack - The current stack.
  15111. * @param {NodeBuilder} builder - The current node builder.
  15112. */
  15113. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15114. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15115. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15116. }
  15117. }
  15118. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15119. /**
  15120. * Node material version of `MeshToonMaterial`.
  15121. *
  15122. * @augments NodeMaterial
  15123. */
  15124. class MeshToonNodeMaterial extends NodeMaterial {
  15125. static get type() {
  15126. return 'MeshToonNodeMaterial';
  15127. }
  15128. /**
  15129. * Constructs a new mesh toon node material.
  15130. *
  15131. * @param {Object?} parameters - The configuration parameter.
  15132. */
  15133. constructor( parameters ) {
  15134. super();
  15135. /**
  15136. * This flag can be used for type testing.
  15137. *
  15138. * @type {Boolean}
  15139. * @readonly
  15140. * @default true
  15141. */
  15142. this.isMeshToonNodeMaterial = true;
  15143. /**
  15144. * Set to `true` because toon materials react on lights.
  15145. *
  15146. * @type {Boolean}
  15147. * @default true
  15148. */
  15149. this.lights = true;
  15150. this.setDefaultValues( _defaultValues$4 );
  15151. this.setValues( parameters );
  15152. }
  15153. /**
  15154. * Setups the lighting model.
  15155. *
  15156. * @return {ToonLightingModel} The lighting model.
  15157. */
  15158. setupLightingModel( /*builder*/ ) {
  15159. return new ToonLightingModel();
  15160. }
  15161. }
  15162. /** @module MatcapUVNode **/
  15163. /**
  15164. * Can be used to compute texture coordinates for projecting a
  15165. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15166. *
  15167. * @augments TempNode
  15168. */
  15169. class MatcapUVNode extends TempNode {
  15170. static get type() {
  15171. return 'MatcapUVNode';
  15172. }
  15173. /**
  15174. * Constructs a new matcap uv node.
  15175. */
  15176. constructor() {
  15177. super( 'vec2' );
  15178. }
  15179. setup() {
  15180. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15181. const y = positionViewDirection.cross( x );
  15182. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15183. }
  15184. }
  15185. /**
  15186. * TSL function for creating a matcap uv node.
  15187. *
  15188. * @function
  15189. * @returns {MatcapUVNode}
  15190. */
  15191. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15192. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15193. /**
  15194. * Node material version of `MeshMatcapMaterial`.
  15195. *
  15196. * @augments NodeMaterial
  15197. */
  15198. class MeshMatcapNodeMaterial extends NodeMaterial {
  15199. static get type() {
  15200. return 'MeshMatcapNodeMaterial';
  15201. }
  15202. /**
  15203. * Constructs a new mesh normal node material.
  15204. *
  15205. * @param {Object?} parameters - The configuration parameter.
  15206. */
  15207. constructor( parameters ) {
  15208. super();
  15209. /**
  15210. * This flag can be used for type testing.
  15211. *
  15212. * @type {Boolean}
  15213. * @readonly
  15214. * @default true
  15215. */
  15216. this.isMeshMatcapNodeMaterial = true;
  15217. this.setDefaultValues( _defaultValues$3 );
  15218. this.setValues( parameters );
  15219. }
  15220. /**
  15221. * Setups the matcap specific node variables.
  15222. *
  15223. * @param {NodeBuilder} builder - The current node builder.
  15224. */
  15225. setupVariants( builder ) {
  15226. const uv = matcapUV;
  15227. let matcapColor;
  15228. if ( builder.material.matcap ) {
  15229. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15230. } else {
  15231. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15232. }
  15233. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15234. }
  15235. }
  15236. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  15237. /**
  15238. * Node material version of `PointsMaterial`.
  15239. *
  15240. * Since WebGPU can render point primitives only with a size of one pixel,
  15241. * this material type does not evaluate the `size` and `sizeAttenuation`
  15242. * property of `PointsMaterial`. Use {@link InstancedPointsNodeMaterial}
  15243. * instead if you need points with a size larger than one pixel.
  15244. *
  15245. * @augments NodeMaterial
  15246. */
  15247. class PointsNodeMaterial extends NodeMaterial {
  15248. static get type() {
  15249. return 'PointsNodeMaterial';
  15250. }
  15251. /**
  15252. * Constructs a new points node material.
  15253. *
  15254. * @param {Object?} parameters - The configuration parameter.
  15255. */
  15256. constructor( parameters ) {
  15257. super();
  15258. /**
  15259. * This flag can be used for type testing.
  15260. *
  15261. * @type {Boolean}
  15262. * @readonly
  15263. * @default true
  15264. */
  15265. this.isPointsNodeMaterial = true;
  15266. this.setDefaultValues( _defaultValues$2 );
  15267. this.setValues( parameters );
  15268. }
  15269. }
  15270. /** @module RotateNode **/
  15271. /**
  15272. * Applies a rotation to the given position node.
  15273. *
  15274. * @augments TempNode
  15275. */
  15276. class RotateNode extends TempNode {
  15277. static get type() {
  15278. return 'RotateNode';
  15279. }
  15280. /**
  15281. * Constructs a new rotate node.
  15282. *
  15283. * @param {Node} positionNode - The position node.
  15284. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15285. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15286. */
  15287. constructor( positionNode, rotationNode ) {
  15288. super();
  15289. /**
  15290. * The position node.
  15291. *
  15292. * @type {Node}
  15293. */
  15294. this.positionNode = positionNode;
  15295. /**
  15296. * Represents the rotation that is applied to the position node.
  15297. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15298. *
  15299. * @type {Node}
  15300. */
  15301. this.rotationNode = rotationNode;
  15302. }
  15303. /**
  15304. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15305. *
  15306. * @param {NodeBuilder} builder - The current node builder.
  15307. * @return {String} The node's type.
  15308. */
  15309. getNodeType( builder ) {
  15310. return this.positionNode.getNodeType( builder );
  15311. }
  15312. setup( builder ) {
  15313. const { rotationNode, positionNode } = this;
  15314. const nodeType = this.getNodeType( builder );
  15315. if ( nodeType === 'vec2' ) {
  15316. const cosAngle = rotationNode.cos();
  15317. const sinAngle = rotationNode.sin();
  15318. const rotationMatrix = mat2(
  15319. cosAngle, sinAngle,
  15320. sinAngle.negate(), cosAngle
  15321. );
  15322. return rotationMatrix.mul( positionNode );
  15323. } else {
  15324. const rotation = rotationNode;
  15325. 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 ) );
  15326. 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 ) );
  15327. 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 ) );
  15328. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15329. }
  15330. }
  15331. }
  15332. /**
  15333. * TSL function for creating a rotate node.
  15334. *
  15335. * @function
  15336. * @param {Node} positionNode - The position node.
  15337. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15338. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15339. * @returns {RotateNode}
  15340. */
  15341. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15342. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  15343. /**
  15344. * Node material version of `SpriteMaterial`.
  15345. *
  15346. * @augments NodeMaterial
  15347. */
  15348. class SpriteNodeMaterial extends NodeMaterial {
  15349. static get type() {
  15350. return 'SpriteNodeMaterial';
  15351. }
  15352. /**
  15353. * Constructs a new sprite node material.
  15354. *
  15355. * @param {Object?} parameters - The configuration parameter.
  15356. */
  15357. constructor( parameters ) {
  15358. super();
  15359. /**
  15360. * This flag can be used for type testing.
  15361. *
  15362. * @type {Boolean}
  15363. * @readonly
  15364. * @default true
  15365. */
  15366. this.isSpriteNodeMaterial = true;
  15367. this._useSizeAttenuation = true;
  15368. /**
  15369. * This property makes it possible to define the position of the sprite with a
  15370. * node. That can be useful when the material is used with instanced rendering
  15371. * and node data are defined with an instanced attribute node:
  15372. * ```js
  15373. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15374. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15375. * ```
  15376. * Another possibility is to compute the instanced data with a compute shader:
  15377. * ```js
  15378. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15379. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15380. * ```
  15381. *
  15382. * @type {Node<vec2>?}
  15383. * @default null
  15384. */
  15385. this.positionNode = null;
  15386. /**
  15387. * The rotation of sprite materials is by default inferred from the `rotation`,
  15388. * property. This node property allows to overwrite the default and define
  15389. * the rotation with a node instead.
  15390. *
  15391. * If you don't want to overwrite the rotation but modify the existing
  15392. * value instead, use {@link module:MaterialNode.materialRotation}.
  15393. *
  15394. * @type {Node<float>?}
  15395. * @default null
  15396. */
  15397. this.rotationNode = null;
  15398. /**
  15399. * This node property provides an additional way to scale sprites next to
  15400. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15401. * is multiplied with the scale value of this node in the vertex shader.
  15402. *
  15403. * @type {Node<vec2>?}
  15404. * @default null
  15405. */
  15406. this.scaleNode = null;
  15407. this.setDefaultValues( _defaultValues$1 );
  15408. this.setValues( parameters );
  15409. }
  15410. /**
  15411. * Setups the position node in view space. This method implements
  15412. * the sprite specific vertex shader.
  15413. *
  15414. * @param {NodeBuilder} builder - The current node builder.
  15415. * @return {Node<vec3>} The position in view space.
  15416. */
  15417. setupPositionView( builder ) {
  15418. const { object, camera } = builder;
  15419. const sizeAttenuation = this.sizeAttenuation;
  15420. const { positionNode, rotationNode, scaleNode } = this;
  15421. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15422. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15423. if ( scaleNode !== null ) {
  15424. scale = scale.mul( scaleNode );
  15425. }
  15426. if ( sizeAttenuation === false ) {
  15427. if ( camera.isPerspectiveCamera ) {
  15428. scale = scale.mul( mvPosition.z.negate() );
  15429. } else {
  15430. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15431. scale = scale.mul( orthoScale.mul( 2 ) );
  15432. }
  15433. }
  15434. let alignedPosition = positionGeometry.xy;
  15435. if ( object.center && object.center.isVector2 === true ) {
  15436. const center = reference$1( 'center', 'vec2', object );
  15437. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15438. }
  15439. alignedPosition = alignedPosition.mul( scale );
  15440. const rotation = float( rotationNode || materialRotation );
  15441. const rotatedPosition = rotate( alignedPosition, rotation );
  15442. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15443. }
  15444. copy( source ) {
  15445. this.positionNode = source.positionNode;
  15446. this.rotationNode = source.rotationNode;
  15447. this.scaleNode = source.scaleNode;
  15448. return super.copy( source );
  15449. }
  15450. /**
  15451. * Whether to use size attenuation or not.
  15452. *
  15453. * @type {Boolean}
  15454. * @default true
  15455. */
  15456. get sizeAttenuation() {
  15457. return this._useSizeAttenuation;
  15458. }
  15459. set sizeAttenuation( value ) {
  15460. if ( this._useSizeAttenuation !== value ) {
  15461. this._useSizeAttenuation = value;
  15462. this.needsUpdate = true;
  15463. }
  15464. }
  15465. }
  15466. /**
  15467. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15468. *
  15469. * @augments LightingModel
  15470. */
  15471. class ShadowMaskModel extends LightingModel {
  15472. /**
  15473. * Constructs a new shadow mask model.
  15474. */
  15475. constructor() {
  15476. super();
  15477. /**
  15478. * The shadow mask node.
  15479. *
  15480. * @type {Node}
  15481. */
  15482. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15483. }
  15484. /**
  15485. * Only used to save the shadow mask.
  15486. *
  15487. * @param {Object} input - The input data.
  15488. */
  15489. direct( { shadowMask } ) {
  15490. this.shadowNode.mulAssign( shadowMask );
  15491. }
  15492. /**
  15493. * Uses the shadow mask to produce the final color.
  15494. *
  15495. * @param {ContextNode} context - The current node context.
  15496. */
  15497. finish( context ) {
  15498. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15499. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15500. }
  15501. }
  15502. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15503. /**
  15504. * Node material version of `ShadowMaterial`.
  15505. *
  15506. * @augments NodeMaterial
  15507. */
  15508. class ShadowNodeMaterial extends NodeMaterial {
  15509. static get type() {
  15510. return 'ShadowNodeMaterial';
  15511. }
  15512. /**
  15513. * Constructs a new shadow node material.
  15514. *
  15515. * @param {Object?} parameters - The configuration parameter.
  15516. */
  15517. constructor( parameters ) {
  15518. super();
  15519. /**
  15520. * This flag can be used for type testing.
  15521. *
  15522. * @type {Boolean}
  15523. * @readonly
  15524. * @default true
  15525. */
  15526. this.isShadowNodeMaterial = true;
  15527. /**
  15528. * Set to `true` because so it's possible to implement
  15529. * the shadow mask effect.
  15530. *
  15531. * @type {Boolean}
  15532. * @default true
  15533. */
  15534. this.lights = true;
  15535. this.setDefaultValues( _defaultValues );
  15536. this.setValues( parameters );
  15537. }
  15538. /**
  15539. * Setups the lighting model.
  15540. *
  15541. * @return {ShadowMaskModel} The lighting model.
  15542. */
  15543. setupLightingModel( /*builder*/ ) {
  15544. return new ShadowMaskModel();
  15545. }
  15546. }
  15547. /** @module Texture3DNode **/
  15548. const normal = Fn( ( { texture, uv } ) => {
  15549. const epsilon = 0.0001;
  15550. const ret = vec3().toVar();
  15551. If( uv.x.lessThan( epsilon ), () => {
  15552. ret.assign( vec3( 1, 0, 0 ) );
  15553. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15554. ret.assign( vec3( 0, 1, 0 ) );
  15555. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15556. ret.assign( vec3( 0, 0, 1 ) );
  15557. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15558. ret.assign( vec3( - 1, 0, 0 ) );
  15559. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15560. ret.assign( vec3( 0, - 1, 0 ) );
  15561. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15562. ret.assign( vec3( 0, 0, - 1 ) );
  15563. } ).Else( () => {
  15564. const step = 0.01;
  15565. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15566. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15567. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15568. ret.assign( vec3( x, y, z ) );
  15569. } );
  15570. return ret.normalize();
  15571. } );
  15572. /**
  15573. * This type of uniform node represents a 3D texture.
  15574. *
  15575. * @augments module:TextureNode~TextureNode
  15576. */
  15577. class Texture3DNode extends TextureNode {
  15578. static get type() {
  15579. return 'Texture3DNode';
  15580. }
  15581. /**
  15582. * Constructs a new 3D texture node.
  15583. *
  15584. * @param {Data3DTexture} value - The 3D texture.
  15585. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15586. * @param {Node<int>?} [levelNode=null] - The level node.
  15587. */
  15588. constructor( value, uvNode = null, levelNode = null ) {
  15589. super( value, uvNode, levelNode );
  15590. /**
  15591. * This flag can be used for type testing.
  15592. *
  15593. * @type {Boolean}
  15594. * @readonly
  15595. * @default true
  15596. */
  15597. this.isTexture3DNode = true;
  15598. }
  15599. /**
  15600. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15601. *
  15602. * @param {NodeBuilder} builder - The current node builder.
  15603. * @return {String} The input type.
  15604. */
  15605. getInputType( /*builder*/ ) {
  15606. return 'texture3D';
  15607. }
  15608. /**
  15609. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15610. * uv node.
  15611. *
  15612. * @return {Node<vec3>} The default uv node.
  15613. */
  15614. getDefaultUV() {
  15615. return vec3( 0.5, 0.5, 0.5 );
  15616. }
  15617. /**
  15618. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15619. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15620. *
  15621. * @param {Boolean} value - The update toggle.
  15622. */
  15623. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15624. /**
  15625. * Overwrites the default implementation to return the unmodified uv node.
  15626. *
  15627. * @param {NodeBuilder} builder - The current node builder.
  15628. * @param {Node} uvNode - The uv node to setup.
  15629. * @return {Node} The unmodified uv node.
  15630. */
  15631. setupUV( builder, uvNode ) {
  15632. return uvNode;
  15633. }
  15634. /**
  15635. * Generates the uv code snippet.
  15636. *
  15637. * @param {NodeBuilder} builder - The current node builder.
  15638. * @param {Node} uvNode - The uv node to generate code for.
  15639. * @return {String} The generated code snippet.
  15640. */
  15641. generateUV( builder, uvNode ) {
  15642. return uvNode.build( builder, 'vec3' );
  15643. }
  15644. /**
  15645. * TODO.
  15646. *
  15647. * @param {Node<vec3>} uvNode - The uv node .
  15648. * @return {Node<vec3>} TODO.
  15649. */
  15650. normal( uvNode ) {
  15651. return normal( { texture: this, uv: uvNode } );
  15652. }
  15653. }
  15654. /**
  15655. * TSL function for creating a 3D texture node.
  15656. *
  15657. * @function
  15658. * @param {Data3DTexture} value - The 3D texture.
  15659. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15660. * @param {Node<int>?} [levelNode=null] - The level node.
  15661. * @returns {Texture3DNode}
  15662. */
  15663. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15664. /**
  15665. * Node material intended for volume rendering. The volumetic data are
  15666. * defined with an instance of {@link Data3DTexture}.
  15667. *
  15668. * @augments NodeMaterial
  15669. */
  15670. class VolumeNodeMaterial extends NodeMaterial {
  15671. static get type() {
  15672. return 'VolumeNodeMaterial';
  15673. }
  15674. /**
  15675. * Constructs a new volume node material.
  15676. *
  15677. * @param {Object?} parameters - The configuration parameter.
  15678. */
  15679. constructor( parameters ) {
  15680. super();
  15681. /**
  15682. * This flag can be used for type testing.
  15683. *
  15684. * @type {Boolean}
  15685. * @readonly
  15686. * @default true
  15687. */
  15688. this.isVolumeNodeMaterial = true;
  15689. /**
  15690. * The base color of the volume.
  15691. *
  15692. * @type {Color}
  15693. * @default 100
  15694. */
  15695. this.base = new Color( 0xffffff );
  15696. /**
  15697. * A 3D data texture holding the volumetric data.
  15698. *
  15699. * @type {Data3DTexture?}
  15700. * @default null
  15701. */
  15702. this.map = null;
  15703. /**
  15704. * This number of samples for each ray that hits the mesh's surface
  15705. * and travels through the volume.
  15706. *
  15707. * @type {Number}
  15708. * @default 100
  15709. */
  15710. this.steps = 100;
  15711. /**
  15712. * Callback for {@link VolumeNodeMaterial#testNode}.
  15713. *
  15714. * @callback testNodeCallback
  15715. * @param {Data3DTexture<float>} map - The 3D texture.
  15716. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15717. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15718. * @param {Node<vec4>} finalColor - The final color.
  15719. */
  15720. /**
  15721. * The volume rendering of this material works by shooting rays
  15722. * from the camera position through each fragment of the mesh's
  15723. * surface and sample the inner volume in a raymarching fashion
  15724. * mutiple times.
  15725. *
  15726. * This node can be used to assign a callback function of type `Fn`
  15727. * that will be exexuted per sample. The callback receives the
  15728. * texture, the sampled texture value as well as position on the surface
  15729. * where the rays enters the volume. The last parameter is a color
  15730. * that allows the callback to determine the final color.
  15731. *
  15732. * @type {testNodeCallback?}
  15733. * @default null
  15734. */
  15735. this.testNode = null;
  15736. this.setValues( parameters );
  15737. }
  15738. /**
  15739. * Setups the vertex and fragment stage of this node material.
  15740. *
  15741. * @param {NodeBuilder} builder - The current node builder.
  15742. */
  15743. setup( builder ) {
  15744. const map = texture3D( this.map, null, 0 );
  15745. const hitBox = Fn( ( { orig, dir } ) => {
  15746. const box_min = vec3( - 0.5 );
  15747. const box_max = vec3( 0.5 );
  15748. const inv_dir = dir.reciprocal();
  15749. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15750. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15751. const tmin = min$1( tmin_tmp, tmax_tmp );
  15752. const tmax = max$1( tmin_tmp, tmax_tmp );
  15753. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15754. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15755. return vec2( t0, t1 );
  15756. } );
  15757. this.fragmentNode = Fn( () => {
  15758. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15759. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15760. const rayDir = vDirection.normalize();
  15761. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15762. bounds.x.greaterThan( bounds.y ).discard();
  15763. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15764. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15765. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15766. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15767. delta.divAssign( materialReference( 'steps', 'float' ) );
  15768. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15769. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15770. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15771. if ( this.testNode !== null ) {
  15772. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15773. } else {
  15774. // default to show surface of mesh
  15775. ac.a.assign( 1 );
  15776. Break();
  15777. }
  15778. p.addAssign( rayDir.mul( delta ) );
  15779. } );
  15780. ac.a.equal( 0 ).discard();
  15781. return vec4( ac );
  15782. } )();
  15783. super.setup( builder );
  15784. }
  15785. }
  15786. class Animation {
  15787. constructor( nodes, info ) {
  15788. this.nodes = nodes;
  15789. this.info = info;
  15790. this._context = self;
  15791. this._animationLoop = null;
  15792. this._requestId = null;
  15793. }
  15794. start() {
  15795. const update = ( time, frame ) => {
  15796. this._requestId = this._context.requestAnimationFrame( update );
  15797. if ( this.info.autoReset === true ) this.info.reset();
  15798. this.nodes.nodeFrame.update();
  15799. this.info.frame = this.nodes.nodeFrame.frameId;
  15800. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  15801. };
  15802. update();
  15803. }
  15804. stop() {
  15805. this._context.cancelAnimationFrame( this._requestId );
  15806. this._requestId = null;
  15807. }
  15808. setAnimationLoop( callback ) {
  15809. this._animationLoop = callback;
  15810. }
  15811. setContext( context ) {
  15812. this._context = context;
  15813. }
  15814. dispose() {
  15815. this.stop();
  15816. }
  15817. }
  15818. class ChainMap {
  15819. constructor() {
  15820. this.weakMap = new WeakMap();
  15821. }
  15822. get( keys ) {
  15823. let map = this.weakMap;
  15824. for ( let i = 0; i < keys.length; i ++ ) {
  15825. map = map.get( keys[ i ] );
  15826. if ( map === undefined ) return undefined;
  15827. }
  15828. return map.get( keys[ keys.length - 1 ] );
  15829. }
  15830. set( keys, value ) {
  15831. let map = this.weakMap;
  15832. for ( let i = 0; i < keys.length; i ++ ) {
  15833. const key = keys[ i ];
  15834. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  15835. map = map.get( key );
  15836. }
  15837. return map.set( keys[ keys.length - 1 ], value );
  15838. }
  15839. delete( keys ) {
  15840. let map = this.weakMap;
  15841. for ( let i = 0; i < keys.length; i ++ ) {
  15842. map = map.get( keys[ i ] );
  15843. if ( map === undefined ) return false;
  15844. }
  15845. return map.delete( keys[ keys.length - 1 ] );
  15846. }
  15847. }
  15848. let _id$8 = 0;
  15849. function getKeys( obj ) {
  15850. const keys = Object.keys( obj );
  15851. let proto = Object.getPrototypeOf( obj );
  15852. while ( proto ) {
  15853. const descriptors = Object.getOwnPropertyDescriptors( proto );
  15854. for ( const key in descriptors ) {
  15855. if ( descriptors[ key ] !== undefined ) {
  15856. const descriptor = descriptors[ key ];
  15857. if ( descriptor && typeof descriptor.get === 'function' ) {
  15858. keys.push( key );
  15859. }
  15860. }
  15861. }
  15862. proto = Object.getPrototypeOf( proto );
  15863. }
  15864. return keys;
  15865. }
  15866. class RenderObject {
  15867. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  15868. this._nodes = nodes;
  15869. this._geometries = geometries;
  15870. this.id = _id$8 ++;
  15871. this.renderer = renderer;
  15872. this.object = object;
  15873. this.material = material;
  15874. this.scene = scene;
  15875. this.camera = camera;
  15876. this.lightsNode = lightsNode;
  15877. this.context = renderContext;
  15878. this.geometry = object.geometry;
  15879. this.version = material.version;
  15880. this.drawRange = null;
  15881. this.attributes = null;
  15882. this.pipeline = null;
  15883. this.vertexBuffers = null;
  15884. this.drawParams = null;
  15885. this.bundle = null;
  15886. this.clippingContext = clippingContext;
  15887. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  15888. this.initialNodesCacheKey = this.getDynamicCacheKey();
  15889. this.initialCacheKey = this.getCacheKey();
  15890. this._nodeBuilderState = null;
  15891. this._bindings = null;
  15892. this._monitor = null;
  15893. this.onDispose = null;
  15894. this.isRenderObject = true;
  15895. this.onMaterialDispose = () => {
  15896. this.dispose();
  15897. };
  15898. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  15899. }
  15900. updateClipping( parent ) {
  15901. this.clippingContext = parent;
  15902. }
  15903. get clippingNeedsUpdate() {
  15904. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  15905. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  15906. return true;
  15907. }
  15908. get hardwareClippingPlanes() {
  15909. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  15910. }
  15911. getNodeBuilderState() {
  15912. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  15913. }
  15914. getMonitor() {
  15915. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  15916. }
  15917. getBindings() {
  15918. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  15919. }
  15920. getIndex() {
  15921. return this._geometries.getIndex( this );
  15922. }
  15923. getIndirect() {
  15924. return this._geometries.getIndirect( this );
  15925. }
  15926. getChainArray() {
  15927. return [ this.object, this.material, this.context, this.lightsNode ];
  15928. }
  15929. setGeometry( geometry ) {
  15930. this.geometry = geometry;
  15931. this.attributes = null;
  15932. }
  15933. getAttributes() {
  15934. if ( this.attributes !== null ) return this.attributes;
  15935. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  15936. const geometry = this.geometry;
  15937. const attributes = [];
  15938. const vertexBuffers = new Set();
  15939. for ( const nodeAttribute of nodeAttributes ) {
  15940. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  15941. if ( attribute === undefined ) continue;
  15942. attributes.push( attribute );
  15943. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  15944. vertexBuffers.add( bufferAttribute );
  15945. }
  15946. this.attributes = attributes;
  15947. this.vertexBuffers = Array.from( vertexBuffers.values() );
  15948. return attributes;
  15949. }
  15950. getVertexBuffers() {
  15951. if ( this.vertexBuffers === null ) this.getAttributes();
  15952. return this.vertexBuffers;
  15953. }
  15954. getDrawParameters() {
  15955. const { object, material, geometry, group, drawRange } = this;
  15956. const drawParams = this.drawParams || ( this.drawParams = {
  15957. vertexCount: 0,
  15958. firstVertex: 0,
  15959. instanceCount: 0,
  15960. firstInstance: 0
  15961. } );
  15962. const index = this.getIndex();
  15963. const hasIndex = ( index !== null );
  15964. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  15965. if ( instanceCount === 0 ) return null;
  15966. drawParams.instanceCount = instanceCount;
  15967. if ( object.isBatchedMesh === true ) return drawParams;
  15968. let rangeFactor = 1;
  15969. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  15970. rangeFactor = 2;
  15971. }
  15972. let firstVertex = drawRange.start * rangeFactor;
  15973. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  15974. if ( group !== null ) {
  15975. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  15976. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  15977. }
  15978. const position = geometry.attributes.position;
  15979. let itemCount = Infinity;
  15980. if ( hasIndex ) {
  15981. itemCount = index.count;
  15982. } else if ( position !== undefined && position !== null ) {
  15983. itemCount = position.count;
  15984. }
  15985. firstVertex = Math.max( firstVertex, 0 );
  15986. lastVertex = Math.min( lastVertex, itemCount );
  15987. const count = lastVertex - firstVertex;
  15988. if ( count < 0 || count === Infinity ) return null;
  15989. drawParams.vertexCount = count;
  15990. drawParams.firstVertex = firstVertex;
  15991. return drawParams;
  15992. }
  15993. getGeometryCacheKey() {
  15994. const { geometry } = this;
  15995. let cacheKey = '';
  15996. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  15997. const attribute = geometry.attributes[ name ];
  15998. cacheKey += name + ',';
  15999. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16000. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16001. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16002. if ( attribute.normalized ) cacheKey += 'n,';
  16003. }
  16004. if ( geometry.index ) {
  16005. cacheKey += 'index,';
  16006. }
  16007. return cacheKey;
  16008. }
  16009. getMaterialCacheKey() {
  16010. const { object, material } = this;
  16011. let cacheKey = material.customProgramCacheKey();
  16012. for ( const property of getKeys( material ) ) {
  16013. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16014. const value = material[ property ];
  16015. let valueKey;
  16016. if ( value !== null ) {
  16017. // some material values require a formatting
  16018. const type = typeof value;
  16019. if ( type === 'number' ) {
  16020. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16021. } else if ( type === 'object' ) {
  16022. valueKey = '{';
  16023. if ( value.isTexture ) {
  16024. valueKey += value.mapping;
  16025. }
  16026. valueKey += '}';
  16027. } else {
  16028. valueKey = String( value );
  16029. }
  16030. } else {
  16031. valueKey = String( value );
  16032. }
  16033. cacheKey += /*property + ':' +*/ valueKey + ',';
  16034. }
  16035. cacheKey += this.clippingContextCacheKey + ',';
  16036. if ( object.geometry ) {
  16037. cacheKey += this.getGeometryCacheKey();
  16038. }
  16039. if ( object.skeleton ) {
  16040. cacheKey += object.skeleton.bones.length + ',';
  16041. }
  16042. if ( object.morphTargetInfluences ) {
  16043. cacheKey += object.morphTargetInfluences.length + ',';
  16044. }
  16045. if ( object.isBatchedMesh ) {
  16046. cacheKey += object._matricesTexture.uuid + ',';
  16047. if ( object._colorsTexture !== null ) {
  16048. cacheKey += object._colorsTexture.uuid + ',';
  16049. }
  16050. }
  16051. if ( object.count > 1 ) {
  16052. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16053. cacheKey += object.uuid + ',';
  16054. }
  16055. cacheKey += object.receiveShadow + ',';
  16056. return hashString( cacheKey );
  16057. }
  16058. get needsGeometryUpdate() {
  16059. return this.geometry.id !== this.object.geometry.id;
  16060. }
  16061. get needsUpdate() {
  16062. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16063. }
  16064. getDynamicCacheKey() {
  16065. // Environment Nodes Cache Key
  16066. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16067. if ( this.object.receiveShadow ) {
  16068. cacheKey += 1;
  16069. }
  16070. return cacheKey;
  16071. }
  16072. getCacheKey() {
  16073. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16074. }
  16075. dispose() {
  16076. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16077. this.onDispose();
  16078. }
  16079. }
  16080. const chainArray = [];
  16081. class RenderObjects {
  16082. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16083. this.renderer = renderer;
  16084. this.nodes = nodes;
  16085. this.geometries = geometries;
  16086. this.pipelines = pipelines;
  16087. this.bindings = bindings;
  16088. this.info = info;
  16089. this.chainMaps = {};
  16090. }
  16091. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16092. const chainMap = this.getChainMap( passId );
  16093. // reuse chainArray
  16094. chainArray[ 0 ] = object;
  16095. chainArray[ 1 ] = material;
  16096. chainArray[ 2 ] = renderContext;
  16097. chainArray[ 3 ] = lightsNode;
  16098. let renderObject = chainMap.get( chainArray );
  16099. if ( renderObject === undefined ) {
  16100. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16101. chainMap.set( chainArray, renderObject );
  16102. } else {
  16103. renderObject.updateClipping( clippingContext );
  16104. if ( renderObject.needsGeometryUpdate ) {
  16105. renderObject.setGeometry( object.geometry );
  16106. }
  16107. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16108. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16109. renderObject.dispose();
  16110. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16111. } else {
  16112. renderObject.version = material.version;
  16113. }
  16114. }
  16115. }
  16116. return renderObject;
  16117. }
  16118. getChainMap( passId = 'default' ) {
  16119. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16120. }
  16121. dispose() {
  16122. this.chainMaps = {};
  16123. }
  16124. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16125. const chainMap = this.getChainMap( passId );
  16126. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16127. renderObject.onDispose = () => {
  16128. this.pipelines.delete( renderObject );
  16129. this.bindings.delete( renderObject );
  16130. this.nodes.delete( renderObject );
  16131. chainMap.delete( renderObject.getChainArray() );
  16132. };
  16133. return renderObject;
  16134. }
  16135. }
  16136. class DataMap {
  16137. constructor() {
  16138. this.data = new WeakMap();
  16139. }
  16140. get( object ) {
  16141. let map = this.data.get( object );
  16142. if ( map === undefined ) {
  16143. map = {};
  16144. this.data.set( object, map );
  16145. }
  16146. return map;
  16147. }
  16148. delete( object ) {
  16149. let map;
  16150. if ( this.data.has( object ) ) {
  16151. map = this.data.get( object );
  16152. this.data.delete( object );
  16153. }
  16154. return map;
  16155. }
  16156. has( object ) {
  16157. return this.data.has( object );
  16158. }
  16159. dispose() {
  16160. this.data = new WeakMap();
  16161. }
  16162. }
  16163. const AttributeType = {
  16164. VERTEX: 1,
  16165. INDEX: 2,
  16166. STORAGE: 3,
  16167. INDIRECT: 4
  16168. };
  16169. // size of a chunk in bytes (STD140 layout)
  16170. const GPU_CHUNK_BYTES = 16;
  16171. // @TODO: Move to src/constants.js
  16172. const BlendColorFactor = 211;
  16173. const OneMinusBlendColorFactor = 212;
  16174. class Attributes extends DataMap {
  16175. constructor( backend ) {
  16176. super();
  16177. this.backend = backend;
  16178. }
  16179. delete( attribute ) {
  16180. const attributeData = super.delete( attribute );
  16181. if ( attributeData !== undefined ) {
  16182. this.backend.destroyAttribute( attribute );
  16183. }
  16184. return attributeData;
  16185. }
  16186. update( attribute, type ) {
  16187. const data = this.get( attribute );
  16188. if ( data.version === undefined ) {
  16189. if ( type === AttributeType.VERTEX ) {
  16190. this.backend.createAttribute( attribute );
  16191. } else if ( type === AttributeType.INDEX ) {
  16192. this.backend.createIndexAttribute( attribute );
  16193. } else if ( type === AttributeType.STORAGE ) {
  16194. this.backend.createStorageAttribute( attribute );
  16195. } else if ( type === AttributeType.INDIRECT ) {
  16196. this.backend.createIndirectStorageAttribute( attribute );
  16197. }
  16198. data.version = this._getBufferAttribute( attribute ).version;
  16199. } else {
  16200. const bufferAttribute = this._getBufferAttribute( attribute );
  16201. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16202. this.backend.updateAttribute( attribute );
  16203. data.version = bufferAttribute.version;
  16204. }
  16205. }
  16206. }
  16207. _getBufferAttribute( attribute ) {
  16208. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16209. return attribute;
  16210. }
  16211. }
  16212. function arrayNeedsUint32( array ) {
  16213. // assumes larger values usually on last
  16214. for ( let i = array.length - 1; i >= 0; -- i ) {
  16215. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  16216. }
  16217. return false;
  16218. }
  16219. function getWireframeVersion( geometry ) {
  16220. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  16221. }
  16222. function getWireframeIndex( geometry ) {
  16223. const indices = [];
  16224. const geometryIndex = geometry.index;
  16225. const geometryPosition = geometry.attributes.position;
  16226. if ( geometryIndex !== null ) {
  16227. const array = geometryIndex.array;
  16228. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  16229. const a = array[ i + 0 ];
  16230. const b = array[ i + 1 ];
  16231. const c = array[ i + 2 ];
  16232. indices.push( a, b, b, c, c, a );
  16233. }
  16234. } else {
  16235. const array = geometryPosition.array;
  16236. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16237. const a = i + 0;
  16238. const b = i + 1;
  16239. const c = i + 2;
  16240. indices.push( a, b, b, c, c, a );
  16241. }
  16242. }
  16243. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  16244. attribute.version = getWireframeVersion( geometry );
  16245. return attribute;
  16246. }
  16247. class Geometries extends DataMap {
  16248. constructor( attributes, info ) {
  16249. super();
  16250. this.attributes = attributes;
  16251. this.info = info;
  16252. this.wireframes = new WeakMap();
  16253. this.attributeCall = new WeakMap();
  16254. }
  16255. has( renderObject ) {
  16256. const geometry = renderObject.geometry;
  16257. return super.has( geometry ) && this.get( geometry ).initialized === true;
  16258. }
  16259. updateForRender( renderObject ) {
  16260. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  16261. this.updateAttributes( renderObject );
  16262. }
  16263. initGeometry( renderObject ) {
  16264. const geometry = renderObject.geometry;
  16265. const geometryData = this.get( geometry );
  16266. geometryData.initialized = true;
  16267. this.info.memory.geometries ++;
  16268. const onDispose = () => {
  16269. this.info.memory.geometries --;
  16270. const index = geometry.index;
  16271. const geometryAttributes = renderObject.getAttributes();
  16272. if ( index !== null ) {
  16273. this.attributes.delete( index );
  16274. }
  16275. for ( const geometryAttribute of geometryAttributes ) {
  16276. this.attributes.delete( geometryAttribute );
  16277. }
  16278. const wireframeAttribute = this.wireframes.get( geometry );
  16279. if ( wireframeAttribute !== undefined ) {
  16280. this.attributes.delete( wireframeAttribute );
  16281. }
  16282. geometry.removeEventListener( 'dispose', onDispose );
  16283. };
  16284. geometry.addEventListener( 'dispose', onDispose );
  16285. }
  16286. updateAttributes( renderObject ) {
  16287. // attributes
  16288. const attributes = renderObject.getAttributes();
  16289. for ( const attribute of attributes ) {
  16290. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  16291. this.updateAttribute( attribute, AttributeType.STORAGE );
  16292. } else {
  16293. this.updateAttribute( attribute, AttributeType.VERTEX );
  16294. }
  16295. }
  16296. // indexes
  16297. const index = this.getIndex( renderObject );
  16298. if ( index !== null ) {
  16299. this.updateAttribute( index, AttributeType.INDEX );
  16300. }
  16301. // indirect
  16302. const indirect = renderObject.geometry.indirect;
  16303. if ( indirect !== null ) {
  16304. this.updateAttribute( indirect, AttributeType.INDIRECT );
  16305. }
  16306. }
  16307. updateAttribute( attribute, type ) {
  16308. const callId = this.info.render.calls;
  16309. if ( ! attribute.isInterleavedBufferAttribute ) {
  16310. if ( this.attributeCall.get( attribute ) !== callId ) {
  16311. this.attributes.update( attribute, type );
  16312. this.attributeCall.set( attribute, callId );
  16313. }
  16314. } else {
  16315. if ( this.attributeCall.get( attribute ) === undefined ) {
  16316. this.attributes.update( attribute, type );
  16317. this.attributeCall.set( attribute, callId );
  16318. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  16319. this.attributes.update( attribute, type );
  16320. this.attributeCall.set( attribute.data, callId );
  16321. this.attributeCall.set( attribute, callId );
  16322. }
  16323. }
  16324. }
  16325. getIndirect( renderObject ) {
  16326. return renderObject.geometry.indirect;
  16327. }
  16328. getIndex( renderObject ) {
  16329. const { geometry, material } = renderObject;
  16330. let index = geometry.index;
  16331. if ( material.wireframe === true ) {
  16332. const wireframes = this.wireframes;
  16333. let wireframeAttribute = wireframes.get( geometry );
  16334. if ( wireframeAttribute === undefined ) {
  16335. wireframeAttribute = getWireframeIndex( geometry );
  16336. wireframes.set( geometry, wireframeAttribute );
  16337. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  16338. this.attributes.delete( wireframeAttribute );
  16339. wireframeAttribute = getWireframeIndex( geometry );
  16340. wireframes.set( geometry, wireframeAttribute );
  16341. }
  16342. index = wireframeAttribute;
  16343. }
  16344. return index;
  16345. }
  16346. }
  16347. class Info {
  16348. constructor() {
  16349. this.autoReset = true;
  16350. this.frame = 0;
  16351. this.calls = 0;
  16352. this.render = {
  16353. calls: 0,
  16354. frameCalls: 0,
  16355. drawCalls: 0,
  16356. triangles: 0,
  16357. points: 0,
  16358. lines: 0,
  16359. timestamp: 0,
  16360. previousFrameCalls: 0,
  16361. timestampCalls: 0
  16362. };
  16363. this.compute = {
  16364. calls: 0,
  16365. frameCalls: 0,
  16366. timestamp: 0,
  16367. previousFrameCalls: 0,
  16368. timestampCalls: 0
  16369. };
  16370. this.memory = {
  16371. geometries: 0,
  16372. textures: 0
  16373. };
  16374. }
  16375. update( object, count, instanceCount ) {
  16376. this.render.drawCalls ++;
  16377. if ( object.isMesh || object.isSprite ) {
  16378. this.render.triangles += instanceCount * ( count / 3 );
  16379. } else if ( object.isPoints ) {
  16380. this.render.points += instanceCount * count;
  16381. } else if ( object.isLineSegments ) {
  16382. this.render.lines += instanceCount * ( count / 2 );
  16383. } else if ( object.isLine ) {
  16384. this.render.lines += instanceCount * ( count - 1 );
  16385. } else {
  16386. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  16387. }
  16388. }
  16389. updateTimestamp( type, time ) {
  16390. if ( this[ type ].timestampCalls === 0 ) {
  16391. this[ type ].timestamp = 0;
  16392. }
  16393. this[ type ].timestamp += time;
  16394. this[ type ].timestampCalls ++;
  16395. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  16396. this[ type ].timestampCalls = 0;
  16397. }
  16398. }
  16399. reset() {
  16400. const previousRenderFrameCalls = this.render.frameCalls;
  16401. this.render.previousFrameCalls = previousRenderFrameCalls;
  16402. const previousComputeFrameCalls = this.compute.frameCalls;
  16403. this.compute.previousFrameCalls = previousComputeFrameCalls;
  16404. this.render.drawCalls = 0;
  16405. this.render.frameCalls = 0;
  16406. this.compute.frameCalls = 0;
  16407. this.render.triangles = 0;
  16408. this.render.points = 0;
  16409. this.render.lines = 0;
  16410. }
  16411. dispose() {
  16412. this.reset();
  16413. this.calls = 0;
  16414. this.render.calls = 0;
  16415. this.compute.calls = 0;
  16416. this.render.timestamp = 0;
  16417. this.compute.timestamp = 0;
  16418. this.memory.geometries = 0;
  16419. this.memory.textures = 0;
  16420. }
  16421. }
  16422. class Pipeline {
  16423. constructor( cacheKey ) {
  16424. this.cacheKey = cacheKey;
  16425. this.usedTimes = 0;
  16426. }
  16427. }
  16428. class RenderPipeline extends Pipeline {
  16429. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  16430. super( cacheKey );
  16431. this.vertexProgram = vertexProgram;
  16432. this.fragmentProgram = fragmentProgram;
  16433. }
  16434. }
  16435. class ComputePipeline extends Pipeline {
  16436. constructor( cacheKey, computeProgram ) {
  16437. super( cacheKey );
  16438. this.computeProgram = computeProgram;
  16439. this.isComputePipeline = true;
  16440. }
  16441. }
  16442. let _id$7 = 0;
  16443. class ProgrammableStage {
  16444. constructor( code, type, transforms = null, attributes = null ) {
  16445. this.id = _id$7 ++;
  16446. this.code = code;
  16447. this.stage = type;
  16448. this.transforms = transforms;
  16449. this.attributes = attributes;
  16450. this.usedTimes = 0;
  16451. }
  16452. }
  16453. class Pipelines extends DataMap {
  16454. constructor( backend, nodes ) {
  16455. super();
  16456. this.backend = backend;
  16457. this.nodes = nodes;
  16458. this.bindings = null; // set by the bindings
  16459. this.caches = new Map();
  16460. this.programs = {
  16461. vertex: new Map(),
  16462. fragment: new Map(),
  16463. compute: new Map()
  16464. };
  16465. }
  16466. getForCompute( computeNode, bindings ) {
  16467. const { backend } = this;
  16468. const data = this.get( computeNode );
  16469. if ( this._needsComputeUpdate( computeNode ) ) {
  16470. const previousPipeline = data.pipeline;
  16471. if ( previousPipeline ) {
  16472. previousPipeline.usedTimes --;
  16473. previousPipeline.computeProgram.usedTimes --;
  16474. }
  16475. // get shader
  16476. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  16477. // programmable stage
  16478. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  16479. if ( stageCompute === undefined ) {
  16480. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  16481. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  16482. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  16483. backend.createProgram( stageCompute );
  16484. }
  16485. // determine compute pipeline
  16486. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  16487. let pipeline = this.caches.get( cacheKey );
  16488. if ( pipeline === undefined ) {
  16489. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  16490. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  16491. }
  16492. // keep track of all used times
  16493. pipeline.usedTimes ++;
  16494. stageCompute.usedTimes ++;
  16495. //
  16496. data.version = computeNode.version;
  16497. data.pipeline = pipeline;
  16498. }
  16499. return data.pipeline;
  16500. }
  16501. getForRender( renderObject, promises = null ) {
  16502. const { backend } = this;
  16503. const data = this.get( renderObject );
  16504. if ( this._needsRenderUpdate( renderObject ) ) {
  16505. const previousPipeline = data.pipeline;
  16506. if ( previousPipeline ) {
  16507. previousPipeline.usedTimes --;
  16508. previousPipeline.vertexProgram.usedTimes --;
  16509. previousPipeline.fragmentProgram.usedTimes --;
  16510. }
  16511. // get shader
  16512. const nodeBuilderState = renderObject.getNodeBuilderState();
  16513. // programmable stages
  16514. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  16515. if ( stageVertex === undefined ) {
  16516. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  16517. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  16518. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  16519. backend.createProgram( stageVertex );
  16520. }
  16521. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  16522. if ( stageFragment === undefined ) {
  16523. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  16524. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  16525. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  16526. backend.createProgram( stageFragment );
  16527. }
  16528. // determine render pipeline
  16529. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  16530. let pipeline = this.caches.get( cacheKey );
  16531. if ( pipeline === undefined ) {
  16532. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  16533. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  16534. } else {
  16535. renderObject.pipeline = pipeline;
  16536. }
  16537. // keep track of all used times
  16538. pipeline.usedTimes ++;
  16539. stageVertex.usedTimes ++;
  16540. stageFragment.usedTimes ++;
  16541. //
  16542. data.pipeline = pipeline;
  16543. }
  16544. return data.pipeline;
  16545. }
  16546. delete( object ) {
  16547. const pipeline = this.get( object ).pipeline;
  16548. if ( pipeline ) {
  16549. // pipeline
  16550. pipeline.usedTimes --;
  16551. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  16552. // programs
  16553. if ( pipeline.isComputePipeline ) {
  16554. pipeline.computeProgram.usedTimes --;
  16555. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  16556. } else {
  16557. pipeline.fragmentProgram.usedTimes --;
  16558. pipeline.vertexProgram.usedTimes --;
  16559. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  16560. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  16561. }
  16562. }
  16563. return super.delete( object );
  16564. }
  16565. dispose() {
  16566. super.dispose();
  16567. this.caches = new Map();
  16568. this.programs = {
  16569. vertex: new Map(),
  16570. fragment: new Map(),
  16571. compute: new Map()
  16572. };
  16573. }
  16574. updateForRender( renderObject ) {
  16575. this.getForRender( renderObject );
  16576. }
  16577. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  16578. // check for existing pipeline
  16579. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  16580. let pipeline = this.caches.get( cacheKey );
  16581. if ( pipeline === undefined ) {
  16582. pipeline = new ComputePipeline( cacheKey, stageCompute );
  16583. this.caches.set( cacheKey, pipeline );
  16584. this.backend.createComputePipeline( pipeline, bindings );
  16585. }
  16586. return pipeline;
  16587. }
  16588. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  16589. // check for existing pipeline
  16590. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  16591. let pipeline = this.caches.get( cacheKey );
  16592. if ( pipeline === undefined ) {
  16593. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  16594. this.caches.set( cacheKey, pipeline );
  16595. renderObject.pipeline = pipeline;
  16596. this.backend.createRenderPipeline( renderObject, promises );
  16597. }
  16598. return pipeline;
  16599. }
  16600. _getComputeCacheKey( computeNode, stageCompute ) {
  16601. return computeNode.id + ',' + stageCompute.id;
  16602. }
  16603. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  16604. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  16605. }
  16606. _releasePipeline( pipeline ) {
  16607. this.caches.delete( pipeline.cacheKey );
  16608. }
  16609. _releaseProgram( program ) {
  16610. const code = program.code;
  16611. const stage = program.stage;
  16612. this.programs[ stage ].delete( code );
  16613. }
  16614. _needsComputeUpdate( computeNode ) {
  16615. const data = this.get( computeNode );
  16616. return data.pipeline === undefined || data.version !== computeNode.version;
  16617. }
  16618. _needsRenderUpdate( renderObject ) {
  16619. const data = this.get( renderObject );
  16620. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  16621. }
  16622. }
  16623. class Bindings extends DataMap {
  16624. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  16625. super();
  16626. this.backend = backend;
  16627. this.textures = textures;
  16628. this.pipelines = pipelines;
  16629. this.attributes = attributes;
  16630. this.nodes = nodes;
  16631. this.info = info;
  16632. this.pipelines.bindings = this; // assign bindings to pipelines
  16633. }
  16634. getForRender( renderObject ) {
  16635. const bindings = renderObject.getBindings();
  16636. for ( const bindGroup of bindings ) {
  16637. const groupData = this.get( bindGroup );
  16638. if ( groupData.bindGroup === undefined ) {
  16639. // each object defines an array of bindings (ubos, textures, samplers etc.)
  16640. this._init( bindGroup );
  16641. this.backend.createBindings( bindGroup, bindings, 0 );
  16642. groupData.bindGroup = bindGroup;
  16643. }
  16644. }
  16645. return bindings;
  16646. }
  16647. getForCompute( computeNode ) {
  16648. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  16649. for ( const bindGroup of bindings ) {
  16650. const groupData = this.get( bindGroup );
  16651. if ( groupData.bindGroup === undefined ) {
  16652. this._init( bindGroup );
  16653. this.backend.createBindings( bindGroup, bindings, 0 );
  16654. groupData.bindGroup = bindGroup;
  16655. }
  16656. }
  16657. return bindings;
  16658. }
  16659. updateForCompute( computeNode ) {
  16660. this._updateBindings( this.getForCompute( computeNode ) );
  16661. }
  16662. updateForRender( renderObject ) {
  16663. this._updateBindings( this.getForRender( renderObject ) );
  16664. }
  16665. _updateBindings( bindings ) {
  16666. for ( const bindGroup of bindings ) {
  16667. this._update( bindGroup, bindings );
  16668. }
  16669. }
  16670. _init( bindGroup ) {
  16671. for ( const binding of bindGroup.bindings ) {
  16672. if ( binding.isSampledTexture ) {
  16673. this.textures.updateTexture( binding.texture );
  16674. } else if ( binding.isStorageBuffer ) {
  16675. const attribute = binding.attribute;
  16676. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  16677. this.attributes.update( attribute, attributeType );
  16678. }
  16679. }
  16680. }
  16681. _update( bindGroup, bindings ) {
  16682. const { backend } = this;
  16683. let needsBindingsUpdate = false;
  16684. let cacheBindings = true;
  16685. let cacheIndex = 0;
  16686. let version = 0;
  16687. // iterate over all bindings and check if buffer updates or a new binding group is required
  16688. for ( const binding of bindGroup.bindings ) {
  16689. if ( binding.isNodeUniformsGroup ) {
  16690. const updated = this.nodes.updateGroup( binding );
  16691. if ( ! updated ) continue;
  16692. }
  16693. if ( binding.isUniformBuffer ) {
  16694. const updated = binding.update();
  16695. if ( updated ) {
  16696. backend.updateBinding( binding );
  16697. }
  16698. } else if ( binding.isSampler ) {
  16699. binding.update();
  16700. } else if ( binding.isSampledTexture ) {
  16701. const texturesTextureData = this.textures.get( binding.texture );
  16702. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  16703. const updated = binding.update();
  16704. const texture = binding.texture;
  16705. if ( updated ) {
  16706. this.textures.updateTexture( texture );
  16707. }
  16708. const textureData = backend.get( texture );
  16709. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  16710. cacheBindings = false;
  16711. } else {
  16712. cacheIndex = cacheIndex * 10 + texture.id;
  16713. version += texture.version;
  16714. }
  16715. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  16716. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  16717. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  16718. this.textures.updateTexture( texture );
  16719. needsBindingsUpdate = true;
  16720. }
  16721. if ( texture.isStorageTexture === true ) {
  16722. const textureData = this.get( texture );
  16723. if ( binding.store === true ) {
  16724. textureData.needsMipmap = true;
  16725. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  16726. this.backend.generateMipmaps( texture );
  16727. textureData.needsMipmap = false;
  16728. }
  16729. }
  16730. }
  16731. }
  16732. if ( needsBindingsUpdate === true ) {
  16733. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  16734. }
  16735. }
  16736. }
  16737. function painterSortStable( a, b ) {
  16738. if ( a.groupOrder !== b.groupOrder ) {
  16739. return a.groupOrder - b.groupOrder;
  16740. } else if ( a.renderOrder !== b.renderOrder ) {
  16741. return a.renderOrder - b.renderOrder;
  16742. } else if ( a.material.id !== b.material.id ) {
  16743. return a.material.id - b.material.id;
  16744. } else if ( a.z !== b.z ) {
  16745. return a.z - b.z;
  16746. } else {
  16747. return a.id - b.id;
  16748. }
  16749. }
  16750. function reversePainterSortStable( a, b ) {
  16751. if ( a.groupOrder !== b.groupOrder ) {
  16752. return a.groupOrder - b.groupOrder;
  16753. } else if ( a.renderOrder !== b.renderOrder ) {
  16754. return a.renderOrder - b.renderOrder;
  16755. } else if ( a.z !== b.z ) {
  16756. return b.z - a.z;
  16757. } else {
  16758. return a.id - b.id;
  16759. }
  16760. }
  16761. function needsDoublePass( material ) {
  16762. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  16763. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  16764. }
  16765. class RenderList {
  16766. constructor( lighting, scene, camera ) {
  16767. this.renderItems = [];
  16768. this.renderItemsIndex = 0;
  16769. this.opaque = [];
  16770. this.transparentDoublePass = [];
  16771. this.transparent = [];
  16772. this.bundles = [];
  16773. this.lightsNode = lighting.getNode( scene, camera );
  16774. this.lightsArray = [];
  16775. this.scene = scene;
  16776. this.camera = camera;
  16777. this.occlusionQueryCount = 0;
  16778. }
  16779. begin() {
  16780. this.renderItemsIndex = 0;
  16781. this.opaque.length = 0;
  16782. this.transparentDoublePass.length = 0;
  16783. this.transparent.length = 0;
  16784. this.bundles.length = 0;
  16785. this.lightsArray.length = 0;
  16786. this.occlusionQueryCount = 0;
  16787. return this;
  16788. }
  16789. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  16790. let renderItem = this.renderItems[ this.renderItemsIndex ];
  16791. if ( renderItem === undefined ) {
  16792. renderItem = {
  16793. id: object.id,
  16794. object: object,
  16795. geometry: geometry,
  16796. material: material,
  16797. groupOrder: groupOrder,
  16798. renderOrder: object.renderOrder,
  16799. z: z,
  16800. group: group,
  16801. clippingContext: clippingContext
  16802. };
  16803. this.renderItems[ this.renderItemsIndex ] = renderItem;
  16804. } else {
  16805. renderItem.id = object.id;
  16806. renderItem.object = object;
  16807. renderItem.geometry = geometry;
  16808. renderItem.material = material;
  16809. renderItem.groupOrder = groupOrder;
  16810. renderItem.renderOrder = object.renderOrder;
  16811. renderItem.z = z;
  16812. renderItem.group = group;
  16813. renderItem.clippingContext = clippingContext;
  16814. }
  16815. this.renderItemsIndex ++;
  16816. return renderItem;
  16817. }
  16818. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  16819. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  16820. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  16821. if ( material.transparent === true || material.transmission > 0 ) {
  16822. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  16823. this.transparent.push( renderItem );
  16824. } else {
  16825. this.opaque.push( renderItem );
  16826. }
  16827. }
  16828. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  16829. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  16830. if ( material.transparent === true || material.transmission > 0 ) {
  16831. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  16832. this.transparent.unshift( renderItem );
  16833. } else {
  16834. this.opaque.unshift( renderItem );
  16835. }
  16836. }
  16837. pushBundle( group ) {
  16838. this.bundles.push( group );
  16839. }
  16840. pushLight( light ) {
  16841. this.lightsArray.push( light );
  16842. }
  16843. sort( customOpaqueSort, customTransparentSort ) {
  16844. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  16845. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  16846. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  16847. }
  16848. finish() {
  16849. // update lights
  16850. this.lightsNode.setLights( this.lightsArray );
  16851. // Clear references from inactive renderItems in the list
  16852. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  16853. const renderItem = this.renderItems[ i ];
  16854. if ( renderItem.id === null ) break;
  16855. renderItem.id = null;
  16856. renderItem.object = null;
  16857. renderItem.geometry = null;
  16858. renderItem.material = null;
  16859. renderItem.groupOrder = null;
  16860. renderItem.renderOrder = null;
  16861. renderItem.z = null;
  16862. renderItem.group = null;
  16863. renderItem.clippingContext = null;
  16864. }
  16865. }
  16866. }
  16867. class RenderLists {
  16868. constructor( lighting ) {
  16869. this.lighting = lighting;
  16870. this.lists = new ChainMap();
  16871. }
  16872. get( scene, camera ) {
  16873. const lists = this.lists;
  16874. const keys = [ scene, camera ];
  16875. let list = lists.get( keys );
  16876. if ( list === undefined ) {
  16877. list = new RenderList( this.lighting, scene, camera );
  16878. lists.set( keys, list );
  16879. }
  16880. return list;
  16881. }
  16882. dispose() {
  16883. this.lists = new ChainMap();
  16884. }
  16885. }
  16886. let id = 0;
  16887. class RenderContext {
  16888. constructor() {
  16889. this.id = id ++;
  16890. this.color = true;
  16891. this.clearColor = true;
  16892. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  16893. this.depth = true;
  16894. this.clearDepth = true;
  16895. this.clearDepthValue = 1;
  16896. this.stencil = false;
  16897. this.clearStencil = true;
  16898. this.clearStencilValue = 1;
  16899. this.viewport = false;
  16900. this.viewportValue = new Vector4();
  16901. this.scissor = false;
  16902. this.scissorValue = new Vector4();
  16903. this.textures = null;
  16904. this.depthTexture = null;
  16905. this.activeCubeFace = 0;
  16906. this.sampleCount = 1;
  16907. this.width = 0;
  16908. this.height = 0;
  16909. this.isRenderContext = true;
  16910. }
  16911. getCacheKey() {
  16912. return getCacheKey( this );
  16913. }
  16914. }
  16915. function getCacheKey( renderContext ) {
  16916. const { textures, activeCubeFace } = renderContext;
  16917. const values = [ activeCubeFace ];
  16918. for ( const texture of textures ) {
  16919. values.push( texture.id );
  16920. }
  16921. return hashArray( values );
  16922. }
  16923. class RenderContexts {
  16924. constructor() {
  16925. this.chainMaps = {};
  16926. }
  16927. get( scene, camera, renderTarget = null ) {
  16928. const chainKey = [ scene, camera ];
  16929. let attachmentState;
  16930. if ( renderTarget === null ) {
  16931. attachmentState = 'default';
  16932. } else {
  16933. const format = renderTarget.texture.format;
  16934. const count = renderTarget.textures.length;
  16935. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  16936. }
  16937. const chainMap = this.getChainMap( attachmentState );
  16938. let renderState = chainMap.get( chainKey );
  16939. if ( renderState === undefined ) {
  16940. renderState = new RenderContext();
  16941. chainMap.set( chainKey, renderState );
  16942. }
  16943. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  16944. return renderState;
  16945. }
  16946. getChainMap( attachmentState ) {
  16947. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  16948. }
  16949. dispose() {
  16950. this.chainMaps = {};
  16951. }
  16952. }
  16953. const _size$3 = /*@__PURE__*/ new Vector3();
  16954. class Textures extends DataMap {
  16955. constructor( renderer, backend, info ) {
  16956. super();
  16957. this.renderer = renderer;
  16958. this.backend = backend;
  16959. this.info = info;
  16960. }
  16961. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  16962. const renderTargetData = this.get( renderTarget );
  16963. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  16964. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  16965. const textures = renderTarget.textures;
  16966. const size = this.getSize( textures[ 0 ] );
  16967. const mipWidth = size.width >> activeMipmapLevel;
  16968. const mipHeight = size.height >> activeMipmapLevel;
  16969. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  16970. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  16971. let textureNeedsUpdate = false;
  16972. if ( depthTexture === undefined && useDepthTexture ) {
  16973. depthTexture = new DepthTexture();
  16974. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  16975. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  16976. depthTexture.image.width = mipWidth;
  16977. depthTexture.image.height = mipHeight;
  16978. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  16979. }
  16980. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  16981. textureNeedsUpdate = true;
  16982. if ( depthTexture ) {
  16983. depthTexture.needsUpdate = true;
  16984. depthTexture.image.width = mipWidth;
  16985. depthTexture.image.height = mipHeight;
  16986. }
  16987. }
  16988. renderTargetData.width = size.width;
  16989. renderTargetData.height = size.height;
  16990. renderTargetData.textures = textures;
  16991. renderTargetData.depthTexture = depthTexture || null;
  16992. renderTargetData.depth = renderTarget.depthBuffer;
  16993. renderTargetData.stencil = renderTarget.stencilBuffer;
  16994. renderTargetData.renderTarget = renderTarget;
  16995. if ( renderTargetData.sampleCount !== sampleCount ) {
  16996. textureNeedsUpdate = true;
  16997. if ( depthTexture ) {
  16998. depthTexture.needsUpdate = true;
  16999. }
  17000. renderTargetData.sampleCount = sampleCount;
  17001. }
  17002. //
  17003. const options = { sampleCount };
  17004. for ( let i = 0; i < textures.length; i ++ ) {
  17005. const texture = textures[ i ];
  17006. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  17007. this.updateTexture( texture, options );
  17008. }
  17009. if ( depthTexture ) {
  17010. this.updateTexture( depthTexture, options );
  17011. }
  17012. // dispose handler
  17013. if ( renderTargetData.initialized !== true ) {
  17014. renderTargetData.initialized = true;
  17015. // dispose
  17016. const onDispose = () => {
  17017. renderTarget.removeEventListener( 'dispose', onDispose );
  17018. for ( let i = 0; i < textures.length; i ++ ) {
  17019. this._destroyTexture( textures[ i ] );
  17020. }
  17021. if ( depthTexture ) {
  17022. this._destroyTexture( depthTexture );
  17023. }
  17024. this.delete( renderTarget );
  17025. };
  17026. renderTarget.addEventListener( 'dispose', onDispose );
  17027. }
  17028. }
  17029. updateTexture( texture, options = {} ) {
  17030. const textureData = this.get( texture );
  17031. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  17032. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  17033. const backend = this.backend;
  17034. if ( isRenderTarget && textureData.initialized === true ) {
  17035. // it's an update
  17036. backend.destroySampler( texture );
  17037. backend.destroyTexture( texture );
  17038. }
  17039. //
  17040. if ( texture.isFramebufferTexture ) {
  17041. const renderTarget = this.renderer.getRenderTarget();
  17042. if ( renderTarget ) {
  17043. texture.type = renderTarget.texture.type;
  17044. } else {
  17045. texture.type = UnsignedByteType;
  17046. }
  17047. }
  17048. //
  17049. const { width, height, depth } = this.getSize( texture );
  17050. options.width = width;
  17051. options.height = height;
  17052. options.depth = depth;
  17053. options.needsMipmaps = this.needsMipmaps( texture );
  17054. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  17055. //
  17056. if ( isRenderTarget || texture.isStorageTexture === true ) {
  17057. backend.createSampler( texture );
  17058. backend.createTexture( texture, options );
  17059. textureData.generation = texture.version;
  17060. } else {
  17061. const needsCreate = textureData.initialized !== true;
  17062. if ( needsCreate ) backend.createSampler( texture );
  17063. if ( texture.version > 0 ) {
  17064. const image = texture.image;
  17065. if ( image === undefined ) {
  17066. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  17067. } else if ( image.complete === false ) {
  17068. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  17069. } else {
  17070. if ( texture.images ) {
  17071. const images = [];
  17072. for ( const image of texture.images ) {
  17073. images.push( image );
  17074. }
  17075. options.images = images;
  17076. } else {
  17077. options.image = image;
  17078. }
  17079. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  17080. backend.createTexture( texture, options );
  17081. textureData.isDefaultTexture = false;
  17082. textureData.generation = texture.version;
  17083. }
  17084. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  17085. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  17086. }
  17087. } else {
  17088. // async update
  17089. backend.createDefaultTexture( texture );
  17090. textureData.isDefaultTexture = true;
  17091. textureData.generation = texture.version;
  17092. }
  17093. }
  17094. // dispose handler
  17095. if ( textureData.initialized !== true ) {
  17096. textureData.initialized = true;
  17097. textureData.generation = texture.version;
  17098. //
  17099. this.info.memory.textures ++;
  17100. // dispose
  17101. const onDispose = () => {
  17102. texture.removeEventListener( 'dispose', onDispose );
  17103. this._destroyTexture( texture );
  17104. this.info.memory.textures --;
  17105. };
  17106. texture.addEventListener( 'dispose', onDispose );
  17107. }
  17108. //
  17109. textureData.version = texture.version;
  17110. }
  17111. getSize( texture, target = _size$3 ) {
  17112. let image = texture.images ? texture.images[ 0 ] : texture.image;
  17113. if ( image ) {
  17114. if ( image.image !== undefined ) image = image.image;
  17115. target.width = image.width || 1;
  17116. target.height = image.height || 1;
  17117. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  17118. } else {
  17119. target.width = target.height = target.depth = 1;
  17120. }
  17121. return target;
  17122. }
  17123. getMipLevels( texture, width, height ) {
  17124. let mipLevelCount;
  17125. if ( texture.isCompressedTexture ) {
  17126. if ( texture.mipmaps ) {
  17127. mipLevelCount = texture.mipmaps.length;
  17128. } else {
  17129. mipLevelCount = 1;
  17130. }
  17131. } else {
  17132. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  17133. }
  17134. return mipLevelCount;
  17135. }
  17136. needsMipmaps( texture ) {
  17137. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  17138. }
  17139. isEnvironmentTexture( texture ) {
  17140. const mapping = texture.mapping;
  17141. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  17142. }
  17143. _destroyTexture( texture ) {
  17144. this.backend.destroySampler( texture );
  17145. this.backend.destroyTexture( texture );
  17146. this.delete( texture );
  17147. }
  17148. }
  17149. class Color4 extends Color {
  17150. constructor( r, g, b, a = 1 ) {
  17151. super( r, g, b );
  17152. this.a = a;
  17153. }
  17154. set( r, g, b, a = 1 ) {
  17155. this.a = a;
  17156. return super.set( r, g, b );
  17157. }
  17158. copy( color ) {
  17159. if ( color.a !== undefined ) this.a = color.a;
  17160. return super.copy( color );
  17161. }
  17162. clone() {
  17163. return new this.constructor( this.r, this.g, this.b, this.a );
  17164. }
  17165. }
  17166. /** @module ParameterNode **/
  17167. /**
  17168. * Special version of {@link PropertyNode} which is used for parameters.
  17169. *
  17170. * @augments PropertyNode
  17171. */
  17172. class ParameterNode extends PropertyNode {
  17173. static get type() {
  17174. return 'ParameterNode';
  17175. }
  17176. /**
  17177. * Constructs a new parameter node.
  17178. *
  17179. * @param {String} nodeType - The type of the node.
  17180. * @param {String?} [name=null] - The name of the parameter in the shader.
  17181. */
  17182. constructor( nodeType, name = null ) {
  17183. super( nodeType, name );
  17184. /**
  17185. * This flag can be used for type testing.
  17186. *
  17187. * @type {Boolean}
  17188. * @readonly
  17189. * @default true
  17190. */
  17191. this.isParameterNode = true;
  17192. }
  17193. getHash() {
  17194. return this.uuid;
  17195. }
  17196. generate() {
  17197. return this.name;
  17198. }
  17199. }
  17200. /**
  17201. * TSL function for creating a parameter node.
  17202. *
  17203. * @function
  17204. * @param {String} type - The type of the node.
  17205. * @param {String?} name - The name of the parameter in the shader.
  17206. * @returns {ParameterNode}
  17207. */
  17208. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  17209. /** @module StackNode **/
  17210. /**
  17211. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  17212. * They are usually needed in cases like `If`, `Else`.
  17213. *
  17214. * @augments Node
  17215. */
  17216. class StackNode extends Node {
  17217. static get type() {
  17218. return 'StackNode';
  17219. }
  17220. /**
  17221. * Constructs a new stack node.
  17222. *
  17223. * @param {StackNode?} [parent=null] - The parent stack node.
  17224. */
  17225. constructor( parent = null ) {
  17226. super();
  17227. /**
  17228. * List of nodes.
  17229. *
  17230. * @type {Array<Node>}
  17231. */
  17232. this.nodes = [];
  17233. /**
  17234. * The output node.
  17235. *
  17236. * @type {Node?}
  17237. * @default null
  17238. */
  17239. this.outputNode = null;
  17240. /**
  17241. * The parent stack node.
  17242. *
  17243. * @type {StackNode}
  17244. * @default null
  17245. */
  17246. this.parent = parent;
  17247. /**
  17248. * The current conditional node.
  17249. *
  17250. * @private
  17251. * @type {ConditionalNode}
  17252. * @default null
  17253. */
  17254. this._currentCond = null;
  17255. /**
  17256. * This flag can be used for type testing.
  17257. *
  17258. * @type {Boolean}
  17259. * @readonly
  17260. * @default true
  17261. */
  17262. this.isStackNode = true;
  17263. }
  17264. getNodeType( builder ) {
  17265. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  17266. }
  17267. /**
  17268. * Adds a node to this stack.
  17269. *
  17270. * @param {Node} node - The node to add.
  17271. * @return {StackNode} A reference to this stack node.
  17272. */
  17273. add( node ) {
  17274. this.nodes.push( node );
  17275. return this;
  17276. }
  17277. /**
  17278. * Represent an `if` statement in TSL.
  17279. *
  17280. * @param {Node} boolNode - Represents the condition.
  17281. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  17282. * @return {StackNode} A reference to this stack node.
  17283. */
  17284. If( boolNode, method ) {
  17285. const methodNode = new ShaderNode( method );
  17286. this._currentCond = select( boolNode, methodNode );
  17287. return this.add( this._currentCond );
  17288. }
  17289. /**
  17290. * Represent an `elseif` statement in TSL.
  17291. *
  17292. * @param {Node} boolNode - Represents the condition.
  17293. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  17294. * @return {StackNode} A reference to this stack node.
  17295. */
  17296. ElseIf( boolNode, method ) {
  17297. const methodNode = new ShaderNode( method );
  17298. const ifNode = select( boolNode, methodNode );
  17299. this._currentCond.elseNode = ifNode;
  17300. this._currentCond = ifNode;
  17301. return this;
  17302. }
  17303. /**
  17304. * Represent an `else` statement in TSL.
  17305. *
  17306. * @param {Function} method - TSL code which is executed in the `else` case.
  17307. * @return {StackNode} A reference to this stack node.
  17308. */
  17309. Else( method ) {
  17310. this._currentCond.elseNode = new ShaderNode( method );
  17311. return this;
  17312. }
  17313. build( builder, ...params ) {
  17314. const previousStack = getCurrentStack();
  17315. setCurrentStack( this );
  17316. for ( const node of this.nodes ) {
  17317. node.build( builder, 'void' );
  17318. }
  17319. setCurrentStack( previousStack );
  17320. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  17321. }
  17322. //
  17323. else( ...params ) { // @deprecated, r168
  17324. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  17325. return this.Else( ...params );
  17326. }
  17327. elseif( ...params ) { // @deprecated, r168
  17328. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  17329. return this.ElseIf( ...params );
  17330. }
  17331. }
  17332. /**
  17333. * TSL function for creating a stack node.
  17334. *
  17335. * @function
  17336. * @param {StackNode?} [parent=null] - The parent stack node.
  17337. * @returns {StackNode}
  17338. */
  17339. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  17340. /** @module OutputStructNode **/
  17341. /**
  17342. * This node can be used to define multiple outputs in a shader programs.
  17343. *
  17344. * @augments Node
  17345. */
  17346. class OutputStructNode extends Node {
  17347. static get type() {
  17348. return 'OutputStructNode';
  17349. }
  17350. /**
  17351. * Constructs a new output struct node. The constructor can be invoked with an
  17352. * arbitrary number of nodes representing the members.
  17353. *
  17354. * @param {...Node} members - A parameter list of nodes.
  17355. */
  17356. constructor( ...members ) {
  17357. super();
  17358. /**
  17359. * An array of nodes which defines the output.
  17360. *
  17361. * @type {Array<Node>}
  17362. */
  17363. this.members = members;
  17364. /**
  17365. * This flag can be used for type testing.
  17366. *
  17367. * @type {Boolean}
  17368. * @readonly
  17369. * @default true
  17370. */
  17371. this.isOutputStructNode = true;
  17372. }
  17373. setup( builder ) {
  17374. super.setup( builder );
  17375. const members = this.members;
  17376. const types = [];
  17377. for ( let i = 0; i < members.length; i ++ ) {
  17378. types.push( members[ i ].getNodeType( builder ) );
  17379. }
  17380. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  17381. }
  17382. generate( builder, output ) {
  17383. const propertyName = builder.getOutputStructName();
  17384. const members = this.members;
  17385. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  17386. for ( let i = 0; i < members.length; i ++ ) {
  17387. const snippet = members[ i ].build( builder, output );
  17388. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  17389. }
  17390. return propertyName;
  17391. }
  17392. }
  17393. /**
  17394. * TSL function for creating an output struct node.
  17395. *
  17396. * @function
  17397. * @param {...Node} members - A parameter list of nodes.
  17398. * @returns {OutputStructNode}
  17399. */
  17400. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  17401. /** @module MRTNode **/
  17402. /**
  17403. * Returns the MRT texture index for the given name.
  17404. *
  17405. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  17406. * @param {String} name - The name of the MRT texture which index is requested.
  17407. * @return {Number} The texture index.
  17408. */
  17409. function getTextureIndex( textures, name ) {
  17410. for ( let i = 0; i < textures.length; i ++ ) {
  17411. if ( textures[ i ].name === name ) {
  17412. return i;
  17413. }
  17414. }
  17415. return - 1;
  17416. }
  17417. /**
  17418. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  17419. * post-processing is shown below:
  17420. * ```js
  17421. * const mrtNode = mrt( {
  17422. * output: output,
  17423. * normal: normalView
  17424. * } ) );
  17425. * ```
  17426. * The MRT output is defined as a dictionary.
  17427. *
  17428. * @augments OutputStructNode
  17429. */
  17430. class MRTNode extends OutputStructNode {
  17431. static get type() {
  17432. return 'MRTNode';
  17433. }
  17434. /**
  17435. * Constructs a new output struct node.
  17436. *
  17437. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  17438. */
  17439. constructor( outputNodes ) {
  17440. super();
  17441. /**
  17442. * A dictionary representing the MRT outputs. The key
  17443. * is the name of the output, the value the node which produces
  17444. * the output result.
  17445. *
  17446. * @type {Object<String, Node>}
  17447. */
  17448. this.outputNodes = outputNodes;
  17449. /**
  17450. * This flag can be used for type testing.
  17451. *
  17452. * @type {Boolean}
  17453. * @readonly
  17454. * @default true
  17455. */
  17456. this.isMRTNode = true;
  17457. }
  17458. /**
  17459. * Returns `true` if the MRT node has an output with the given name.
  17460. *
  17461. * @param {String} name - The name of the output.
  17462. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  17463. */
  17464. has( name ) {
  17465. return this.outputNodes[ name ] !== undefined;
  17466. }
  17467. /**
  17468. * Returns the output node for the given name.
  17469. *
  17470. * @param {String} name - The name of the output.
  17471. * @return {Node} The output node.
  17472. */
  17473. get( name ) {
  17474. return this.outputNodes[ name ];
  17475. }
  17476. /**
  17477. * Merges the outputs of the given MRT node with the outputs of this node.
  17478. *
  17479. * @param {MRTNode} mrtNode - The MRT to merge.
  17480. * @return {MRTNode} A new MRT node with merged outputs..
  17481. */
  17482. merge( mrtNode ) {
  17483. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  17484. return mrt( outputs );
  17485. }
  17486. setup( builder ) {
  17487. const outputNodes = this.outputNodes;
  17488. const mrt = builder.renderer.getRenderTarget();
  17489. const members = [];
  17490. const textures = mrt.textures;
  17491. for ( const name in outputNodes ) {
  17492. const index = getTextureIndex( textures, name );
  17493. members[ index ] = vec4( outputNodes[ name ] );
  17494. }
  17495. this.members = members;
  17496. return super.setup( builder );
  17497. }
  17498. }
  17499. /**
  17500. * TSL function for creating a MRT node.
  17501. *
  17502. * @function
  17503. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  17504. * @returns {MRTNode}
  17505. */
  17506. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  17507. /** @module Hash **/
  17508. /**
  17509. * Generates a hash value in the range `[0, 1]` from the given seed.
  17510. *
  17511. * @method
  17512. * @param {Node<float>} seed - The seed.
  17513. * @return {Node<float>} The hash value.
  17514. */
  17515. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  17516. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  17517. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  17518. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  17519. const result = word.shiftRight( 22 ).bitXor( word );
  17520. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  17521. } );
  17522. /** @module MathUtils **/
  17523. /**
  17524. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  17525. * The corners are mapped to `0` and the center to `1`.
  17526. * Reference: {@link https://iquilezles.org/articles/functions/}.
  17527. *
  17528. * @method
  17529. * @param {Node<float>} x - The value to remap.
  17530. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  17531. * @return {Node<float>} The remapped value.
  17532. */
  17533. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  17534. /**
  17535. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  17536. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  17537. * Reference: {@link https://iquilezles.org/articles/functions/}.
  17538. *
  17539. * @method
  17540. * @param {Node<float>} x - The value to remap.
  17541. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  17542. * @return {Node<float>} The remapped value.
  17543. */
  17544. 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 ) );
  17545. /**
  17546. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  17547. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  17548. * Reference: {@link https://iquilezles.org/articles/functions/}.
  17549. *
  17550. * @method
  17551. * @param {Node<float>} x - The value to remap.
  17552. * @param {Node<float>} a - First control parameter.
  17553. * @param {Node<float>} b - Second control parameter.
  17554. * @return {Node<float>} The remapped value.
  17555. */
  17556. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  17557. /**
  17558. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  17559. * Reference: {@link https://iquilezles.org/articles/functions/}.
  17560. *
  17561. * @method
  17562. * @param {Node<float>} x - The value to compute the sin for.
  17563. * @param {Node<float>} k - Controls the amount of bounces.
  17564. * @return {Node<float>} The result value.
  17565. */
  17566. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  17567. // https://github.com/cabbibo/glsl-tri-noise-3d
  17568. /** @module TriNoise3D **/
  17569. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  17570. return x.fract().sub( .5 ).abs();
  17571. } ).setLayout( {
  17572. name: 'tri',
  17573. type: 'float',
  17574. inputs: [
  17575. { name: 'x', type: 'float' }
  17576. ]
  17577. } );
  17578. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  17579. 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. ) ) ) ) );
  17580. } ).setLayout( {
  17581. name: 'tri3',
  17582. type: 'vec3',
  17583. inputs: [
  17584. { name: 'p', type: 'vec3' }
  17585. ]
  17586. } );
  17587. /**
  17588. * Generates a noise value from the given position, speed and time parameters.
  17589. *
  17590. * @method
  17591. * @param {Node<vec3>} position - The position.
  17592. * @param {Node<float>} speed - The speed.
  17593. * @param {Node<float>} time - The time.
  17594. * @return {Node<float>} The generated noise.
  17595. */
  17596. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  17597. const p = vec3( position ).toVar();
  17598. const z = float( 1.4 ).toVar();
  17599. const rz = float( 0.0 ).toVar();
  17600. const bp = vec3( p ).toVar();
  17601. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  17602. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  17603. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  17604. bp.mulAssign( 1.8 );
  17605. z.mulAssign( 1.5 );
  17606. p.mulAssign( 1.2 );
  17607. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  17608. rz.addAssign( t.div( z ) );
  17609. bp.addAssign( 0.14 );
  17610. } );
  17611. return rz;
  17612. } ).setLayout( {
  17613. name: 'triNoise3D',
  17614. type: 'float',
  17615. inputs: [
  17616. { name: 'position', type: 'vec3' },
  17617. { name: 'speed', type: 'float' },
  17618. { name: 'time', type: 'float' }
  17619. ]
  17620. } );
  17621. /** @module FunctionOverloadingNode **/
  17622. /**
  17623. * This class allows to define multiple overloaded versions
  17624. * of the same function. Depending on the parameters of the function
  17625. * call, the node picks the best-fit overloaded version.
  17626. *
  17627. * @augments Node
  17628. */
  17629. class FunctionOverloadingNode extends Node {
  17630. static get type() {
  17631. return 'FunctionOverloadingNode';
  17632. }
  17633. /**
  17634. * Constructs a new function overloading node.
  17635. *
  17636. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  17637. * @param {...Node} parametersNodes - A list of parameter nodes.
  17638. */
  17639. constructor( functionNodes = [], ...parametersNodes ) {
  17640. super();
  17641. /**
  17642. * Array of `Fn` function definitions.
  17643. *
  17644. * @type {Array<Function>}
  17645. */
  17646. this.functionNodes = functionNodes;
  17647. /**
  17648. * A list of parameter nodes.
  17649. *
  17650. * @type {Array<Node>}
  17651. */
  17652. this.parametersNodes = parametersNodes;
  17653. /**
  17654. * The selected overloaded function call.
  17655. *
  17656. * @private
  17657. * @type {ShaderCallNodeInternal}
  17658. */
  17659. this._candidateFnCall = null;
  17660. /**
  17661. * This node is marked as global.
  17662. *
  17663. * @type {Boolean}
  17664. * @default true
  17665. */
  17666. this.global = true;
  17667. }
  17668. /**
  17669. * This method is overwritten since the node type is inferred from
  17670. * the function's return type.
  17671. *
  17672. * @param {NodeBuilder} builder - The current node builder.
  17673. * @return {String} The node type.
  17674. */
  17675. getNodeType() {
  17676. return this.functionNodes[ 0 ].shaderNode.layout.type;
  17677. }
  17678. setup( builder ) {
  17679. const params = this.parametersNodes;
  17680. let candidateFnCall = this._candidateFnCall;
  17681. if ( candidateFnCall === null ) {
  17682. let candidateFn = null;
  17683. let candidateScore = - 1;
  17684. for ( const functionNode of this.functionNodes ) {
  17685. const shaderNode = functionNode.shaderNode;
  17686. const layout = shaderNode.layout;
  17687. if ( layout === null ) {
  17688. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  17689. }
  17690. const inputs = layout.inputs;
  17691. if ( params.length === inputs.length ) {
  17692. let score = 0;
  17693. for ( let i = 0; i < params.length; i ++ ) {
  17694. const param = params[ i ];
  17695. const input = inputs[ i ];
  17696. if ( param.getNodeType( builder ) === input.type ) {
  17697. score ++;
  17698. } else {
  17699. score = 0;
  17700. }
  17701. }
  17702. if ( score > candidateScore ) {
  17703. candidateFn = functionNode;
  17704. candidateScore = score;
  17705. }
  17706. }
  17707. }
  17708. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  17709. }
  17710. return candidateFnCall;
  17711. }
  17712. }
  17713. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  17714. /**
  17715. * TSL function for creating a function overloading node.
  17716. *
  17717. * @function
  17718. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  17719. * @returns {FunctionOverloadingNode}
  17720. */
  17721. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  17722. /** @module Timer **/
  17723. /**
  17724. * Represents the elapsed time in seconds.
  17725. *
  17726. * @type {UniformNode<float>}
  17727. */
  17728. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  17729. /**
  17730. * Represents the delta time in seconds.
  17731. *
  17732. * @type {UniformNode<float>}
  17733. */
  17734. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  17735. /**
  17736. * Represents the current frame ID.
  17737. *
  17738. * @type {UniformNode<uint>}
  17739. */
  17740. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  17741. // Deprecated
  17742. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  17743. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  17744. return time.mul( timeScale );
  17745. };
  17746. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  17747. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  17748. return time.mul( timeScale );
  17749. };
  17750. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  17751. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  17752. return deltaTime.mul( timeScale );
  17753. };
  17754. /** @module Oscillators **/
  17755. /**
  17756. * Generates a sine wave oscillation based on a timer.
  17757. *
  17758. * @method
  17759. * @param {Node<float>} t - The timer to generate the oscillation with.
  17760. * @return {Node<float>} The oscillation node.
  17761. */
  17762. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  17763. /**
  17764. * Generates a square wave oscillation based on a timer.
  17765. *
  17766. * @method
  17767. * @param {Node<float>} t - The timer to generate the oscillation with.
  17768. * @return {Node<float>} The oscillation node.
  17769. */
  17770. const oscSquare = ( t = time ) => t.fract().round();
  17771. /**
  17772. * Generates a triangle wave oscillation based on a timer.
  17773. *
  17774. * @method
  17775. * @param {Node<float>} t - The timer to generate the oscillation with.
  17776. * @return {Node<float>} The oscillation node.
  17777. */
  17778. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  17779. /**
  17780. * Generates a sawtooth wave oscillation based on a timer.
  17781. *
  17782. * @method
  17783. * @param {Node<float>} t - The timer to generate the oscillation with.
  17784. * @return {Node<float>} The oscillation node.
  17785. */
  17786. const oscSawtooth = ( t = time ) => t.fract();
  17787. /** @module UVUtils **/
  17788. /**
  17789. * Rotates the given uv coordinates around a center point
  17790. *
  17791. * @method
  17792. * @param {Node<vec2>} uv - The uv coordinates.
  17793. * @param {Node<float>} rotation - The rotation defined in radians.
  17794. * @param {Node<vec2>} center - The center of rotation
  17795. * @return {Node<vec2>} The rotated uv coordinates.
  17796. */
  17797. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  17798. return rotate( uv.sub( center ), rotation ).add( center );
  17799. } );
  17800. /**
  17801. * Applies a spherical warping effect to the given uv coordinates.
  17802. *
  17803. * @method
  17804. * @param {Node<vec2>} uv - The uv coordinates.
  17805. * @param {Node<float>} strength - The strength of the effect.
  17806. * @param {Node<vec2>} center - The center point
  17807. * @return {Node<vec2>} The updated uv coordinates.
  17808. */
  17809. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  17810. const delta = uv.sub( center );
  17811. const delta2 = delta.dot( delta );
  17812. const delta4 = delta2.mul( delta2 );
  17813. const deltaOffset = delta4.mul( strength );
  17814. return uv.add( delta.mul( deltaOffset ) );
  17815. } );
  17816. /** @module SpriteUtils **/
  17817. /**
  17818. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  17819. * oriented always towards the camera.
  17820. *
  17821. * ```js
  17822. * material.vertexNode = billboarding();
  17823. * ```
  17824. *
  17825. * @method
  17826. * @param {Object} config - The configuration object.
  17827. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  17828. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  17829. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  17830. * @return {Node<vec3>} The updated vertex position in clip space.
  17831. */
  17832. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  17833. let worldMatrix;
  17834. if ( position !== null ) {
  17835. worldMatrix = modelWorldMatrix.toVar();
  17836. worldMatrix[ 3 ][ 0 ] = position.x;
  17837. worldMatrix[ 3 ][ 1 ] = position.y;
  17838. worldMatrix[ 3 ][ 2 ] = position.z;
  17839. } else {
  17840. worldMatrix = modelWorldMatrix;
  17841. }
  17842. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  17843. if ( defined( horizontal ) ) {
  17844. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  17845. modelViewMatrix[ 0 ][ 1 ] = 0;
  17846. modelViewMatrix[ 0 ][ 2 ] = 0;
  17847. }
  17848. if ( defined( vertical ) ) {
  17849. modelViewMatrix[ 1 ][ 0 ] = 0;
  17850. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  17851. modelViewMatrix[ 1 ][ 2 ] = 0;
  17852. }
  17853. modelViewMatrix[ 2 ][ 0 ] = 0;
  17854. modelViewMatrix[ 2 ][ 1 ] = 0;
  17855. modelViewMatrix[ 2 ][ 2 ] = 1;
  17856. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  17857. } );
  17858. /** @module ViewportUtils **/
  17859. /**
  17860. * A special version of a screen uv function that involves a depth comparison
  17861. * when computing the final uvs. The function mitigates visual errors when
  17862. * using viewport texture nodes for refraction purposes. Without this function
  17863. * objects in front of a refractive surface might appear on the refractive surface
  17864. * which is incorrect.
  17865. *
  17866. * @method
  17867. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  17868. * @return {Node<vec2>} The update uv coordinates.
  17869. */
  17870. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  17871. const depth = linearDepth();
  17872. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  17873. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  17874. return finalUV;
  17875. } );
  17876. /** @module SpriteSheetUVNode **/
  17877. /**
  17878. * Can be used to compute texture coordinates for animated sprite sheets.
  17879. *
  17880. * ```js
  17881. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  17882. *
  17883. * material.colorNode = texture( spriteSheet, uvNode );
  17884. * ```
  17885. *
  17886. * @augments Node
  17887. */
  17888. class SpriteSheetUVNode extends Node {
  17889. static get type() {
  17890. return 'SpriteSheetUVNode';
  17891. }
  17892. /**
  17893. * Constructs a new sprite sheet uv node.
  17894. *
  17895. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  17896. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  17897. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  17898. */
  17899. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  17900. super( 'vec2' );
  17901. /**
  17902. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  17903. *
  17904. * @type {Node<vec2>}
  17905. */
  17906. this.countNode = countNode;
  17907. /**
  17908. * The uv node.
  17909. *
  17910. * @type {Node<vec2>}
  17911. */
  17912. this.uvNode = uvNode;
  17913. /**
  17914. * The node that defines the current frame/sprite.
  17915. *
  17916. * @type {Node<float>}
  17917. */
  17918. this.frameNode = frameNode;
  17919. }
  17920. setup() {
  17921. const { frameNode, uvNode, countNode } = this;
  17922. const { width, height } = countNode;
  17923. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  17924. const column = frameNum.mod( width );
  17925. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  17926. const scale = countNode.reciprocal();
  17927. const uvFrameOffset = vec2( column, row );
  17928. return uvNode.add( uvFrameOffset ).mul( scale );
  17929. }
  17930. }
  17931. /**
  17932. * TSL function for creating a sprite sheet uv node.
  17933. *
  17934. * @function
  17935. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  17936. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  17937. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  17938. * @returns {SpriteSheetUVNode}
  17939. */
  17940. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  17941. /** @module TriplanarTexturesNode **/
  17942. /**
  17943. * Can be used for triplanar texture mapping.
  17944. *
  17945. * ```js
  17946. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  17947. * ```
  17948. *
  17949. * @augments Node
  17950. */
  17951. class TriplanarTexturesNode extends Node {
  17952. static get type() {
  17953. return 'TriplanarTexturesNode';
  17954. }
  17955. /**
  17956. * Constructs a new triplanar textures node.
  17957. *
  17958. * @param {Node} textureXNode - First texture node.
  17959. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  17960. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  17961. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  17962. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  17963. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  17964. */
  17965. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  17966. super( 'vec4' );
  17967. /**
  17968. * First texture node.
  17969. *
  17970. * @type {Node}
  17971. */
  17972. this.textureXNode = textureXNode;
  17973. /**
  17974. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  17975. *
  17976. * @type {Node}
  17977. * @default null
  17978. */
  17979. this.textureYNode = textureYNode;
  17980. /**
  17981. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  17982. *
  17983. * @type {Node}
  17984. * @default null
  17985. */
  17986. this.textureZNode = textureZNode;
  17987. /**
  17988. * The scale node.
  17989. *
  17990. * @type {Node<float>}
  17991. * @default float(1)
  17992. */
  17993. this.scaleNode = scaleNode;
  17994. /**
  17995. * Vertex positions in local space.
  17996. *
  17997. * @type {Node<vec3>}
  17998. * @default positionLocal
  17999. */
  18000. this.positionNode = positionNode;
  18001. /**
  18002. * Normals in local space.
  18003. *
  18004. * @type {Node<vec3>}
  18005. * @default normalLocal
  18006. */
  18007. this.normalNode = normalNode;
  18008. }
  18009. setup() {
  18010. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  18011. // Ref: https://github.com/keijiro/StandardTriplanar
  18012. // Blending factor of triplanar mapping
  18013. let bf = normalNode.abs().normalize();
  18014. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  18015. // Triplanar mapping
  18016. const tx = positionNode.yz.mul( scaleNode );
  18017. const ty = positionNode.zx.mul( scaleNode );
  18018. const tz = positionNode.xy.mul( scaleNode );
  18019. // Base color
  18020. const textureX = textureXNode.value;
  18021. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  18022. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  18023. const cx = texture( textureX, tx ).mul( bf.x );
  18024. const cy = texture( textureY, ty ).mul( bf.y );
  18025. const cz = texture( textureZ, tz ).mul( bf.z );
  18026. return add( cx, cy, cz );
  18027. }
  18028. }
  18029. /**
  18030. * TSL function for creating a triplanar textures node.
  18031. *
  18032. * @function
  18033. * @param {Node} textureXNode - First texture node.
  18034. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  18035. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  18036. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  18037. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  18038. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  18039. * @returns {TriplanarTexturesNode}
  18040. */
  18041. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  18042. /**
  18043. * TSL function for creating a triplanar textures node.
  18044. *
  18045. * @function
  18046. * @param {Node} textureXNode - First texture node.
  18047. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  18048. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  18049. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  18050. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  18051. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  18052. * @returns {TriplanarTexturesNode}
  18053. */
  18054. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  18055. /** @module ReflectorNode **/
  18056. const _reflectorPlane = new Plane();
  18057. const _normal = new Vector3();
  18058. const _reflectorWorldPosition = new Vector3();
  18059. const _cameraWorldPosition = new Vector3();
  18060. const _rotationMatrix = new Matrix4();
  18061. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  18062. const clipPlane = new Vector4();
  18063. const _view = new Vector3();
  18064. const _target = new Vector3();
  18065. const _q = new Vector4();
  18066. const _size$2 = new Vector2();
  18067. const _defaultRT = new RenderTarget();
  18068. const _defaultUV = screenUV.flipX();
  18069. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  18070. let _inReflector = false;
  18071. /**
  18072. * This node can be used to implement mirror-like flat reflective surfaces.
  18073. *
  18074. * ```js
  18075. * const groundReflector = reflector();
  18076. * material.colorNode = groundReflector;
  18077. *
  18078. * const plane = new Mesh( geometry, material );
  18079. * plane.add( groundReflector.target );
  18080. * ```
  18081. *
  18082. * @augments module:TextureNode~TextureNode
  18083. */
  18084. class ReflectorNode extends TextureNode {
  18085. static get type() {
  18086. return 'ReflectorNode';
  18087. }
  18088. /**
  18089. * Constructs a new reflector node.
  18090. *
  18091. * @param {Object} [parameters={}] - An object holding configuration parameters.
  18092. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  18093. * @param {Number} [parameters.resolution=1] - The resolution scale.
  18094. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  18095. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  18096. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  18097. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  18098. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  18099. */
  18100. constructor( parameters = {} ) {
  18101. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  18102. /**
  18103. * A reference to the internal reflector base node which holds the actual implementation.
  18104. *
  18105. * @private
  18106. * @type {ReflectorBaseNode?}
  18107. * @default null
  18108. */
  18109. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  18110. /**
  18111. * A reference to the internal depth node.
  18112. *
  18113. * @private
  18114. * @type {Node?}
  18115. * @default null
  18116. */
  18117. this._depthNode = null;
  18118. this.setUpdateMatrix( false );
  18119. }
  18120. /**
  18121. * A reference to the internal reflector node.
  18122. *
  18123. * @type {ReflectorBaseNode}
  18124. */
  18125. get reflector() {
  18126. return this._reflectorBaseNode;
  18127. }
  18128. /**
  18129. * A reference to 3D object the reflector is linked to.
  18130. *
  18131. * @type {Object3D}
  18132. */
  18133. get target() {
  18134. return this._reflectorBaseNode.target;
  18135. }
  18136. /**
  18137. * Returns a node representing the mirror's depth. That can be used
  18138. * to implement more advanced reflection effects like distance attenuation.
  18139. *
  18140. * @return {Node} The depth node.
  18141. */
  18142. getDepthNode() {
  18143. if ( this._depthNode === null ) {
  18144. if ( this._reflectorBaseNode.depth !== true ) {
  18145. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  18146. }
  18147. this._depthNode = nodeObject( new ReflectorNode( {
  18148. defaultTexture: _defaultRT.depthTexture,
  18149. reflector: this._reflectorBaseNode
  18150. } ) );
  18151. }
  18152. return this._depthNode;
  18153. }
  18154. setup( builder ) {
  18155. // ignore if used in post-processing
  18156. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  18157. return super.setup( builder );
  18158. }
  18159. clone() {
  18160. const texture = new this.constructor( this.reflectorNode );
  18161. texture._reflectorBaseNode = this._reflectorBaseNode;
  18162. return texture;
  18163. }
  18164. }
  18165. /**
  18166. * Holds the actual implementation of the reflector.
  18167. *
  18168. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  18169. * in `ReflectorNode`, see #29619.
  18170. *
  18171. * @private
  18172. * @augments Node
  18173. */
  18174. class ReflectorBaseNode extends Node {
  18175. static get type() {
  18176. return 'ReflectorBaseNode';
  18177. }
  18178. /**
  18179. * Constructs a new reflector base node.
  18180. *
  18181. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  18182. * @param {Object} [parameters={}] - An object holding configuration parameters.
  18183. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  18184. * @param {Number} [parameters.resolution=1] - The resolution scale.
  18185. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  18186. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  18187. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  18188. */
  18189. constructor( textureNode, parameters = {} ) {
  18190. super();
  18191. const {
  18192. target = new Object3D(),
  18193. resolution = 1,
  18194. generateMipmaps = false,
  18195. bounces = true,
  18196. depth = false
  18197. } = parameters;
  18198. /**
  18199. * Represents the rendered reflections as a texture node.
  18200. *
  18201. * @type {TextureNode}
  18202. */
  18203. this.textureNode = textureNode;
  18204. /**
  18205. * The 3D object the reflector is linked to.
  18206. *
  18207. * @type {Object3D}
  18208. * @default {new Object3D()}
  18209. */
  18210. this.target = target;
  18211. /**
  18212. * The resolution scale.
  18213. *
  18214. * @type {Number}
  18215. * @default {1}
  18216. */
  18217. this.resolution = resolution;
  18218. /**
  18219. * Whether mipmaps should be generated or not.
  18220. *
  18221. * @type {Boolean}
  18222. * @default {false}
  18223. */
  18224. this.generateMipmaps = generateMipmaps;
  18225. /**
  18226. * Whether reflectors can render other reflector nodes or not.
  18227. *
  18228. * @type {Boolean}
  18229. * @default {true}
  18230. */
  18231. this.bounces = bounces;
  18232. /**
  18233. * Whether depth data should be generated or not.
  18234. *
  18235. * @type {Boolean}
  18236. * @default {false}
  18237. */
  18238. this.depth = depth;
  18239. /**
  18240. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  18241. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  18242. *
  18243. * @type {String}
  18244. * @default 'render'
  18245. */
  18246. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  18247. /**
  18248. * Weak map for managing virtual cameras.
  18249. *
  18250. * @type {WeakMap<Camera, Camera>}
  18251. */
  18252. this.virtualCameras = new WeakMap();
  18253. /**
  18254. * Weak map for managing render targets.
  18255. *
  18256. * @type {WeakMap<Camera, RenderTarget>}
  18257. */
  18258. this.renderTargets = new WeakMap();
  18259. }
  18260. /**
  18261. * Updates the resolution of the internal render target.
  18262. *
  18263. * @private
  18264. * @param {RenderTarget} renderTarget - The render target to resize.
  18265. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  18266. */
  18267. _updateResolution( renderTarget, renderer ) {
  18268. const resolution = this.resolution;
  18269. renderer.getDrawingBufferSize( _size$2 );
  18270. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  18271. }
  18272. setup( builder ) {
  18273. this._updateResolution( _defaultRT, builder.renderer );
  18274. return super.setup( builder );
  18275. }
  18276. /**
  18277. * Returns a virtual camera for the given camera. The virtual camera is used to
  18278. * render the scene from the reflector's view so correct reflections can be produced.
  18279. *
  18280. * @param {Camera} camera - The scene's camera.
  18281. * @return {Camera} The corresponding virtual camera.
  18282. */
  18283. getVirtualCamera( camera ) {
  18284. let virtualCamera = this.virtualCameras.get( camera );
  18285. if ( virtualCamera === undefined ) {
  18286. virtualCamera = camera.clone();
  18287. this.virtualCameras.set( camera, virtualCamera );
  18288. }
  18289. return virtualCamera;
  18290. }
  18291. /**
  18292. * Returns a render target for the given camera. The reflections are rendered
  18293. * into this render target.
  18294. *
  18295. * @param {Camera} camera - The scene's camera.
  18296. * @return {RenderTarget} The render target.
  18297. */
  18298. getRenderTarget( camera ) {
  18299. let renderTarget = this.renderTargets.get( camera );
  18300. if ( renderTarget === undefined ) {
  18301. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  18302. if ( this.generateMipmaps === true ) {
  18303. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  18304. renderTarget.texture.generateMipmaps = true;
  18305. }
  18306. if ( this.depth === true ) {
  18307. renderTarget.depthTexture = new DepthTexture();
  18308. }
  18309. this.renderTargets.set( camera, renderTarget );
  18310. }
  18311. return renderTarget;
  18312. }
  18313. updateBefore( frame ) {
  18314. if ( this.bounces === false && _inReflector ) return;
  18315. _inReflector = true;
  18316. const { scene, camera, renderer, material } = frame;
  18317. const { target } = this;
  18318. const virtualCamera = this.getVirtualCamera( camera );
  18319. const renderTarget = this.getRenderTarget( virtualCamera );
  18320. renderer.getDrawingBufferSize( _size$2 );
  18321. this._updateResolution( renderTarget, renderer );
  18322. //
  18323. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  18324. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  18325. _rotationMatrix.extractRotation( target.matrixWorld );
  18326. _normal.set( 0, 0, 1 );
  18327. _normal.applyMatrix4( _rotationMatrix );
  18328. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  18329. // Avoid rendering when reflector is facing away
  18330. if ( _view.dot( _normal ) > 0 ) return;
  18331. _view.reflect( _normal ).negate();
  18332. _view.add( _reflectorWorldPosition );
  18333. _rotationMatrix.extractRotation( camera.matrixWorld );
  18334. _lookAtPosition.set( 0, 0, - 1 );
  18335. _lookAtPosition.applyMatrix4( _rotationMatrix );
  18336. _lookAtPosition.add( _cameraWorldPosition );
  18337. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  18338. _target.reflect( _normal ).negate();
  18339. _target.add( _reflectorWorldPosition );
  18340. //
  18341. virtualCamera.coordinateSystem = camera.coordinateSystem;
  18342. virtualCamera.position.copy( _view );
  18343. virtualCamera.up.set( 0, 1, 0 );
  18344. virtualCamera.up.applyMatrix4( _rotationMatrix );
  18345. virtualCamera.up.reflect( _normal );
  18346. virtualCamera.lookAt( _target );
  18347. virtualCamera.near = camera.near;
  18348. virtualCamera.far = camera.far;
  18349. virtualCamera.updateMatrixWorld();
  18350. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  18351. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  18352. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  18353. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  18354. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  18355. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  18356. const projectionMatrix = virtualCamera.projectionMatrix;
  18357. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  18358. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  18359. _q.z = - 1.0;
  18360. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  18361. // Calculate the scaled plane vector
  18362. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  18363. const clipBias = 0;
  18364. // Replacing the third row of the projection matrix
  18365. projectionMatrix.elements[ 2 ] = clipPlane.x;
  18366. projectionMatrix.elements[ 6 ] = clipPlane.y;
  18367. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  18368. projectionMatrix.elements[ 14 ] = clipPlane.w;
  18369. //
  18370. this.textureNode.value = renderTarget.texture;
  18371. if ( this.depth === true ) {
  18372. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  18373. }
  18374. material.visible = false;
  18375. const currentRenderTarget = renderer.getRenderTarget();
  18376. const currentMRT = renderer.getMRT();
  18377. renderer.setMRT( null );
  18378. renderer.setRenderTarget( renderTarget );
  18379. renderer.render( scene, virtualCamera );
  18380. renderer.setMRT( currentMRT );
  18381. renderer.setRenderTarget( currentRenderTarget );
  18382. material.visible = true;
  18383. _inReflector = false;
  18384. }
  18385. }
  18386. /**
  18387. * TSL function for creating a reflector node.
  18388. *
  18389. * @function
  18390. * @param {Object} [parameters={}] - An object holding configuration parameters.
  18391. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  18392. * @param {Number} [parameters.resolution=1] - The resolution scale.
  18393. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  18394. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  18395. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  18396. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  18397. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  18398. * @returns {ReflectorNode}
  18399. */
  18400. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  18401. // Helper for passes that need to fill the viewport with a single quad.
  18402. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  18403. // https://github.com/mrdoob/three.js/pull/21358
  18404. class QuadGeometry extends BufferGeometry {
  18405. constructor( flipY = false ) {
  18406. super();
  18407. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  18408. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  18409. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  18410. }
  18411. }
  18412. const _geometry = /*@__PURE__*/ new QuadGeometry();
  18413. class QuadMesh extends Mesh {
  18414. constructor( material = null ) {
  18415. super( _geometry, material );
  18416. this.camera = _camera;
  18417. this.isQuadMesh = true;
  18418. }
  18419. renderAsync( renderer ) {
  18420. return renderer.renderAsync( this, _camera );
  18421. }
  18422. render( renderer ) {
  18423. renderer.render( this, _camera );
  18424. }
  18425. }
  18426. /** @module RTTNode **/
  18427. const _size$1 = /*@__PURE__*/ new Vector2();
  18428. /**
  18429. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  18430. * This module is especially relevant in context of post processing where certain nodes require
  18431. * texture input for their effects. With the helper function `convertToTexture()` which is based
  18432. * on this module, the node system can automatically ensure texture input if required.
  18433. *
  18434. * @augments module:TextureNode~TextureNode
  18435. */
  18436. class RTTNode extends TextureNode {
  18437. static get type() {
  18438. return 'RTTNode';
  18439. }
  18440. /**
  18441. * Constructs a new RTT node.
  18442. *
  18443. * @param {Node} node - The node to render a texture with.
  18444. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  18445. * @param {Number?} [height=null] - The height of the internal render target.
  18446. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  18447. */
  18448. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  18449. const renderTarget = new RenderTarget( width, height, options );
  18450. super( renderTarget.texture, uv() );
  18451. /**
  18452. * The node to render a texture with.
  18453. *
  18454. * @type {Node}
  18455. */
  18456. this.node = node;
  18457. /**
  18458. * The width of the internal render target.
  18459. * If not width is applied, the render target is automatically resized.
  18460. *
  18461. * @type {Number?}
  18462. * @default null
  18463. */
  18464. this.width = width;
  18465. /**
  18466. * The height of the internal render target.
  18467. *
  18468. * @type {Number?}
  18469. * @default null
  18470. */
  18471. this.height = height;
  18472. /**
  18473. * The pixel ratio
  18474. *
  18475. * @type {Number}
  18476. * @default 1
  18477. */
  18478. this.pixelRatio = 1;
  18479. /**
  18480. * The render target
  18481. *
  18482. * @type {RenderTarget}
  18483. */
  18484. this.renderTarget = renderTarget;
  18485. /**
  18486. * Whether the texture requires an update or not.
  18487. *
  18488. * @type {Boolean}
  18489. * @default true
  18490. */
  18491. this.textureNeedsUpdate = true;
  18492. /**
  18493. * Whether the texture should automatically be updated or not.
  18494. *
  18495. * @type {Boolean}
  18496. * @default true
  18497. */
  18498. this.autoUpdate = true;
  18499. /**
  18500. * The node which is used with the quad mesh for RTT.
  18501. *
  18502. * @private
  18503. * @type {Node}
  18504. * @default null
  18505. */
  18506. this._rttNode = null;
  18507. /**
  18508. * The internal quad mesh for RTT.
  18509. *
  18510. * @private
  18511. * @type {QuadMesh}
  18512. */
  18513. this._quadMesh = new QuadMesh( new NodeMaterial() );
  18514. /**
  18515. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  18516. * the texture once per render in its {@link RTTNode#updateBefore} method.
  18517. *
  18518. * @type {String}
  18519. * @default 'render'
  18520. */
  18521. this.updateBeforeType = NodeUpdateType.RENDER;
  18522. }
  18523. /**
  18524. * Whether the internal render target should automatically be resized or not.
  18525. *
  18526. * @type {Boolean}
  18527. * @readonly
  18528. * @default true
  18529. */
  18530. get autoSize() {
  18531. return this.width === null;
  18532. }
  18533. setup( builder ) {
  18534. this._rttNode = this.node.context( builder.getSharedContext() );
  18535. this._quadMesh.material.name = 'RTT';
  18536. this._quadMesh.material.needsUpdate = true;
  18537. return super.setup( builder );
  18538. }
  18539. /**
  18540. * Sets the size of the internal render target
  18541. *
  18542. * @param {Number} width - The width to set.
  18543. * @param {Number} height - The width to set.
  18544. */
  18545. setSize( width, height ) {
  18546. this.width = width;
  18547. this.height = height;
  18548. const effectiveWidth = width * this.pixelRatio;
  18549. const effectiveHeight = height * this.pixelRatio;
  18550. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  18551. this.textureNeedsUpdate = true;
  18552. }
  18553. /**
  18554. * Sets the pixel ratio. This will also resize the render target.
  18555. *
  18556. * @param {Number} pixelRatio - The pixel ratio to set.
  18557. */
  18558. setPixelRatio( pixelRatio ) {
  18559. this.pixelRatio = pixelRatio;
  18560. this.setSize( this.width, this.height );
  18561. }
  18562. updateBefore( { renderer } ) {
  18563. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  18564. this.textureNeedsUpdate = false;
  18565. //
  18566. if ( this.autoSize === true ) {
  18567. this.pixelRatio = renderer.getPixelRatio();
  18568. const size = renderer.getSize( _size$1 );
  18569. this.setSize( size.width, size.height );
  18570. }
  18571. //
  18572. this._quadMesh.material.fragmentNode = this._rttNode;
  18573. //
  18574. const currentRenderTarget = renderer.getRenderTarget();
  18575. renderer.setRenderTarget( this.renderTarget );
  18576. this._quadMesh.render( renderer );
  18577. renderer.setRenderTarget( currentRenderTarget );
  18578. }
  18579. clone() {
  18580. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  18581. newNode.sampler = this.sampler;
  18582. newNode.referenceNode = this;
  18583. return newNode;
  18584. }
  18585. }
  18586. /**
  18587. * TSL function for creating a RTT node.
  18588. *
  18589. * @function
  18590. * @param {Node} node - The node to render a texture with.
  18591. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  18592. * @param {Number?} [height=null] - The height of the internal render target.
  18593. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  18594. * @returns {RTTNode}
  18595. */
  18596. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  18597. /**
  18598. * TSL function for converting nodes to textures nodes.
  18599. *
  18600. * @function
  18601. * @param {Node} node - The node to render a texture with.
  18602. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  18603. * @param {Number?} [height=null] - The height of the internal render target.
  18604. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  18605. * @returns {RTTNode}
  18606. */
  18607. const convertToTexture = ( node, ...params ) => {
  18608. if ( node.isTextureNode ) return node;
  18609. if ( node.isPassNode ) return node.getTextureNode();
  18610. return rtt( node, ...params );
  18611. };
  18612. /** @module PostProcessingUtils **/
  18613. /**
  18614. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  18615. * depth value and the camera's inverse projection matrix.
  18616. *
  18617. * @method
  18618. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  18619. * @param {Node<float>} depth - The fragment's depth value.
  18620. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  18621. * @return {Node<vec3>} The fragments position in view space.
  18622. */
  18623. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  18624. let clipSpacePosition;
  18625. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  18626. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  18627. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  18628. } else {
  18629. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  18630. }
  18631. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  18632. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  18633. } );
  18634. /**
  18635. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  18636. * and the camera's projection matrix
  18637. *
  18638. * @method
  18639. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  18640. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  18641. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  18642. */
  18643. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  18644. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  18645. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  18646. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  18647. } );
  18648. /**
  18649. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  18650. * target is available or if flat surface normals are required.
  18651. *
  18652. * @method
  18653. * @param {Node<vec2>} uv - The texture coordinate.
  18654. * @param {DepthTexture} depthTexture - The depth texture.
  18655. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  18656. * @return {Node<vec3>} The computed normal vector.
  18657. */
  18658. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  18659. const size = textureSize( textureLoad( depthTexture ) );
  18660. const p = ivec2( uv.mul( size ) ).toVar();
  18661. const c0 = textureLoad( depthTexture, p ).toVar();
  18662. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  18663. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  18664. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  18665. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  18666. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  18667. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  18668. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  18669. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  18670. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  18671. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  18672. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  18673. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  18674. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  18675. 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 ) ) );
  18676. 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 ) ) );
  18677. return normalize( cross( dpdx, dpdy ) );
  18678. } );
  18679. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  18680. constructor( array, itemSize, typeClass = Float32Array ) {
  18681. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  18682. super( array, itemSize );
  18683. this.isStorageInstancedBufferAttribute = true;
  18684. }
  18685. }
  18686. class StorageBufferAttribute extends BufferAttribute {
  18687. constructor( array, itemSize, typeClass = Float32Array ) {
  18688. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  18689. super( array, itemSize );
  18690. this.isStorageBufferAttribute = true;
  18691. }
  18692. }
  18693. /** @module StorageArrayElementNode **/
  18694. /**
  18695. * This class enables element access on instances of {@link StorageBufferNode}.
  18696. * In most cases, it is indirectly used when accessing elements with the
  18697. * {@link StorageBufferNode#element} method.
  18698. *
  18699. * ```js
  18700. * const position = positionStorage.element( instanceIndex );
  18701. * ```
  18702. *
  18703. * @augments ArrayElementNode
  18704. */
  18705. class StorageArrayElementNode extends ArrayElementNode {
  18706. static get type() {
  18707. return 'StorageArrayElementNode';
  18708. }
  18709. /**
  18710. * Constructs storage buffer element node.
  18711. *
  18712. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  18713. * @param {Node} indexNode - The index node that defines the element access.
  18714. */
  18715. constructor( storageBufferNode, indexNode ) {
  18716. super( storageBufferNode, indexNode );
  18717. /**
  18718. * This flag can be used for type testing.
  18719. *
  18720. * @type {Boolean}
  18721. * @readonly
  18722. * @default true
  18723. */
  18724. this.isStorageArrayElementNode = true;
  18725. }
  18726. /**
  18727. * The storage buffer node.
  18728. *
  18729. * @param {Node} value
  18730. * @type {StorageBufferNode}
  18731. */
  18732. set storageBufferNode( value ) {
  18733. this.node = value;
  18734. }
  18735. get storageBufferNode() {
  18736. return this.node;
  18737. }
  18738. setup( builder ) {
  18739. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  18740. if ( this.node.isPBO === true ) {
  18741. builder.setupPBO( this.node );
  18742. }
  18743. }
  18744. return super.setup( builder );
  18745. }
  18746. generate( builder, output ) {
  18747. let snippet;
  18748. const isAssignContext = builder.context.assign;
  18749. //
  18750. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  18751. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  18752. snippet = builder.generatePBO( this );
  18753. } else {
  18754. snippet = this.node.build( builder );
  18755. }
  18756. } else {
  18757. snippet = super.generate( builder );
  18758. }
  18759. if ( isAssignContext !== true ) {
  18760. const type = this.getNodeType( builder );
  18761. snippet = builder.format( snippet, type, output );
  18762. }
  18763. return snippet;
  18764. }
  18765. }
  18766. /**
  18767. * TSL function for creating a storage element node.
  18768. *
  18769. * @function
  18770. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  18771. * @param {Node} indexNode - The index node that defines the element access.
  18772. * @returns {StorageArrayElementNode}
  18773. */
  18774. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  18775. /** @module StorageBufferNode **/
  18776. /**
  18777. * This node is used in context of compute shaders and allows to define a
  18778. * storage buffer for data. A typical workflow is to create instances of
  18779. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  18780. * setup up a compute shader that writes into the buffers and then convert
  18781. * the storage buffers to attributes for rendering.
  18782. *
  18783. * ```js
  18784. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  18785. *
  18786. * const computeInit = Fn( () => { // the compute shader
  18787. *
  18788. * const position = positionBuffer.element( instanceIndex );
  18789. *
  18790. * // compute position data
  18791. *
  18792. * position.x = 1;
  18793. * position.y = 1;
  18794. * position.z = 1;
  18795. *
  18796. * } )().compute( particleCount );
  18797. *
  18798. * const particleMaterial = new THREE.SpriteNodeMaterial();
  18799. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18800. *
  18801. * renderer.computeAsync( computeInit );
  18802. *
  18803. * ```
  18804. *
  18805. * @augments BufferNode
  18806. */
  18807. class StorageBufferNode extends BufferNode {
  18808. static get type() {
  18809. return 'StorageBufferNode';
  18810. }
  18811. /**
  18812. * Constructs a new storage buffer node.
  18813. *
  18814. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute} value - The buffer data.
  18815. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  18816. * @param {Number} [bufferCount=0] - The buffer count.
  18817. */
  18818. constructor( value, bufferType = null, bufferCount = 0 ) {
  18819. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  18820. bufferType = getTypeFromLength( value.itemSize );
  18821. bufferCount = value.count;
  18822. }
  18823. super( value, bufferType, bufferCount );
  18824. /**
  18825. * This flag can be used for type testing.
  18826. *
  18827. * @type {Boolean}
  18828. * @readonly
  18829. * @default true
  18830. */
  18831. this.isStorageBufferNode = true;
  18832. /**
  18833. * The access type of the texture node.
  18834. *
  18835. * @type {String}
  18836. * @default 'readWrite'
  18837. */
  18838. this.access = NodeAccess.READ_WRITE;
  18839. /**
  18840. * Whether the node is atomic or not.
  18841. *
  18842. * @type {Boolean}
  18843. * @default false
  18844. */
  18845. this.isAtomic = false;
  18846. /**
  18847. * Whether the node represents a PBO or not.
  18848. * Only relevant for WebGL.
  18849. *
  18850. * @type {Boolean}
  18851. * @default false
  18852. */
  18853. this.isPBO = false;
  18854. /**
  18855. * A reference to the internal buffer attribute node.
  18856. *
  18857. * @type {BufferAttributeNode?}
  18858. * @default null
  18859. */
  18860. this._attribute = null;
  18861. /**
  18862. * A reference to the internal varying node.
  18863. *
  18864. * @type {VaryingNode?}
  18865. * @default null
  18866. */
  18867. this._varying = null;
  18868. /**
  18869. * `StorageBufferNode` sets this property to `true` by default.
  18870. *
  18871. * @type {Boolean}
  18872. * @default true
  18873. */
  18874. this.global = true;
  18875. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  18876. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  18877. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  18878. else value.isStorageBufferAttribute = true;
  18879. }
  18880. }
  18881. /**
  18882. * This method is overwritten since the buffer data might be shared
  18883. * and thus the hash should be shared as well.
  18884. *
  18885. * @param {NodeBuilder} builder - The current node builder.
  18886. * @return {String} The hash.
  18887. */
  18888. getHash( builder ) {
  18889. if ( this.bufferCount === 0 ) {
  18890. let bufferData = builder.globalCache.getData( this.value );
  18891. if ( bufferData === undefined ) {
  18892. bufferData = {
  18893. node: this
  18894. };
  18895. builder.globalCache.setData( this.value, bufferData );
  18896. }
  18897. return bufferData.node.uuid;
  18898. }
  18899. return this.uuid;
  18900. }
  18901. /**
  18902. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  18903. *
  18904. * @param {NodeBuilder} builder - The current node builder.
  18905. * @return {String} The input type.
  18906. */
  18907. getInputType( /*builder*/ ) {
  18908. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  18909. }
  18910. /**
  18911. * Enables element access with the given index node.
  18912. *
  18913. * @param {IndexNode} indexNode - The index node.
  18914. * @return {StorageArrayElementNode} A node representing the element access.
  18915. */
  18916. element( indexNode ) {
  18917. return storageElement( this, indexNode );
  18918. }
  18919. /**
  18920. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  18921. *
  18922. * @param {Boolean} value - The value so set.
  18923. * @return {StorageBufferNode} A reference to this node.
  18924. */
  18925. setPBO( value ) {
  18926. this.isPBO = value;
  18927. return this;
  18928. }
  18929. /**
  18930. * Returns the `isPBO` value.
  18931. *
  18932. * @return {Boolean} Whether the node represents a PBO or not.
  18933. */
  18934. getPBO() {
  18935. return this.isPBO;
  18936. }
  18937. /**
  18938. * Defines the node access.
  18939. *
  18940. * @param {String} value - The node access.
  18941. * @return {StorageBufferNode} A reference to this node.
  18942. */
  18943. setAccess( value ) {
  18944. this.access = value;
  18945. return this;
  18946. }
  18947. /**
  18948. * Convenience method for configuring a read-only node access.
  18949. *
  18950. * @return {StorageBufferNode} A reference to this node.
  18951. */
  18952. toReadOnly() {
  18953. return this.setAccess( NodeAccess.READ_ONLY );
  18954. }
  18955. /**
  18956. * Defines whether the node is atomic or not.
  18957. *
  18958. * @param {Boolean} value - The atomic flag.
  18959. * @return {StorageBufferNode} A reference to this node.
  18960. */
  18961. setAtomic( value ) {
  18962. this.isAtomic = value;
  18963. return this;
  18964. }
  18965. /**
  18966. * Convenience method for making this node atomic.
  18967. *
  18968. * @return {StorageBufferNode} A reference to this node.
  18969. */
  18970. toAtomic() {
  18971. return this.setAtomic( true );
  18972. }
  18973. /**
  18974. * Returns attribute data for this storage buffer node.
  18975. *
  18976. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  18977. */
  18978. getAttributeData() {
  18979. if ( this._attribute === null ) {
  18980. this._attribute = bufferAttribute( this.value );
  18981. this._varying = varying( this._attribute );
  18982. }
  18983. return {
  18984. attribute: this._attribute,
  18985. varying: this._varying
  18986. };
  18987. }
  18988. /**
  18989. * This method is overwritten since the node type from the availability of storage buffers
  18990. * and the attribute data.
  18991. *
  18992. * @param {NodeBuilder} builder - The current node builder.
  18993. * @return {String} The node type.
  18994. */
  18995. getNodeType( builder ) {
  18996. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  18997. return super.getNodeType( builder );
  18998. }
  18999. const { attribute } = this.getAttributeData();
  19000. return attribute.getNodeType( builder );
  19001. }
  19002. /**
  19003. * Generates the code snippet of the storage buffer node.
  19004. *
  19005. * @param {NodeBuilder} builder - The current node builder.
  19006. * @return {String} The generated code snippet.
  19007. */
  19008. generate( builder ) {
  19009. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  19010. return super.generate( builder );
  19011. }
  19012. const { attribute, varying } = this.getAttributeData();
  19013. const output = varying.build( builder );
  19014. builder.registerTransform( output, attribute );
  19015. return output;
  19016. }
  19017. }
  19018. /**
  19019. * TSL function for creating a storage buffer node.
  19020. *
  19021. * @function
  19022. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute} value - The buffer data.
  19023. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  19024. * @param {Number} [count=0] - The buffer count.
  19025. * @returns {StorageBufferNode}
  19026. */
  19027. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  19028. const storageObject = ( value, type, count ) => { // @deprecated, r171
  19029. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  19030. return storage( value, type, count ).setPBO( true );
  19031. };
  19032. /** @module Arrays **/
  19033. /**
  19034. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  19035. *
  19036. * @function
  19037. * @param {Number} count - The data count.
  19038. * @param {String} [type='float'] - The data type.
  19039. * @returns {StorageBufferNode}
  19040. */
  19041. const attributeArray = ( count, type = 'float' ) => {
  19042. const itemSize = getLengthFromType( type );
  19043. const buffer = new StorageBufferAttribute( count, itemSize );
  19044. const node = storage( buffer, type, count );
  19045. return node;
  19046. };
  19047. /**
  19048. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  19049. *
  19050. * @function
  19051. * @param {Number} count - The data count.
  19052. * @param {String} [type='float'] - The data type.
  19053. * @returns {StorageBufferNode}
  19054. */
  19055. const instancedArray = ( count, type = 'float' ) => {
  19056. const itemSize = getLengthFromType( type );
  19057. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  19058. const node = storage( buffer, type, count );
  19059. return node;
  19060. };
  19061. /** @module VertexColorNode **/
  19062. /**
  19063. * An attribute node for representing vertex colors.
  19064. *
  19065. * @augments module:AttributeNode~AttributeNode
  19066. */
  19067. class VertexColorNode extends AttributeNode {
  19068. static get type() {
  19069. return 'VertexColorNode';
  19070. }
  19071. /**
  19072. * Constructs a new vertex color node.
  19073. *
  19074. * @param {Number} [index=0] - The attribute index.
  19075. */
  19076. constructor( index = 0 ) {
  19077. super( null, 'vec4' );
  19078. /**
  19079. * This flag can be used for type testing.
  19080. *
  19081. * @type {Boolean}
  19082. * @readonly
  19083. * @default true
  19084. */
  19085. this.isVertexColorNode = true;
  19086. /**
  19087. * The attribute index to enable more than one sets of vertex colors.
  19088. *
  19089. * @type {Number}
  19090. * @default 0
  19091. */
  19092. this.index = index;
  19093. }
  19094. /**
  19095. * Overwrites the default implementation by honoring the attribute index.
  19096. *
  19097. * @param {NodeBuilder} builder - The current node builder.
  19098. * @return {String} The attribute name.
  19099. */
  19100. getAttributeName( /*builder*/ ) {
  19101. const index = this.index;
  19102. return 'color' + ( index > 0 ? index : '' );
  19103. }
  19104. generate( builder ) {
  19105. const attributeName = this.getAttributeName( builder );
  19106. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  19107. let result;
  19108. if ( geometryAttribute === true ) {
  19109. result = super.generate( builder );
  19110. } else {
  19111. // Vertex color fallback should be white
  19112. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  19113. }
  19114. return result;
  19115. }
  19116. serialize( data ) {
  19117. super.serialize( data );
  19118. data.index = this.index;
  19119. }
  19120. deserialize( data ) {
  19121. super.deserialize( data );
  19122. this.index = data.index;
  19123. }
  19124. }
  19125. /**
  19126. * TSL function for creating a reference node.
  19127. *
  19128. * @function
  19129. * @param {Number} index - The attribute index.
  19130. * @returns {VertexColorNode}
  19131. */
  19132. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  19133. /** @module PointUVNode **/
  19134. /**
  19135. * A node for representing the uv coordinates of points.
  19136. *
  19137. * Can only be used with a WebGL backend. In WebGPU, point
  19138. * primitives always have the size of one pixel and can thus
  19139. * can't be used as sprite-like objects that display textures.
  19140. *
  19141. * @augments Node
  19142. */
  19143. class PointUVNode extends Node {
  19144. static get type() {
  19145. return 'PointUVNode';
  19146. }
  19147. /**
  19148. * Constructs a new point uv node.
  19149. */
  19150. constructor() {
  19151. super( 'vec2' );
  19152. /**
  19153. * This flag can be used for type testing.
  19154. *
  19155. * @type {Boolean}
  19156. * @readonly
  19157. * @default true
  19158. */
  19159. this.isPointUVNode = true;
  19160. }
  19161. generate( /*builder*/ ) {
  19162. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  19163. }
  19164. }
  19165. /**
  19166. * TSL object that represents the uv coordinates of points.
  19167. *
  19168. * @type {PointUVNode}
  19169. */
  19170. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  19171. const _e1 = /*@__PURE__*/ new Euler();
  19172. const _m1 = /*@__PURE__*/ new Matrix4();
  19173. /** @module SceneNode **/
  19174. /**
  19175. * This module allows access to a collection of scene properties. The following predefined TSL objects
  19176. * are available for easier use:
  19177. *
  19178. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  19179. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  19180. * - `backgroundRotation`: A node that represents the scene's background rotation.
  19181. *
  19182. * @augments Node
  19183. */
  19184. class SceneNode extends Node {
  19185. static get type() {
  19186. return 'SceneNode';
  19187. }
  19188. /**
  19189. * Constructs a new scene node.
  19190. *
  19191. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  19192. * @param {Scene?} [scene=null] - A reference to the scene.
  19193. */
  19194. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  19195. super();
  19196. /**
  19197. * The scope defines the type of scene property that is accessed.
  19198. *
  19199. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  19200. */
  19201. this.scope = scope;
  19202. /**
  19203. * A reference to the scene that is going to be accessed.
  19204. *
  19205. * @type {Scene?}
  19206. * @default null
  19207. */
  19208. this.scene = scene;
  19209. }
  19210. /**
  19211. * Depending on the scope, the method returns a different type of node that represents
  19212. * the respective scene property.
  19213. *
  19214. * @param {NodeBuilder} builder - The current node builder.
  19215. * @return {Node} The output node.
  19216. */
  19217. setup( builder ) {
  19218. const scope = this.scope;
  19219. const scene = this.scene !== null ? this.scene : builder.scene;
  19220. let output;
  19221. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  19222. output = reference( 'backgroundBlurriness', 'float', scene );
  19223. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  19224. output = reference( 'backgroundIntensity', 'float', scene );
  19225. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  19226. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  19227. const background = scene.background;
  19228. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  19229. _e1.copy( scene.backgroundRotation );
  19230. // accommodate left-handed frame
  19231. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  19232. _m1.makeRotationFromEuler( _e1 );
  19233. } else {
  19234. _m1.identity();
  19235. }
  19236. return _m1;
  19237. } );
  19238. } else {
  19239. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  19240. }
  19241. return output;
  19242. }
  19243. }
  19244. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  19245. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  19246. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  19247. /**
  19248. * TSL object that represents the scene's background blurriness.
  19249. *
  19250. * @type {SceneNode}
  19251. */
  19252. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  19253. /**
  19254. * TSL object that represents the scene's background intensity.
  19255. *
  19256. * @type {SceneNode}
  19257. */
  19258. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  19259. /**
  19260. * TSL object that represents the scene's background rotation.
  19261. *
  19262. * @type {SceneNode}
  19263. */
  19264. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  19265. /** @module StorageTextureNode **/
  19266. /**
  19267. * This special version of a texture node can be used to
  19268. * write data into a storage texture with a compute shader.
  19269. *
  19270. * ```js
  19271. * const storageTexture = new THREE.StorageTexture( width, height );
  19272. *
  19273. * const computeTexture = Fn( ( { storageTexture } ) => {
  19274. *
  19275. * const posX = instanceIndex.modInt( width );
  19276. * const posY = instanceIndex.div( width );
  19277. * const indexUV = uvec2( posX, posY );
  19278. *
  19279. * // generate RGB values
  19280. *
  19281. * const r = 1;
  19282. * const g = 1;
  19283. * const b = 1;
  19284. *
  19285. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  19286. *
  19287. * } );
  19288. *
  19289. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  19290. * renderer.computeAsync( computeNode );
  19291. * ```
  19292. *
  19293. * This node can only be used with a WebGPU backend.
  19294. *
  19295. * @augments module:TextureNode~TextureNode
  19296. */
  19297. class StorageTextureNode extends TextureNode {
  19298. static get type() {
  19299. return 'StorageTextureNode';
  19300. }
  19301. /**
  19302. * Constructs a new storage texture node.
  19303. *
  19304. * @param {StorageTexture} value - The storage texture.
  19305. * @param {Node<vec2|vec3>} uvNode - The uv node.
  19306. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  19307. */
  19308. constructor( value, uvNode, storeNode = null ) {
  19309. super( value, uvNode );
  19310. /**
  19311. * The value node that should be stored in the texture.
  19312. *
  19313. * @type {Node?}
  19314. * @default null
  19315. */
  19316. this.storeNode = storeNode;
  19317. /**
  19318. * This flag can be used for type testing.
  19319. *
  19320. * @type {Boolean}
  19321. * @readonly
  19322. * @default true
  19323. */
  19324. this.isStorageTextureNode = true;
  19325. /**
  19326. * The access type of the texture node.
  19327. *
  19328. * @type {String}
  19329. * @default 'writeOnly'
  19330. */
  19331. this.access = NodeAccess.WRITE_ONLY;
  19332. }
  19333. /**
  19334. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  19335. *
  19336. * @param {NodeBuilder} builder - The current node builder.
  19337. * @return {String} The input type.
  19338. */
  19339. getInputType( /*builder*/ ) {
  19340. return 'storageTexture';
  19341. }
  19342. setup( builder ) {
  19343. super.setup( builder );
  19344. const properties = builder.getNodeProperties( this );
  19345. properties.storeNode = this.storeNode;
  19346. }
  19347. /**
  19348. * Defines the node access.
  19349. *
  19350. * @param {String} value - The node access.
  19351. * @return {StorageTextureNode} A reference to this node.
  19352. */
  19353. setAccess( value ) {
  19354. this.access = value;
  19355. return this;
  19356. }
  19357. /**
  19358. * Generates the code snippet of the stroge node. If no `storeNode`
  19359. * is defined, the texture node is generated as normal texture.
  19360. *
  19361. * @param {NodeBuilder} builder - The current node builder.
  19362. * @param {String} output - The current output.
  19363. * @return {String} The generated code snippet.
  19364. */
  19365. generate( builder, output ) {
  19366. let snippet;
  19367. if ( this.storeNode !== null ) {
  19368. snippet = this.generateStore( builder );
  19369. } else {
  19370. snippet = super.generate( builder, output );
  19371. }
  19372. return snippet;
  19373. }
  19374. /**
  19375. * Convenience method for configuring a read/write node access.
  19376. *
  19377. * @return {StorageTextureNode} A reference to this node.
  19378. */
  19379. toReadWrite() {
  19380. return this.setAccess( NodeAccess.READ_WRITE );
  19381. }
  19382. /**
  19383. * Convenience method for configuring a read-only node access.
  19384. *
  19385. * @return {StorageTextureNode} A reference to this node.
  19386. */
  19387. toReadOnly() {
  19388. return this.setAccess( NodeAccess.READ_ONLY );
  19389. }
  19390. /**
  19391. * Convenience method for configuring a write-only node access.
  19392. *
  19393. * @return {StorageTextureNode} A reference to this node.
  19394. */
  19395. toWriteOnly() {
  19396. return this.setAccess( NodeAccess.WRITE_ONLY );
  19397. }
  19398. /**
  19399. * Generates the code snippet of the storage texture node.
  19400. *
  19401. * @param {NodeBuilder} builder - The current node builder.
  19402. */
  19403. generateStore( builder ) {
  19404. const properties = builder.getNodeProperties( this );
  19405. const { uvNode, storeNode } = properties;
  19406. const textureProperty = super.generate( builder, 'property' );
  19407. const uvSnippet = uvNode.build( builder, 'uvec2' );
  19408. const storeSnippet = storeNode.build( builder, 'vec4' );
  19409. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  19410. builder.addLineFlowCode( snippet, this );
  19411. }
  19412. }
  19413. /**
  19414. * TSL function for creating a storage texture node.
  19415. *
  19416. * @function
  19417. * @param {StorageTexture} value - The storage texture.
  19418. * @param {Node<vec2|vec3>} uvNode - The uv node.
  19419. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  19420. * @returns {StorageTextureNode}
  19421. */
  19422. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  19423. /**
  19424. * TODO: Explain difference to `storageTexture()`.
  19425. *
  19426. * @function
  19427. * @param {StorageTexture} value - The storage texture.
  19428. * @param {Node<vec2|vec3>} uvNode - The uv node.
  19429. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  19430. * @returns {StorageTextureNode}
  19431. */
  19432. const textureStore = ( value, uvNode, storeNode ) => {
  19433. const node = storageTexture( value, uvNode, storeNode );
  19434. if ( storeNode !== null ) node.append();
  19435. return node;
  19436. };
  19437. /** @module UserDataNode **/
  19438. /**
  19439. * A special type of reference node that allows to link values in
  19440. * `userData` fields to node objects.
  19441. * ```js
  19442. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  19443. *
  19444. * const material = new THREE.SpriteNodeMaterial();
  19445. * material.rotationNode = userData( 'rotation', 'float' );
  19446. * ```
  19447. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  19448. * will automatically be updated when the `rotation` user data field changes.
  19449. *
  19450. * @augments module:ReferenceNode~ReferenceNode
  19451. */
  19452. class UserDataNode extends ReferenceNode {
  19453. static get type() {
  19454. return 'UserDataNode';
  19455. }
  19456. /**
  19457. * Constructs a new user data node.
  19458. *
  19459. * @param {String} property - The property name that should be referenced by the node.
  19460. * @param {String} inputType - The node data type of the reference.
  19461. * @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.
  19462. */
  19463. constructor( property, inputType, userData = null ) {
  19464. super( property, inputType, userData );
  19465. /**
  19466. * A reference to the `userData` object. If not provided, the `userData`
  19467. * property of the 3D object that uses the node material is evaluated.
  19468. *
  19469. * @type {Object?}
  19470. * @default null
  19471. */
  19472. this.userData = userData;
  19473. }
  19474. /**
  19475. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  19476. * `userData` field.
  19477. *
  19478. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  19479. * @return {Object} A reference to the `userData` field.
  19480. */
  19481. updateReference( state ) {
  19482. this.reference = this.userData !== null ? this.userData : state.object.userData;
  19483. return this.reference;
  19484. }
  19485. }
  19486. /**
  19487. * TSL function for creating a user data node.
  19488. *
  19489. * @function
  19490. * @param {String} name - The property name that should be referenced by the node.
  19491. * @param {String} inputType - The node data type of the reference.
  19492. * @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.
  19493. * @returns {UserDataNode}
  19494. */
  19495. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  19496. const _objectData = new WeakMap();
  19497. /** @module VelocityNode **/
  19498. /**
  19499. * A node for representing motion or velocity vectors. Foundation
  19500. * for advanced post processing effects like motion blur or TRAA.
  19501. *
  19502. * The node keeps track of the model, view and projection matrices
  19503. * of the previous frame and uses them to compute offsets in NDC space.
  19504. * These offsets represent the final velocity.
  19505. *
  19506. * @augments TempNode
  19507. */
  19508. class VelocityNode extends TempNode {
  19509. static get type() {
  19510. return 'VelocityNode';
  19511. }
  19512. /**
  19513. * Constructs a new vertex color node.
  19514. *
  19515. * @param {Number} [index=0] - The attribute index.
  19516. */
  19517. constructor() {
  19518. super( 'vec2' );
  19519. /**
  19520. * The current projection matrix.
  19521. *
  19522. * @type {Matrix4?}
  19523. * @default null
  19524. */
  19525. this.projectionMatrix = null;
  19526. /**
  19527. * Overwritten since velocity nodes are updated per object.
  19528. *
  19529. * @type {String}
  19530. * @default 'object'
  19531. */
  19532. this.updateType = NodeUpdateType.OBJECT;
  19533. /**
  19534. * Overwritten since velocity nodes save data after the update.
  19535. *
  19536. * @type {String}
  19537. * @default 'object'
  19538. */
  19539. this.updateAfterType = NodeUpdateType.OBJECT;
  19540. /**
  19541. * Uniform node representing the previous model matrix in world space.
  19542. *
  19543. * @type {UniformNode<mat4>}
  19544. * @default null
  19545. */
  19546. this.previousModelWorldMatrix = uniform( new Matrix4() );
  19547. /**
  19548. * Uniform node representing the previous projection matrix.
  19549. *
  19550. * @type {UniformNode<mat4>}
  19551. * @default null
  19552. */
  19553. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  19554. /**
  19555. * Uniform node representing the previous view matrix.
  19556. *
  19557. * @type {UniformNode<mat4>}
  19558. * @default null
  19559. */
  19560. this.previousCameraViewMatrix = uniform( new Matrix4() );
  19561. }
  19562. /**
  19563. * Sets the given projection matrix.
  19564. *
  19565. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  19566. */
  19567. setProjectionMatrix( projectionMatrix ) {
  19568. this.projectionMatrix = projectionMatrix;
  19569. }
  19570. /**
  19571. * Updates velocity specific uniforms.
  19572. *
  19573. * @param {NodeFrame} frame - A reference to the current node frame.
  19574. */
  19575. update( { frameId, camera, object } ) {
  19576. const previousModelMatrix = getPreviousMatrix( object );
  19577. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  19578. //
  19579. const cameraData = getData( camera );
  19580. if ( cameraData.frameId !== frameId ) {
  19581. cameraData.frameId = frameId;
  19582. if ( cameraData.previousProjectionMatrix === undefined ) {
  19583. cameraData.previousProjectionMatrix = new Matrix4();
  19584. cameraData.previousCameraViewMatrix = new Matrix4();
  19585. cameraData.currentProjectionMatrix = new Matrix4();
  19586. cameraData.currentCameraViewMatrix = new Matrix4();
  19587. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  19588. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  19589. } else {
  19590. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  19591. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  19592. }
  19593. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  19594. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  19595. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  19596. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  19597. }
  19598. }
  19599. /**
  19600. * Overwritten to updated velocity specific uniforms.
  19601. *
  19602. * @param {NodeFrame} frame - A reference to the current node frame.
  19603. */
  19604. updateAfter( { object } ) {
  19605. getPreviousMatrix( object ).copy( object.matrixWorld );
  19606. }
  19607. /**
  19608. * Implements the velocity computation based on the previous and current vertex data.
  19609. *
  19610. * @param {NodeBuilder} builder - A reference to the current node builder.
  19611. * @return {Node<vec2>} The motion vector.
  19612. */
  19613. setup( /*builder*/ ) {
  19614. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  19615. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  19616. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19617. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  19618. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  19619. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  19620. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  19621. return velocity;
  19622. }
  19623. }
  19624. function getData( object ) {
  19625. let objectData = _objectData.get( object );
  19626. if ( objectData === undefined ) {
  19627. objectData = {};
  19628. _objectData.set( object, objectData );
  19629. }
  19630. return objectData;
  19631. }
  19632. function getPreviousMatrix( object, index = 0 ) {
  19633. const objectData = getData( object );
  19634. let matrix = objectData[ index ];
  19635. if ( matrix === undefined ) {
  19636. objectData[ index ] = matrix = new Matrix4();
  19637. }
  19638. return matrix;
  19639. }
  19640. /**
  19641. * TSL object that represents the velocity of a render pass.
  19642. *
  19643. * @type {VelocityNode}
  19644. */
  19645. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  19646. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  19647. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  19648. } ).setLayout( {
  19649. name: 'blendBurn',
  19650. type: 'vec3',
  19651. inputs: [
  19652. { name: 'base', type: 'vec3' },
  19653. { name: 'blend', type: 'vec3' }
  19654. ]
  19655. } );
  19656. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  19657. return min$1( base.div( blend.oneMinus() ), 1.0 );
  19658. } ).setLayout( {
  19659. name: 'blendDodge',
  19660. type: 'vec3',
  19661. inputs: [
  19662. { name: 'base', type: 'vec3' },
  19663. { name: 'blend', type: 'vec3' }
  19664. ]
  19665. } );
  19666. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  19667. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  19668. } ).setLayout( {
  19669. name: 'blendScreen',
  19670. type: 'vec3',
  19671. inputs: [
  19672. { name: 'base', type: 'vec3' },
  19673. { name: 'blend', type: 'vec3' }
  19674. ]
  19675. } );
  19676. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  19677. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  19678. } ).setLayout( {
  19679. name: 'blendOverlay',
  19680. type: 'vec3',
  19681. inputs: [
  19682. { name: 'base', type: 'vec3' },
  19683. { name: 'blend', type: 'vec3' }
  19684. ]
  19685. } );
  19686. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  19687. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  19688. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  19689. } ).setLayout( {
  19690. name: 'blendColor',
  19691. type: 'vec4',
  19692. inputs: [
  19693. { name: 'base', type: 'vec4' },
  19694. { name: 'blend', type: 'vec4' }
  19695. ]
  19696. } );
  19697. // deprecated
  19698. const burn = ( ...params ) => { // @deprecated, r171
  19699. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  19700. return blendBurn( params );
  19701. };
  19702. const dodge = ( ...params ) => { // @deprecated, r171
  19703. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  19704. return blendDodge( params );
  19705. };
  19706. const screen = ( ...params ) => { // @deprecated, r171
  19707. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  19708. return blendScreen( params );
  19709. };
  19710. const overlay = ( ...params ) => { // @deprecated, r171
  19711. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  19712. return blendOverlay( params );
  19713. };
  19714. /** @module ColorAdjustment **/
  19715. /**
  19716. * Computes a grayscale value for the given RGB color value.
  19717. *
  19718. * @method
  19719. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  19720. * @return {Node<vec3>} The grayscale color.
  19721. */
  19722. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  19723. return luminance( color.rgb );
  19724. } );
  19725. /**
  19726. * Super-saturates or desaturates the given RGB color.
  19727. *
  19728. * @method
  19729. * @param {Node<vec3>} color - The input color.
  19730. * @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.
  19731. * @return {Node<vec3>} The saturated color.
  19732. */
  19733. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  19734. return adjustment.mix( luminance( color.rgb ), color.rgb );
  19735. } );
  19736. /**
  19737. * Selectively enhance the intensity of less saturated RGB colors. Can result
  19738. * in a more natural and visually appealing image with enhanced color depth
  19739. * compared to {@link ColorAdjustment#saturation}.
  19740. *
  19741. * @method
  19742. * @param {Node<vec3>} color - The input color.
  19743. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  19744. * @return {Node<vec3>} The updated color.
  19745. */
  19746. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  19747. const average = add( color.r, color.g, color.b ).div( 3.0 );
  19748. const mx = color.r.max( color.g.max( color.b ) );
  19749. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  19750. return mix( color.rgb, mx, amt );
  19751. } );
  19752. /**
  19753. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  19754. *
  19755. * @method
  19756. * @param {Node<vec3>} color - The input color.
  19757. * @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.
  19758. * @return {Node<vec3>} The updated color.
  19759. */
  19760. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  19761. const k = vec3( 0.57735, 0.57735, 0.57735 );
  19762. const cosAngle = adjustment.cos();
  19763. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  19764. } );
  19765. /**
  19766. * Computes the luminance for the given RGB color value.
  19767. *
  19768. * @method
  19769. * @param {Node<vec3>} color - The color value to compute the luminance for.
  19770. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  19771. * @return {Node<vec3>} The luminance.
  19772. */
  19773. const luminance = (
  19774. color,
  19775. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  19776. ) => dot( color, luminanceCoefficients );
  19777. /**
  19778. * Color Decision List (CDL) v1.2
  19779. *
  19780. * Compact representation of color grading information, defined by slope, offset, power, and
  19781. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  19782. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  19783. *
  19784. * @method
  19785. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  19786. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  19787. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  19788. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  19789. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  19790. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  19791. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  19792. *
  19793. * References:
  19794. * - ASC CDL v1.2
  19795. * - {@link https://blender.stackexchange.com/a/55239/43930}
  19796. * - {@link https://docs.acescentral.com/specifications/acescc/}
  19797. */
  19798. const cdl = /*@__PURE__*/ Fn( ( [
  19799. color,
  19800. slope = vec3( 1 ),
  19801. offset = vec3( 0 ),
  19802. power = vec3( 1 ),
  19803. saturation = float( 1 ),
  19804. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  19805. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  19806. ] ) => {
  19807. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  19808. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  19809. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  19810. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  19811. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  19812. const pv = v.pow( power ).toVar();
  19813. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  19814. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  19815. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  19816. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  19817. return vec4( v.rgb, color.a );
  19818. } );
  19819. /** @module PosterizeNode **/
  19820. /**
  19821. * Represents a posterize effect which reduces the number of colors
  19822. * in an image, resulting in a more blocky and stylized appearance.
  19823. *
  19824. * @augments TempNode
  19825. */
  19826. class PosterizeNode extends TempNode {
  19827. static get type() {
  19828. return 'PosterizeNode';
  19829. }
  19830. /**
  19831. * Constructs a new posterize node.
  19832. *
  19833. * @param {Node} sourceNode - The input color.
  19834. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  19835. */
  19836. constructor( sourceNode, stepsNode ) {
  19837. super();
  19838. /**
  19839. * The input color.
  19840. *
  19841. * @type {Node}
  19842. */
  19843. this.sourceNode = sourceNode;
  19844. /**
  19845. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  19846. *
  19847. * @type {Node}
  19848. */
  19849. this.stepsNode = stepsNode;
  19850. }
  19851. setup() {
  19852. const { sourceNode, stepsNode } = this;
  19853. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  19854. }
  19855. }
  19856. /**
  19857. * TSL function for creating a posterize node.
  19858. *
  19859. * @function
  19860. * @param {Node} sourceNode - The input color.
  19861. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  19862. * @returns {PosterizeNode}
  19863. */
  19864. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  19865. /** @module PassNode **/
  19866. const _size = /*@__PURE__*/ new Vector2();
  19867. /**
  19868. * Represents the texture of a pass node.
  19869. *
  19870. * @augments module:TextureNode~TextureNode
  19871. */
  19872. class PassTextureNode extends TextureNode {
  19873. static get type() {
  19874. return 'PassTextureNode';
  19875. }
  19876. /**
  19877. * Constructs a new pass texture node.
  19878. *
  19879. * @param {PassNode} passNode - The pass node.
  19880. * @param {Texture} texture - The output texture.
  19881. */
  19882. constructor( passNode, texture ) {
  19883. super( texture );
  19884. /**
  19885. * A reference to the pass node.
  19886. *
  19887. * @type {PassNode}
  19888. */
  19889. this.passNode = passNode;
  19890. this.setUpdateMatrix( false );
  19891. }
  19892. setup( builder ) {
  19893. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  19894. return super.setup( builder );
  19895. }
  19896. clone() {
  19897. return new this.constructor( this.passNode, this.value );
  19898. }
  19899. }
  19900. /**
  19901. * An extension of `PassTextureNode` which allows to manage more than one
  19902. * internal texture. Relevant for the `getPreviousTexture()` related API.
  19903. *
  19904. * @augments module:PassTextureNode~PassTextureNode
  19905. */
  19906. class PassMultipleTextureNode extends PassTextureNode {
  19907. static get type() {
  19908. return 'PassMultipleTextureNode';
  19909. }
  19910. /**
  19911. * Constructs a new pass texture node.
  19912. *
  19913. * @param {PassNode} passNode - The pass node.
  19914. * @param {String} textureName - The output texture name.
  19915. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  19916. */
  19917. constructor( passNode, textureName, previousTexture = false ) {
  19918. // null is passed to the super call since this class does not
  19919. // use an external texture for rendering pass data into. Instead
  19920. // the texture is managed by the pass node itself
  19921. super( passNode, null );
  19922. /**
  19923. * The output texture name.
  19924. *
  19925. * @type {String}
  19926. */
  19927. this.textureName = textureName;
  19928. /**
  19929. * Whether previous frame data should be used or not.
  19930. *
  19931. * @type {Boolean}
  19932. */
  19933. this.previousTexture = previousTexture;
  19934. }
  19935. /**
  19936. * Updates the texture reference of this node.
  19937. */
  19938. updateTexture() {
  19939. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  19940. }
  19941. setup( builder ) {
  19942. this.updateTexture();
  19943. return super.setup( builder );
  19944. }
  19945. clone() {
  19946. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  19947. }
  19948. }
  19949. /**
  19950. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  19951. * This pass produces a render for the given scene and camera and can provide multiple outputs
  19952. * via MRT for further processing.
  19953. *
  19954. * ```js
  19955. * const postProcessing = new PostProcessing( renderer );
  19956. *
  19957. * const scenePass = pass( scene, camera );
  19958. *
  19959. * postProcessing.outputNode = scenePass;
  19960. * ```
  19961. *
  19962. * @augments TempNode
  19963. */
  19964. class PassNode extends TempNode {
  19965. static get type() {
  19966. return 'PassNode';
  19967. }
  19968. /**
  19969. * Constructs a new pass node.
  19970. *
  19971. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  19972. * @param {Scene} scene - A reference to the scene.
  19973. * @param {Camera} camera - A reference to the camera.
  19974. * @param {Object} options - Options for the internal render target.
  19975. */
  19976. constructor( scope, scene, camera, options = {} ) {
  19977. super( 'vec4' );
  19978. /**
  19979. * The scope of the pass. The scope determines whether the node outputs color or depth.
  19980. *
  19981. * @type {('color'|'depth')}
  19982. */
  19983. this.scope = scope;
  19984. /**
  19985. * A reference to the scene.
  19986. *
  19987. * @type {Scene}
  19988. */
  19989. this.scene = scene;
  19990. /**
  19991. * A reference to the camera.
  19992. *
  19993. * @type {Camera}
  19994. */
  19995. this.camera = camera;
  19996. /**
  19997. * Options for the internal render target.
  19998. *
  19999. * @type {Object}
  20000. */
  20001. this.options = options;
  20002. /**
  20003. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  20004. *
  20005. * @private
  20006. * @type {Number}
  20007. * @default 1
  20008. */
  20009. this._pixelRatio = 1;
  20010. /**
  20011. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  20012. * @private
  20013. * @type {Number}
  20014. * @default 1
  20015. */
  20016. this._width = 1;
  20017. /**
  20018. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  20019. * @private
  20020. * @type {Number}
  20021. * @default 1
  20022. */
  20023. this._height = 1;
  20024. const depthTexture = new DepthTexture();
  20025. depthTexture.isRenderTargetTexture = true;
  20026. //depthTexture.type = FloatType;
  20027. depthTexture.name = 'depth';
  20028. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  20029. renderTarget.texture.name = 'output';
  20030. renderTarget.depthTexture = depthTexture;
  20031. /**
  20032. * The pass's render target.
  20033. *
  20034. * @type {RenderTarget}
  20035. */
  20036. this.renderTarget = renderTarget;
  20037. /**
  20038. * A dictionary holding the internal result textures.
  20039. *
  20040. * @private
  20041. * @type {Object<String, Texture>}
  20042. */
  20043. this._textures = {
  20044. output: renderTarget.texture,
  20045. depth: depthTexture
  20046. };
  20047. /**
  20048. * A dictionary holding the internal texture nodes.
  20049. *
  20050. * @private
  20051. * @type {Object<String, TextureNode>}
  20052. */
  20053. this._textureNodes = {};
  20054. /**
  20055. * A dictionary holding the internal depth nodes.
  20056. *
  20057. * @private
  20058. * @type {Object}
  20059. */
  20060. this._linearDepthNodes = {};
  20061. /**
  20062. * A dictionary holding the internal viewZ nodes.
  20063. *
  20064. * @private
  20065. * @type {Object}
  20066. */
  20067. this._viewZNodes = {};
  20068. /**
  20069. * A dictionary holding the texture data of the previous frame.
  20070. * Used for computing velocity/motion vectors.
  20071. *
  20072. * @private
  20073. * @type {Object<String, Texture>}
  20074. */
  20075. this._previousTextures = {};
  20076. /**
  20077. * A dictionary holding the texture nodes of the previous frame.
  20078. * Used for computing velocity/motion vectors.
  20079. *
  20080. * @private
  20081. * @type {Object<String, TextureNode>}
  20082. */
  20083. this._previousTextureNodes = {};
  20084. /**
  20085. * The `near` property of the camera as a uniform.
  20086. *
  20087. * @private
  20088. * @type {UniformNode}
  20089. */
  20090. this._cameraNear = uniform( 0 );
  20091. /**
  20092. * The `far` property of the camera as a uniform.
  20093. *
  20094. * @private
  20095. * @type {UniformNode}
  20096. */
  20097. this._cameraFar = uniform( 0 );
  20098. /**
  20099. * A MRT node configuring the MRT settings.
  20100. *
  20101. * @private
  20102. * @type {MRTNode?}
  20103. * @default null
  20104. */
  20105. this._mrt = null;
  20106. /**
  20107. * This flag can be used for type testing.
  20108. *
  20109. * @type {Boolean}
  20110. * @readonly
  20111. * @default true
  20112. */
  20113. this.isPassNode = true;
  20114. /**
  20115. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  20116. * scene once per frame in its {@link PassNode#updateBefore} method.
  20117. *
  20118. * @type {String}
  20119. * @default 'frame'
  20120. */
  20121. this.updateBeforeType = NodeUpdateType.FRAME;
  20122. }
  20123. /**
  20124. * Sets the given MRT node to setup MRT for this pass.
  20125. *
  20126. * @param {MRTNode} mrt - The MRT object.
  20127. * @return {PassNode} A reference to this pass.
  20128. */
  20129. setMRT( mrt ) {
  20130. this._mrt = mrt;
  20131. return this;
  20132. }
  20133. /**
  20134. * Returns the current MRT node.
  20135. *
  20136. * @return {MRTNode} The current MRT node.
  20137. */
  20138. getMRT() {
  20139. return this._mrt;
  20140. }
  20141. /**
  20142. * The method is overwritten so it always returns `true`.
  20143. *
  20144. * @return {Boolean} Whether this node is global or not.
  20145. */
  20146. isGlobal() {
  20147. return true;
  20148. }
  20149. /**
  20150. * Returns the texture for the given output name.
  20151. *
  20152. * @param {String} name - The output name to get the texture for.
  20153. * @return {Texture} The texture.
  20154. */
  20155. getTexture( name ) {
  20156. let texture = this._textures[ name ];
  20157. if ( texture === undefined ) {
  20158. const refTexture = this.renderTarget.texture;
  20159. texture = refTexture.clone();
  20160. texture.name = name;
  20161. this._textures[ name ] = texture;
  20162. this.renderTarget.textures.push( texture );
  20163. }
  20164. return texture;
  20165. }
  20166. /**
  20167. * Returns the texture holding the data of the previous frame for the given output name.
  20168. *
  20169. * @param {String} name - The output name to get the texture for.
  20170. * @return {Texture} The texture holding the data of the previous frame.
  20171. */
  20172. getPreviousTexture( name ) {
  20173. let texture = this._previousTextures[ name ];
  20174. if ( texture === undefined ) {
  20175. texture = this.getTexture( name ).clone();
  20176. this._previousTextures[ name ] = texture;
  20177. }
  20178. return texture;
  20179. }
  20180. /**
  20181. * Switches current and previous textures for the given output name.
  20182. *
  20183. * @param {String} name - The output name.
  20184. */
  20185. toggleTexture( name ) {
  20186. const prevTexture = this._previousTextures[ name ];
  20187. if ( prevTexture !== undefined ) {
  20188. const texture = this._textures[ name ];
  20189. const index = this.renderTarget.textures.indexOf( texture );
  20190. this.renderTarget.textures[ index ] = prevTexture;
  20191. this._textures[ name ] = prevTexture;
  20192. this._previousTextures[ name ] = texture;
  20193. this._textureNodes[ name ].updateTexture();
  20194. this._previousTextureNodes[ name ].updateTexture();
  20195. }
  20196. }
  20197. /**
  20198. * Returns the texture node for the given output name.
  20199. *
  20200. * @param {String} [name='output'] - The output name to get the texture node for.
  20201. * @return {TextureNode} The texture node.
  20202. */
  20203. getTextureNode( name = 'output' ) {
  20204. let textureNode = this._textureNodes[ name ];
  20205. if ( textureNode === undefined ) {
  20206. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  20207. textureNode.updateTexture();
  20208. this._textureNodes[ name ] = textureNode;
  20209. }
  20210. return textureNode;
  20211. }
  20212. /**
  20213. * Returns the previous texture node for the given output name.
  20214. *
  20215. * @param {String} [name='output'] - The output name to get the previous texture node for.
  20216. * @return {TextureNode} The previous texture node.
  20217. */
  20218. getPreviousTextureNode( name = 'output' ) {
  20219. let textureNode = this._previousTextureNodes[ name ];
  20220. if ( textureNode === undefined ) {
  20221. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  20222. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  20223. textureNode.updateTexture();
  20224. this._previousTextureNodes[ name ] = textureNode;
  20225. }
  20226. return textureNode;
  20227. }
  20228. /**
  20229. * Returns a viewZ node of this pass.
  20230. *
  20231. * @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.
  20232. * @return {Node} The viewZ node.
  20233. */
  20234. getViewZNode( name = 'depth' ) {
  20235. let viewZNode = this._viewZNodes[ name ];
  20236. if ( viewZNode === undefined ) {
  20237. const cameraNear = this._cameraNear;
  20238. const cameraFar = this._cameraFar;
  20239. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  20240. }
  20241. return viewZNode;
  20242. }
  20243. /**
  20244. * Returns a linear depth node of this pass.
  20245. *
  20246. * @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.
  20247. * @return {Node} The linear depth node.
  20248. */
  20249. getLinearDepthNode( name = 'depth' ) {
  20250. let linearDepthNode = this._linearDepthNodes[ name ];
  20251. if ( linearDepthNode === undefined ) {
  20252. const cameraNear = this._cameraNear;
  20253. const cameraFar = this._cameraFar;
  20254. const viewZNode = this.getViewZNode( name );
  20255. // TODO: just if ( builder.camera.isPerspectiveCamera )
  20256. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  20257. }
  20258. return linearDepthNode;
  20259. }
  20260. setup( { renderer } ) {
  20261. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  20262. // Disable MSAA for WebGL backend for now
  20263. if ( renderer.backend.isWebGLBackend === true ) {
  20264. this.renderTarget.samples = 0;
  20265. }
  20266. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  20267. }
  20268. updateBefore( frame ) {
  20269. const { renderer } = frame;
  20270. const { scene, camera } = this;
  20271. this._pixelRatio = renderer.getPixelRatio();
  20272. const size = renderer.getSize( _size );
  20273. this.setSize( size.width, size.height );
  20274. const currentRenderTarget = renderer.getRenderTarget();
  20275. const currentMRT = renderer.getMRT();
  20276. this._cameraNear.value = camera.near;
  20277. this._cameraFar.value = camera.far;
  20278. for ( const name in this._previousTextures ) {
  20279. this.toggleTexture( name );
  20280. }
  20281. renderer.setRenderTarget( this.renderTarget );
  20282. renderer.setMRT( this._mrt );
  20283. renderer.render( scene, camera );
  20284. renderer.setRenderTarget( currentRenderTarget );
  20285. renderer.setMRT( currentMRT );
  20286. }
  20287. /**
  20288. * Sets the size of the pass's render target. Honors the pixel ratio.
  20289. *
  20290. * @param {Number} width - The width to set.
  20291. * @param {Number} height - The height to set.
  20292. */
  20293. setSize( width, height ) {
  20294. this._width = width;
  20295. this._height = height;
  20296. const effectiveWidth = this._width * this._pixelRatio;
  20297. const effectiveHeight = this._height * this._pixelRatio;
  20298. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20299. }
  20300. /**
  20301. * Sets the pixel ratio the pass's render target and updates the size.
  20302. *
  20303. * @param {Number} pixelRatio - The pixel ratio to set.
  20304. */
  20305. setPixelRatio( pixelRatio ) {
  20306. this._pixelRatio = pixelRatio;
  20307. this.setSize( this._width, this._height );
  20308. }
  20309. /**
  20310. * Frees internal resources. Should be called when the node is no longer in use.
  20311. */
  20312. dispose() {
  20313. this.renderTarget.dispose();
  20314. }
  20315. }
  20316. PassNode.COLOR = 'color';
  20317. PassNode.DEPTH = 'depth';
  20318. /**
  20319. * TSL function for creating a pass node.
  20320. *
  20321. * @function
  20322. * @param {Scene} scene - A reference to the scene.
  20323. * @param {Camera} camera - A reference to the camera.
  20324. * @param {Object} options - Options for the internal render target.
  20325. * @returns {PassNode}
  20326. */
  20327. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  20328. /**
  20329. * TSL function for creating a pass texture node.
  20330. *
  20331. * @function
  20332. * @param {PassNode} pass - The pass node.
  20333. * @param {Texture} texture - The output texture.
  20334. * @returns {PassTextureNode}
  20335. */
  20336. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  20337. /**
  20338. * TSL function for creating a depth pass node.
  20339. *
  20340. * @function
  20341. * @param {Scene} scene - A reference to the scene.
  20342. * @param {Camera} camera - A reference to the camera.
  20343. * @param {Object} options - Options for the internal render target.
  20344. * @returns {PassNode}
  20345. */
  20346. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  20347. /** @module ToonOutlinePassNode **/
  20348. /**
  20349. * Represents a render pass for producing a toon outline effect on compatible objects.
  20350. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  20351. * will receive the outline.
  20352. *
  20353. * ```js
  20354. * const postProcessing = new PostProcessing( renderer );
  20355. *
  20356. * const scenePass = toonOutlinePass( scene, camera );
  20357. *
  20358. * postProcessing.outputNode = scenePass;
  20359. * ```
  20360. * @augments PassNode
  20361. */
  20362. class ToonOutlinePassNode extends PassNode {
  20363. static get type() {
  20364. return 'ToonOutlinePassNode';
  20365. }
  20366. /**
  20367. * Constructs a new outline pass node.
  20368. *
  20369. * @param {Scene} scene - A reference to the scene.
  20370. * @param {Camera} camera - A reference to the camera.
  20371. * @param {Node} colorNode - Defines the outline's color.
  20372. * @param {Node} thicknessNode - Defines the outline's thickness.
  20373. * @param {Node} alphaNode - Defines the outline's alpha.
  20374. */
  20375. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  20376. super( PassNode.COLOR, scene, camera );
  20377. /**
  20378. * Defines the outline's color.
  20379. *
  20380. * @type {Node}
  20381. */
  20382. this.colorNode = colorNode;
  20383. /**
  20384. * Defines the outline's thickness.
  20385. *
  20386. * @type {Node}
  20387. */
  20388. this.thicknessNode = thicknessNode;
  20389. /**
  20390. * Defines the outline's alpha.
  20391. *
  20392. * @type {Node}
  20393. */
  20394. this.alphaNode = alphaNode;
  20395. /**
  20396. * An internal material cache.
  20397. *
  20398. * @private
  20399. * @type {WeakMap<Material, NodeMaterial>}
  20400. */
  20401. this._materialCache = new WeakMap();
  20402. }
  20403. updateBefore( frame ) {
  20404. const { renderer } = frame;
  20405. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  20406. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  20407. // only render outline for supported materials
  20408. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  20409. if ( material.wireframe === false ) {
  20410. const outlineMaterial = this._getOutlineMaterial( material );
  20411. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  20412. }
  20413. }
  20414. // default
  20415. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  20416. } );
  20417. super.updateBefore( frame );
  20418. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  20419. }
  20420. /**
  20421. * Creates the material used for outline rendering.
  20422. *
  20423. * @private
  20424. * @return {NodeMaterial} The outline material.
  20425. */
  20426. _createMaterial() {
  20427. const material = new NodeMaterial();
  20428. material.isMeshToonOutlineMaterial = true;
  20429. material.name = 'Toon_Outline';
  20430. material.side = BackSide;
  20431. // vertex node
  20432. const outlineNormal = normalLocal.negate();
  20433. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  20434. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  20435. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  20436. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  20437. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  20438. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  20439. // color node
  20440. material.colorNode = vec4( this.colorNode, this.alphaNode );
  20441. return material;
  20442. }
  20443. /**
  20444. * For the given toon material, this method returns a corresponding
  20445. * outline material.
  20446. *
  20447. * @private
  20448. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  20449. * @return {NodeMaterial} The outline material.
  20450. */
  20451. _getOutlineMaterial( originalMaterial ) {
  20452. let outlineMaterial = this._materialCache.get( originalMaterial );
  20453. if ( outlineMaterial === undefined ) {
  20454. outlineMaterial = this._createMaterial();
  20455. this._materialCache.set( originalMaterial, outlineMaterial );
  20456. }
  20457. return outlineMaterial;
  20458. }
  20459. }
  20460. /**
  20461. * TSL function for creating a toon outline pass node.
  20462. *
  20463. * @function
  20464. * @param {Scene} scene - A reference to the scene.
  20465. * @param {Camera} camera - A reference to the camera.
  20466. * @param {Color} color - Defines the outline's color.
  20467. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  20468. * @param {Number} [alpha=1] - Defines the outline's alpha.
  20469. * @returns {ToonOutlinePassNode}
  20470. */
  20471. 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 ) ) );
  20472. /** @module ToneMappingFunctions **/
  20473. /**
  20474. * Linear tone mapping, exposure only.
  20475. *
  20476. * @method
  20477. * @param {Node<vec3>} color - The color that should be tone mapped.
  20478. * @param {Node<float>} exposure - The exposure.
  20479. * @return {Node<vec3>} The tone mapped color.
  20480. */
  20481. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20482. return color.mul( exposure ).clamp();
  20483. } ).setLayout( {
  20484. name: 'linearToneMapping',
  20485. type: 'vec3',
  20486. inputs: [
  20487. { name: 'color', type: 'vec3' },
  20488. { name: 'exposure', type: 'float' }
  20489. ]
  20490. } );
  20491. /**
  20492. * Reinhard tone mapping.
  20493. *
  20494. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  20495. *
  20496. * @method
  20497. * @param {Node<vec3>} color - The color that should be tone mapped.
  20498. * @param {Node<float>} exposure - The exposure.
  20499. * @return {Node<vec3>} The tone mapped color.
  20500. */
  20501. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20502. color = color.mul( exposure );
  20503. return color.div( color.add( 1.0 ) ).clamp();
  20504. } ).setLayout( {
  20505. name: 'reinhardToneMapping',
  20506. type: 'vec3',
  20507. inputs: [
  20508. { name: 'color', type: 'vec3' },
  20509. { name: 'exposure', type: 'float' }
  20510. ]
  20511. } );
  20512. /**
  20513. * Cineon tone mapping.
  20514. *
  20515. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  20516. *
  20517. * @method
  20518. * @param {Node<vec3>} color - The color that should be tone mapped.
  20519. * @param {Node<float>} exposure - The exposure.
  20520. * @return {Node<vec3>} The tone mapped color.
  20521. */
  20522. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20523. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  20524. color = color.mul( exposure );
  20525. color = color.sub( 0.004 ).max( 0.0 );
  20526. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  20527. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  20528. return a.div( b ).pow( 2.2 );
  20529. } ).setLayout( {
  20530. name: 'cineonToneMapping',
  20531. type: 'vec3',
  20532. inputs: [
  20533. { name: 'color', type: 'vec3' },
  20534. { name: 'exposure', type: 'float' }
  20535. ]
  20536. } );
  20537. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  20538. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  20539. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  20540. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  20541. return a.div( b );
  20542. } );
  20543. /**
  20544. * ACESFilmic tone mapping.
  20545. *
  20546. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  20547. *
  20548. * @method
  20549. * @param {Node<vec3>} color - The color that should be tone mapped.
  20550. * @param {Node<float>} exposure - The exposure.
  20551. * @return {Node<vec3>} The tone mapped color.
  20552. */
  20553. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20554. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  20555. const ACESInputMat = mat3(
  20556. 0.59719, 0.35458, 0.04823,
  20557. 0.07600, 0.90834, 0.01566,
  20558. 0.02840, 0.13383, 0.83777
  20559. );
  20560. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  20561. const ACESOutputMat = mat3(
  20562. 1.60475, - 0.53108, - 0.07367,
  20563. - 0.10208, 1.10813, - 0.00605,
  20564. - 0.00327, - 0.07276, 1.07602
  20565. );
  20566. color = color.mul( exposure ).div( 0.6 );
  20567. color = ACESInputMat.mul( color );
  20568. // Apply RRT and ODT
  20569. color = RRTAndODTFit( color );
  20570. color = ACESOutputMat.mul( color );
  20571. // Clamp to [0, 1]
  20572. return color.clamp();
  20573. } ).setLayout( {
  20574. name: 'acesFilmicToneMapping',
  20575. type: 'vec3',
  20576. inputs: [
  20577. { name: 'color', type: 'vec3' },
  20578. { name: 'exposure', type: 'float' }
  20579. ]
  20580. } );
  20581. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  20582. 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 ) );
  20583. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  20584. const x = vec3( x_immutable ).toVar();
  20585. const x2 = vec3( x.mul( x ) ).toVar();
  20586. const x4 = vec3( x2.mul( x2 ) ).toVar();
  20587. 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 ) ) ) );
  20588. } );
  20589. /**
  20590. * AgX tone mapping.
  20591. *
  20592. * @method
  20593. * @param {Node<vec3>} color - The color that should be tone mapped.
  20594. * @param {Node<float>} exposure - The exposure.
  20595. * @return {Node<vec3>} The tone mapped color.
  20596. */
  20597. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20598. const colortone = vec3( color ).toVar();
  20599. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  20600. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  20601. const AgxMinEv = float( - 12.47393 );
  20602. const AgxMaxEv = float( 4.026069 );
  20603. colortone.mulAssign( exposure );
  20604. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  20605. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  20606. colortone.assign( max$1( colortone, 1e-10 ) );
  20607. colortone.assign( log2( colortone ) );
  20608. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  20609. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  20610. colortone.assign( agxDefaultContrastApprox( colortone ) );
  20611. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  20612. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  20613. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  20614. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  20615. return colortone;
  20616. } ).setLayout( {
  20617. name: 'agxToneMapping',
  20618. type: 'vec3',
  20619. inputs: [
  20620. { name: 'color', type: 'vec3' },
  20621. { name: 'exposure', type: 'float' }
  20622. ]
  20623. } );
  20624. /**
  20625. * Neutral tone mapping.
  20626. *
  20627. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  20628. *
  20629. * @method
  20630. * @param {Node<vec3>} color - The color that should be tone mapped.
  20631. * @param {Node<float>} exposure - The exposure.
  20632. * @return {Node<vec3>} The tone mapped color.
  20633. */
  20634. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  20635. const StartCompression = float( 0.8 - 0.04 );
  20636. const Desaturation = float( 0.15 );
  20637. color = color.mul( exposure );
  20638. const x = min$1( color.r, min$1( color.g, color.b ) );
  20639. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  20640. color.subAssign( offset );
  20641. const peak = max$1( color.r, max$1( color.g, color.b ) );
  20642. If( peak.lessThan( StartCompression ), () => {
  20643. return color;
  20644. } );
  20645. const d = sub( 1, StartCompression );
  20646. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  20647. color.mulAssign( newPeak.div( peak ) );
  20648. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  20649. return mix( color, vec3( newPeak ), g );
  20650. } ).setLayout( {
  20651. name: 'neutralToneMapping',
  20652. type: 'vec3',
  20653. inputs: [
  20654. { name: 'color', type: 'vec3' },
  20655. { name: 'exposure', type: 'float' }
  20656. ]
  20657. } );
  20658. /** @module CodeNode **/
  20659. /**
  20660. * This class represents native code sections. It is the base
  20661. * class for modules like {@link FunctionNode} which allows to implement
  20662. * functions with native shader languages.
  20663. *
  20664. * @augments Node
  20665. */
  20666. class CodeNode extends Node {
  20667. static get type() {
  20668. return 'CodeNode';
  20669. }
  20670. /**
  20671. * Constructs a new code node.
  20672. *
  20673. * @param {String} [code=''] - The native code.
  20674. * @param {Array<Node>} [includes=[]] - An array of includes.
  20675. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  20676. */
  20677. constructor( code = '', includes = [], language = '' ) {
  20678. super( 'code' );
  20679. /**
  20680. * This flag can be used for type testing.
  20681. *
  20682. * @type {Boolean}
  20683. * @readonly
  20684. * @default true
  20685. */
  20686. this.isCodeNode = true;
  20687. /**
  20688. * The native code.
  20689. *
  20690. * @type {String}
  20691. * @default ''
  20692. */
  20693. this.code = code;
  20694. /**
  20695. * An array of includes
  20696. *
  20697. * @type {Array<Node>}
  20698. * @default []
  20699. */
  20700. this.includes = includes;
  20701. /**
  20702. * The used language.
  20703. *
  20704. * @type {('js'|'wgsl'|'glsl')}
  20705. * @default ''
  20706. */
  20707. this.language = language;
  20708. }
  20709. /**
  20710. * The method is overwritten so it always returns `true`.
  20711. *
  20712. * @return {Boolean} Whether this node is global or not.
  20713. */
  20714. isGlobal() {
  20715. return true;
  20716. }
  20717. /**
  20718. * Sets the includes of this code node.
  20719. *
  20720. * @param {Array<Node>} includes - The includes to set.
  20721. * @return {CodeNode} A reference to this node.
  20722. */
  20723. setIncludes( includes ) {
  20724. this.includes = includes;
  20725. return this;
  20726. }
  20727. /**
  20728. * Returns the includes of this code node.
  20729. *
  20730. * @param {NodeBuilder} builder - The current node builder.
  20731. * @return {Array<Node>} The includes.
  20732. */
  20733. getIncludes( /*builder*/ ) {
  20734. return this.includes;
  20735. }
  20736. generate( builder ) {
  20737. const includes = this.getIncludes( builder );
  20738. for ( const include of includes ) {
  20739. include.build( builder );
  20740. }
  20741. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  20742. nodeCode.code = this.code;
  20743. return nodeCode.code;
  20744. }
  20745. serialize( data ) {
  20746. super.serialize( data );
  20747. data.code = this.code;
  20748. data.language = this.language;
  20749. }
  20750. deserialize( data ) {
  20751. super.deserialize( data );
  20752. this.code = data.code;
  20753. this.language = data.language;
  20754. }
  20755. }
  20756. /**
  20757. * TSL function for creating a code node.
  20758. *
  20759. * @function
  20760. * @param {String} [code=''] - The native code.
  20761. * @param {Array<Node>} [includes=[]] - An array of includes.
  20762. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  20763. * @returns {CodeNode}
  20764. */
  20765. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  20766. /**
  20767. * TSL function for creating a JS code node.
  20768. *
  20769. * @function
  20770. * @param {String} src - The native code.
  20771. * @param {Array<Node>} includes - An array of includes.
  20772. * @returns {CodeNode}
  20773. */
  20774. const js = ( src, includes ) => code( src, includes, 'js' );
  20775. /**
  20776. * TSL function for creating a WGSL code node.
  20777. *
  20778. * @function
  20779. * @param {String} src - The native code.
  20780. * @param {Array<Node>} includes - An array of includes.
  20781. * @returns {CodeNode}
  20782. */
  20783. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  20784. /**
  20785. * TSL function for creating a GLSL code node.
  20786. *
  20787. * @function
  20788. * @param {String} src - The native code.
  20789. * @param {Array<Node>} includes - An array of includes.
  20790. * @returns {CodeNode}
  20791. */
  20792. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  20793. /**
  20794. * This class represents a native shader function. It can be used to implement
  20795. * certain aspects of a node material with native shader code. There are two predefined
  20796. * TSL functions for easier usage.
  20797. *
  20798. * - `wgslFn`: Creates a WGSL function node.
  20799. * - `glslFn`: Creates a GLSL function node.
  20800. *
  20801. * A basic example with one include looks like so:
  20802. *
  20803. * ```js
  20804. * const desaturateWGSLFn = wgslFn( `
  20805. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  20806. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  20807. * return vec3<f32>( dot( lum, color ) );
  20808. * }`
  20809. *);
  20810. * const someWGSLFn = wgslFn( `
  20811. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  20812. * return desaturate( color );
  20813. * }
  20814. * `, [ desaturateWGSLFn ] );
  20815. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  20816. *```
  20817. * @augments CodeNode
  20818. */
  20819. class FunctionNode extends CodeNode {
  20820. static get type() {
  20821. return 'FunctionNode';
  20822. }
  20823. /**
  20824. * Constructs a new function node.
  20825. *
  20826. * @param {String} [code=''] - The native code.
  20827. * @param {Array<Node>} [includes=[]] - An array of includes.
  20828. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  20829. */
  20830. constructor( code = '', includes = [], language = '' ) {
  20831. super( code, includes, language );
  20832. }
  20833. getNodeType( builder ) {
  20834. return this.getNodeFunction( builder ).type;
  20835. }
  20836. /**
  20837. * Returns the inputs of this function node.
  20838. *
  20839. * @param {NodeBuilder} builder - The current node builder.
  20840. * @return {Array<NodeFunctionInput>} The inputs.
  20841. */
  20842. getInputs( builder ) {
  20843. return this.getNodeFunction( builder ).inputs;
  20844. }
  20845. /**
  20846. * Returns the node function for this function node.
  20847. *
  20848. * @param {NodeBuilder} builder - The current node builder.
  20849. * @return {NodeFunction} The node function.
  20850. */
  20851. getNodeFunction( builder ) {
  20852. const nodeData = builder.getDataFromNode( this );
  20853. let nodeFunction = nodeData.nodeFunction;
  20854. if ( nodeFunction === undefined ) {
  20855. nodeFunction = builder.parser.parseFunction( this.code );
  20856. nodeData.nodeFunction = nodeFunction;
  20857. }
  20858. return nodeFunction;
  20859. }
  20860. generate( builder, output ) {
  20861. super.generate( builder );
  20862. const nodeFunction = this.getNodeFunction( builder );
  20863. const name = nodeFunction.name;
  20864. const type = nodeFunction.type;
  20865. const nodeCode = builder.getCodeFromNode( this, type );
  20866. if ( name !== '' ) {
  20867. // use a custom property name
  20868. nodeCode.name = name;
  20869. }
  20870. const propertyName = builder.getPropertyName( nodeCode );
  20871. const code = this.getNodeFunction( builder ).getCode( propertyName );
  20872. nodeCode.code = code + '\n';
  20873. if ( output === 'property' ) {
  20874. return propertyName;
  20875. } else {
  20876. return builder.format( `${ propertyName }()`, type, output );
  20877. }
  20878. }
  20879. }
  20880. const nativeFn = ( code, includes = [], language = '' ) => {
  20881. for ( let i = 0; i < includes.length; i ++ ) {
  20882. const include = includes[ i ];
  20883. // TSL Function: glslFn, wgslFn
  20884. if ( typeof include === 'function' ) {
  20885. includes[ i ] = include.functionNode;
  20886. }
  20887. }
  20888. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  20889. const fn = ( ...params ) => functionNode.call( ...params );
  20890. fn.functionNode = functionNode;
  20891. return fn;
  20892. };
  20893. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  20894. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  20895. /**
  20896. * `ScriptableNode` uses this class to manage script inputs and outputs.
  20897. *
  20898. * @augments Node
  20899. */
  20900. class ScriptableValueNode extends Node {
  20901. static get type() {
  20902. return 'ScriptableValueNode';
  20903. }
  20904. /**
  20905. * Constructs a new scriptable node.
  20906. *
  20907. * @param {Any} [value=null] - The value.
  20908. */
  20909. constructor( value = null ) {
  20910. super();
  20911. /**
  20912. * A reference to the value.
  20913. *
  20914. * @private
  20915. * @default null
  20916. */
  20917. this._value = value;
  20918. /**
  20919. * Depending on the type of `_value`, this property might cache parsed data.
  20920. *
  20921. * @private
  20922. * @default null
  20923. */
  20924. this._cache = null;
  20925. /**
  20926. * If this node represents an input, this property represents the input type.
  20927. *
  20928. * @type {String?}
  20929. * @default null
  20930. */
  20931. this.inputType = null;
  20932. /**
  20933. * If this node represents an output, this property represents the output type.
  20934. *
  20935. * @type {String?}
  20936. * @default null
  20937. */
  20938. this.outputType = null;
  20939. /**
  20940. * An event dispatcher for managing events.
  20941. *
  20942. * @type {EventDispatcher}
  20943. */
  20944. this.events = new EventDispatcher();
  20945. /**
  20946. * This flag can be used for type testing.
  20947. *
  20948. * @type {Boolean}
  20949. * @readonly
  20950. * @default true
  20951. */
  20952. this.isScriptableValueNode = true;
  20953. }
  20954. /**
  20955. * Whether this node represents an output or not.
  20956. *
  20957. * @type {Boolean}
  20958. * @readonly
  20959. * @default true
  20960. */
  20961. get isScriptableOutputNode() {
  20962. return this.outputType !== null;
  20963. }
  20964. set value( val ) {
  20965. if ( this._value === val ) return;
  20966. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  20967. URL.revokeObjectURL( this._cache );
  20968. this._cache = null;
  20969. }
  20970. this._value = val;
  20971. this.events.dispatchEvent( { type: 'change' } );
  20972. this.refresh();
  20973. }
  20974. /**
  20975. * The node's value.
  20976. *
  20977. * @type {Any}
  20978. */
  20979. get value() {
  20980. return this._value;
  20981. }
  20982. /**
  20983. * Dispatches the `refresh` event.
  20984. */
  20985. refresh() {
  20986. this.events.dispatchEvent( { type: 'refresh' } );
  20987. }
  20988. /**
  20989. * The `value` property usually represents a node or even binary data in form of array buffers.
  20990. * In this case, this method tries to return the actual value behind the complex type.
  20991. *
  20992. * @return {Any} The value.
  20993. */
  20994. getValue() {
  20995. const value = this.value;
  20996. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  20997. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  20998. } else if ( value && value.value !== null && value.value !== undefined && (
  20999. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  21000. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  21001. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  21002. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  21003. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  21004. ( this.inputType === 'Color' && value.value.isColor ) ||
  21005. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  21006. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  21007. ) ) {
  21008. return value.value;
  21009. }
  21010. return this._cache || value;
  21011. }
  21012. /**
  21013. * Overwritten since the node type is inferred from the value.
  21014. *
  21015. * @param {NodeBuilder} builder - The current node builder.
  21016. * @return {String} The node type.
  21017. */
  21018. getNodeType( builder ) {
  21019. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  21020. }
  21021. setup() {
  21022. return this.value && this.value.isNode ? this.value : float();
  21023. }
  21024. serialize( data ) {
  21025. super.serialize( data );
  21026. if ( this.value !== null ) {
  21027. if ( this.inputType === 'ArrayBuffer' ) {
  21028. data.value = arrayBufferToBase64( this.value );
  21029. } else {
  21030. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  21031. }
  21032. } else {
  21033. data.value = null;
  21034. }
  21035. data.inputType = this.inputType;
  21036. data.outputType = this.outputType;
  21037. }
  21038. deserialize( data ) {
  21039. super.deserialize( data );
  21040. let value = null;
  21041. if ( data.value !== null ) {
  21042. if ( data.inputType === 'ArrayBuffer' ) {
  21043. value = base64ToArrayBuffer( data.value );
  21044. } else if ( data.inputType === 'Texture' ) {
  21045. value = data.meta.textures[ data.value ];
  21046. } else {
  21047. value = data.meta.nodes[ data.value ] || null;
  21048. }
  21049. }
  21050. this.value = value;
  21051. this.inputType = data.inputType;
  21052. this.outputType = data.outputType;
  21053. }
  21054. }
  21055. /**
  21056. * TSL function for creating a scriptable value node.
  21057. *
  21058. * @function
  21059. * @param {Any} [value=null] - The value.
  21060. * @returns {ScriptableValueNode}
  21061. */
  21062. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  21063. /**
  21064. * A Map-like data structure for managing resources of scriptable nodes.
  21065. *
  21066. * @augments Map
  21067. */
  21068. class Resources extends Map {
  21069. get( key, callback = null, ...params ) {
  21070. if ( this.has( key ) ) return super.get( key );
  21071. if ( callback !== null ) {
  21072. const value = callback( ...params );
  21073. this.set( key, value );
  21074. return value;
  21075. }
  21076. }
  21077. }
  21078. class Parameters {
  21079. constructor( scriptableNode ) {
  21080. this.scriptableNode = scriptableNode;
  21081. }
  21082. get parameters() {
  21083. return this.scriptableNode.parameters;
  21084. }
  21085. get layout() {
  21086. return this.scriptableNode.getLayout();
  21087. }
  21088. getInputLayout( id ) {
  21089. return this.scriptableNode.getInputLayout( id );
  21090. }
  21091. get( name ) {
  21092. const param = this.parameters[ name ];
  21093. const value = param ? param.getValue() : null;
  21094. return value;
  21095. }
  21096. }
  21097. /**
  21098. * Defines the resouces (e.g. namespaces) of scriptable nodes.
  21099. *
  21100. * @type {Resources}
  21101. */
  21102. const ScriptableNodeResources = new Resources();
  21103. /**
  21104. * This type of node allows to implement nodes with custom scripts. The script
  21105. * section is represented as an instance of `CodeNode` written with JavaScript.
  21106. * The script itself must adhere to a specific structure.
  21107. *
  21108. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  21109. * - layout: The layout object defines the script's interface (inputs and outputs).
  21110. *
  21111. * ```js
  21112. * ScriptableNodeResources.set( 'TSL', TSL );
  21113. *
  21114. * const scriptableNode = scriptable( js( `
  21115. * layout = {
  21116. * outputType: 'node',
  21117. * elements: [
  21118. * { name: 'source', inputType: 'node' },
  21119. * ]
  21120. * };
  21121. *
  21122. * const { mul, oscSine } = TSL;
  21123. *
  21124. * function main() {
  21125. * const source = parameters.get( 'source' ) || float();
  21126. * return mul( source, oscSine() ) );
  21127. * }
  21128. *
  21129. * ` ) );
  21130. *
  21131. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  21132. *
  21133. * const material = new THREE.MeshBasicNodeMaterial();
  21134. * material.colorNode = scriptableNode;
  21135. * ```
  21136. *
  21137. * @augments Node
  21138. */
  21139. class ScriptableNode extends Node {
  21140. static get type() {
  21141. return 'ScriptableNode';
  21142. }
  21143. /**
  21144. * Constructs a new scriptable node.
  21145. *
  21146. * @param {CodeNode?} [codeNode=null] - The code node.
  21147. * @param {Object} [parameters={}] - The parameters definition.
  21148. */
  21149. constructor( codeNode = null, parameters = {} ) {
  21150. super();
  21151. /**
  21152. * The code node.
  21153. *
  21154. * @type {CodeNode?}
  21155. * @default null
  21156. */
  21157. this.codeNode = codeNode;
  21158. /**
  21159. * The parameters definition.
  21160. *
  21161. * @type {Object}
  21162. * @default {}
  21163. */
  21164. this.parameters = parameters;
  21165. this._local = new Resources();
  21166. this._output = scriptableValue();
  21167. this._outputs = {};
  21168. this._source = this.source;
  21169. this._method = null;
  21170. this._object = null;
  21171. this._value = null;
  21172. this._needsOutputUpdate = true;
  21173. this.onRefresh = this.onRefresh.bind( this );
  21174. /**
  21175. * This flag can be used for type testing.
  21176. *
  21177. * @type {Boolean}
  21178. * @readonly
  21179. * @default true
  21180. */
  21181. this.isScriptableNode = true;
  21182. }
  21183. /**
  21184. * The source code of the scriptable node.
  21185. *
  21186. * @type {String}
  21187. */
  21188. get source() {
  21189. return this.codeNode ? this.codeNode.code : '';
  21190. }
  21191. /**
  21192. * Sets the reference of a local script variable.
  21193. *
  21194. * @param {String} name - The variable name.
  21195. * @param {Object} value - The reference to set.
  21196. * @return {Resources} The resource map
  21197. */
  21198. setLocal( name, value ) {
  21199. return this._local.set( name, value );
  21200. }
  21201. /**
  21202. * Gets the value of a local script variable.
  21203. *
  21204. * @param {String} name - The variable name.
  21205. * @return {Object} The value.
  21206. */
  21207. getLocal( name ) {
  21208. return this._local.get( name );
  21209. }
  21210. /**
  21211. * Event listener for the `refresh` event.
  21212. */
  21213. onRefresh() {
  21214. this._refresh();
  21215. }
  21216. /**
  21217. * Returns an input from the layout with the given id/name.
  21218. *
  21219. * @param {String} id - The id/name of the input.
  21220. * @return {Object} The element entry.
  21221. */
  21222. getInputLayout( id ) {
  21223. for ( const element of this.getLayout() ) {
  21224. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  21225. return element;
  21226. }
  21227. }
  21228. }
  21229. /**
  21230. * Returns an output from the layout with the given id/name.
  21231. *
  21232. * @param {String} id - The id/name of the output.
  21233. * @return {Object} The element entry.
  21234. */
  21235. getOutputLayout( id ) {
  21236. for ( const element of this.getLayout() ) {
  21237. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  21238. return element;
  21239. }
  21240. }
  21241. }
  21242. /**
  21243. * Defines a script output for the given name and value.
  21244. *
  21245. * @param {String} name - The name of the output.
  21246. * @param {Node} value - The node value.
  21247. * @return {ScriptableNode} A reference to this node.
  21248. */
  21249. setOutput( name, value ) {
  21250. const outputs = this._outputs;
  21251. if ( outputs[ name ] === undefined ) {
  21252. outputs[ name ] = scriptableValue( value );
  21253. } else {
  21254. outputs[ name ].value = value;
  21255. }
  21256. return this;
  21257. }
  21258. /**
  21259. * Returns a script output for the given name.
  21260. *
  21261. * @param {String} name - The name of the output.
  21262. * @return {ScriptableValueNode} The node value.
  21263. */
  21264. getOutput( name ) {
  21265. return this._outputs[ name ];
  21266. }
  21267. /**
  21268. * Returns a paramater for the given name
  21269. *
  21270. * @param {String} name - The name of the parameter.
  21271. * @return {ScriptableValueNode} The node value.
  21272. */
  21273. getParameter( name ) {
  21274. return this.parameters[ name ];
  21275. }
  21276. /**
  21277. * Sets a value for the given parameter name.
  21278. *
  21279. * @param {String} name - The parameter name.
  21280. * @param {Any} value - The parameter value.
  21281. * @return {ScriptableNode} A reference to this node.
  21282. */
  21283. setParameter( name, value ) {
  21284. const parameters = this.parameters;
  21285. if ( value && value.isScriptableNode ) {
  21286. this.deleteParameter( name );
  21287. parameters[ name ] = value;
  21288. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  21289. } else if ( value && value.isScriptableValueNode ) {
  21290. this.deleteParameter( name );
  21291. parameters[ name ] = value;
  21292. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  21293. } else if ( parameters[ name ] === undefined ) {
  21294. parameters[ name ] = scriptableValue( value );
  21295. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  21296. } else {
  21297. parameters[ name ].value = value;
  21298. }
  21299. return this;
  21300. }
  21301. /**
  21302. * Returns the value of this node which is the value of
  21303. * the default output.
  21304. *
  21305. * @return {Node} The value.
  21306. */
  21307. getValue() {
  21308. return this.getDefaultOutput().getValue();
  21309. }
  21310. /**
  21311. * Deletes a parameter from the script.
  21312. *
  21313. * @param {String} name - The parameter to remove.
  21314. * @return {ScriptableNode} A reference to this node.
  21315. */
  21316. deleteParameter( name ) {
  21317. let valueNode = this.parameters[ name ];
  21318. if ( valueNode ) {
  21319. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  21320. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  21321. }
  21322. return this;
  21323. }
  21324. /**
  21325. * Deletes all parameters from the script.
  21326. *
  21327. * @return {ScriptableNode} A reference to this node.
  21328. */
  21329. clearParameters() {
  21330. for ( const name of Object.keys( this.parameters ) ) {
  21331. this.deleteParameter( name );
  21332. }
  21333. this.needsUpdate = true;
  21334. return this;
  21335. }
  21336. /**
  21337. * Calls a function from the script.
  21338. *
  21339. * @param {String} name - The function name.
  21340. * @param {...Any} params - A list of parameters.
  21341. * @return {Any} The result of the function call.
  21342. */
  21343. call( name, ...params ) {
  21344. const object = this.getObject();
  21345. const method = object[ name ];
  21346. if ( typeof method === 'function' ) {
  21347. return method( ...params );
  21348. }
  21349. }
  21350. /**
  21351. * Asynchronously calls a function from the script.
  21352. *
  21353. * @param {String} name - The function name.
  21354. * @param {...Any} params - A list of parameters.
  21355. * @return {Any} The result of the function call.
  21356. */
  21357. async callAsync( name, ...params ) {
  21358. const object = this.getObject();
  21359. const method = object[ name ];
  21360. if ( typeof method === 'function' ) {
  21361. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  21362. }
  21363. }
  21364. /**
  21365. * Overwritten since the node types is inferred from the script's output.
  21366. *
  21367. * @param {NodeBuilder} builder - The current node builder
  21368. * @return {String} The node type.
  21369. */
  21370. getNodeType( builder ) {
  21371. return this.getDefaultOutputNode().getNodeType( builder );
  21372. }
  21373. /**
  21374. * Refreshes the script node.
  21375. *
  21376. * @param {String?} [output=null] - An optional output.
  21377. */
  21378. refresh( output = null ) {
  21379. if ( output !== null ) {
  21380. this.getOutput( output ).refresh();
  21381. } else {
  21382. this._refresh();
  21383. }
  21384. }
  21385. /**
  21386. * Returns an object representation of the script.
  21387. *
  21388. * @return {Object} The result object.
  21389. */
  21390. getObject() {
  21391. if ( this.needsUpdate ) this.dispose();
  21392. if ( this._object !== null ) return this._object;
  21393. //
  21394. const refresh = () => this.refresh();
  21395. const setOutput = ( id, value ) => this.setOutput( id, value );
  21396. const parameters = new Parameters( this );
  21397. const THREE = ScriptableNodeResources.get( 'THREE' );
  21398. const TSL = ScriptableNodeResources.get( 'TSL' );
  21399. const method = this.getMethod();
  21400. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  21401. this._object = method( ...params );
  21402. const layout = this._object.layout;
  21403. if ( layout ) {
  21404. if ( layout.cache === false ) {
  21405. this._local.clear();
  21406. }
  21407. // default output
  21408. this._output.outputType = layout.outputType || null;
  21409. if ( Array.isArray( layout.elements ) ) {
  21410. for ( const element of layout.elements ) {
  21411. const id = element.id || element.name;
  21412. if ( element.inputType ) {
  21413. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  21414. this.getParameter( id ).inputType = element.inputType;
  21415. }
  21416. if ( element.outputType ) {
  21417. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  21418. this.getOutput( id ).outputType = element.outputType;
  21419. }
  21420. }
  21421. }
  21422. }
  21423. return this._object;
  21424. }
  21425. deserialize( data ) {
  21426. super.deserialize( data );
  21427. for ( const name in this.parameters ) {
  21428. let valueNode = this.parameters[ name ];
  21429. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  21430. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  21431. }
  21432. }
  21433. /**
  21434. * Returns the layout of the script.
  21435. *
  21436. * @return {Object} The script's layout.
  21437. */
  21438. getLayout() {
  21439. return this.getObject().layout;
  21440. }
  21441. /**
  21442. * Returns default node output of the script.
  21443. *
  21444. * @return {Node} The default node output.
  21445. */
  21446. getDefaultOutputNode() {
  21447. const output = this.getDefaultOutput().value;
  21448. if ( output && output.isNode ) {
  21449. return output;
  21450. }
  21451. return float();
  21452. }
  21453. /**
  21454. * Returns default output of the script.
  21455. *
  21456. * @return {ScriptableValueNode} The default output.
  21457. */
  21458. getDefaultOutput() {
  21459. return this._exec()._output;
  21460. }
  21461. /**
  21462. * Returns a function created from the node's script.
  21463. *
  21464. * @return {Function} The function representing the node's code.
  21465. */
  21466. getMethod() {
  21467. if ( this.needsUpdate ) this.dispose();
  21468. if ( this._method !== null ) return this._method;
  21469. //
  21470. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  21471. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  21472. const properties = interfaceProps.join( ', ' );
  21473. const declarations = 'var ' + properties + '; var output = {};\n';
  21474. const returns = '\nreturn { ...output, ' + properties + ' };';
  21475. const code = declarations + this.codeNode.code + returns;
  21476. //
  21477. this._method = new Function( ...parametersProps, code );
  21478. return this._method;
  21479. }
  21480. /**
  21481. * Frees all internal resources.
  21482. */
  21483. dispose() {
  21484. if ( this._method === null ) return;
  21485. if ( this._object && typeof this._object.dispose === 'function' ) {
  21486. this._object.dispose();
  21487. }
  21488. this._method = null;
  21489. this._object = null;
  21490. this._source = null;
  21491. this._value = null;
  21492. this._needsOutputUpdate = true;
  21493. this._output.value = null;
  21494. this._outputs = {};
  21495. }
  21496. setup() {
  21497. return this.getDefaultOutputNode();
  21498. }
  21499. getCacheKey( force ) {
  21500. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  21501. for ( const param in this.parameters ) {
  21502. values.push( this.parameters[ param ].getCacheKey( force ) );
  21503. }
  21504. return hashArray( values );
  21505. }
  21506. set needsUpdate( value ) {
  21507. if ( value === true ) this.dispose();
  21508. }
  21509. get needsUpdate() {
  21510. return this.source !== this._source;
  21511. }
  21512. /**
  21513. * Executes the `main` function of the script.
  21514. *
  21515. * @private
  21516. * @return {ScriptableNode} A reference to this node.
  21517. */
  21518. _exec() {
  21519. if ( this.codeNode === null ) return this;
  21520. if ( this._needsOutputUpdate === true ) {
  21521. this._value = this.call( 'main' );
  21522. this._needsOutputUpdate = false;
  21523. }
  21524. this._output.value = this._value;
  21525. return this;
  21526. }
  21527. /**
  21528. * Executes the refresh.
  21529. *
  21530. * @private
  21531. */
  21532. _refresh() {
  21533. this.needsUpdate = true;
  21534. this._exec();
  21535. this._output.refresh();
  21536. }
  21537. }
  21538. /**
  21539. * TSL function for creating a scriptable node.
  21540. *
  21541. * @function
  21542. * @param {CodeNode?} [codeNode=null] - The code node.
  21543. * @param {Object} [parameters={}] - The parameters definition.
  21544. * @returns {ScriptableNode}
  21545. */
  21546. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  21547. /** @module Fog **/
  21548. /**
  21549. * Returns a node that represents the `z` coordinate in view space
  21550. * for the current fragment. It's a different representation of the
  21551. * default depth value.
  21552. *
  21553. * This value can be part of a computation that defines how the fog
  21554. * density increases when moving away from the camera.
  21555. *
  21556. * @param {NodeBuilder} builder - The current node builder.
  21557. * @return {Node} The viewZ node.
  21558. */
  21559. function getViewZNode( builder ) {
  21560. let viewZ;
  21561. const getViewZ = builder.context.getViewZ;
  21562. if ( getViewZ !== undefined ) {
  21563. viewZ = getViewZ( this );
  21564. }
  21565. return ( viewZ || positionView.z ).negate();
  21566. }
  21567. /**
  21568. * Constructs a new range factor node.
  21569. *
  21570. * @param {Node} near - Defines the near value.
  21571. * @param {Node} far - Defines the far value.
  21572. */
  21573. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  21574. const viewZ = getViewZNode( builder );
  21575. return smoothstep( near, far, viewZ );
  21576. } );
  21577. /**
  21578. * Represents an exponential squared fog. This type of fog gives
  21579. * a clear view near the camera and a faster than exponentially
  21580. * densening fog farther from the camera.
  21581. *
  21582. * @param {Node} density - Defines the fog density.
  21583. */
  21584. const densityFogFactor = Fn( ( [ density ], builder ) => {
  21585. const viewZ = getViewZNode( builder );
  21586. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  21587. } );
  21588. /**
  21589. * This class can be used to configure a fog for the scene.
  21590. * Nodes of this type are assigned to `Scene.fogNode`.
  21591. *
  21592. * @param {Node} color - Defines the color of the fog.
  21593. * @param {Node} factor - Defines how the fog is factored in the scene.
  21594. */
  21595. const fog = Fn( ( [ color, factor ] ) => {
  21596. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  21597. } );
  21598. // Deprecated
  21599. function rangeFog( color, near, far ) { // @deprecated, r171
  21600. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  21601. return fog( color, rangeFogFactor( near, far ) );
  21602. }
  21603. function densityFog( color, density ) { // @deprecated, r171
  21604. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  21605. return fog( color, densityFogFactor( density ) );
  21606. }
  21607. /** @module RangeNode **/
  21608. let min = null;
  21609. let max = null;
  21610. /**
  21611. * `RangeNode` generates random instanced attribute data in a defined range.
  21612. * An exemplary use case for this utility node is to generate random per-instance
  21613. * colors:
  21614. * ```js
  21615. * const material = new MeshBasicNodeMaterial();
  21616. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  21617. * const mesh = new InstancedMesh( geometry, material, count );
  21618. * ```
  21619. * @augments Node
  21620. */
  21621. class RangeNode extends Node {
  21622. static get type() {
  21623. return 'RangeNode';
  21624. }
  21625. /**
  21626. * Constructs a new range node.
  21627. *
  21628. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  21629. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  21630. */
  21631. constructor( minNode = float(), maxNode = float() ) {
  21632. super();
  21633. /**
  21634. * A node defining the lower bound of the range.
  21635. *
  21636. * @type {Node<any>}
  21637. * @default float()
  21638. */
  21639. this.minNode = minNode;
  21640. /**
  21641. * A node defining the upper bound of the range.
  21642. *
  21643. * @type {Node<any>}
  21644. * @default float()
  21645. */
  21646. this.maxNode = maxNode;
  21647. }
  21648. /**
  21649. * Returns the vector length which is computed based on the range definition.
  21650. *
  21651. * @param {NodeBuilder} builder - The current node builder.
  21652. * @return {Number} The vector length.
  21653. */
  21654. getVectorLength( builder ) {
  21655. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  21656. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  21657. return minLength > maxLength ? minLength : maxLength;
  21658. }
  21659. /**
  21660. * This method is overwritten since the node type is inferred from range definition.
  21661. *
  21662. * @param {NodeBuilder} builder - The current node builder.
  21663. * @return {String} The node type.
  21664. */
  21665. getNodeType( builder ) {
  21666. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  21667. }
  21668. setup( builder ) {
  21669. const object = builder.object;
  21670. let output = null;
  21671. if ( object.count > 1 ) {
  21672. const minValue = this.minNode.value;
  21673. const maxValue = this.maxNode.value;
  21674. const minLength = builder.getTypeLength( getValueType( minValue ) );
  21675. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  21676. min = min || new Vector4();
  21677. max = max || new Vector4();
  21678. min.setScalar( 0 );
  21679. max.setScalar( 0 );
  21680. if ( minLength === 1 ) min.setScalar( minValue );
  21681. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  21682. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  21683. if ( maxLength === 1 ) max.setScalar( maxValue );
  21684. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  21685. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  21686. const stride = 4;
  21687. const length = stride * object.count;
  21688. const array = new Float32Array( length );
  21689. for ( let i = 0; i < length; i ++ ) {
  21690. const index = i % stride;
  21691. const minElementValue = min.getComponent( index );
  21692. const maxElementValue = max.getComponent( index );
  21693. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  21694. }
  21695. const nodeType = this.getNodeType( builder );
  21696. if ( object.count <= 4096 ) {
  21697. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  21698. } else {
  21699. // TODO: Improve anonymous buffer attribute creation removing this part
  21700. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  21701. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  21702. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  21703. }
  21704. } else {
  21705. output = float( 0 );
  21706. }
  21707. return output;
  21708. }
  21709. }
  21710. /**
  21711. * TSL function for creating a range node.
  21712. *
  21713. * @function
  21714. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  21715. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  21716. * @returns {RangeNode}
  21717. */
  21718. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  21719. /** @module ComputeBuiltinNode **/
  21720. /**
  21721. * TODO
  21722. *
  21723. * @augments Node
  21724. */
  21725. class ComputeBuiltinNode extends Node {
  21726. static get type() {
  21727. return 'ComputeBuiltinNode';
  21728. }
  21729. /**
  21730. * Constructs a new compute builtin node.
  21731. *
  21732. * @param {String} builtinName - The built-in name.
  21733. * @param {String} nodeType - The node type.
  21734. */
  21735. constructor( builtinName, nodeType ) {
  21736. super( nodeType );
  21737. /**
  21738. * The built-in name.
  21739. *
  21740. * @private
  21741. * @type {String}
  21742. */
  21743. this._builtinName = builtinName;
  21744. }
  21745. /**
  21746. * This method is overwritten since hash is derived from the built-in name.
  21747. *
  21748. * @param {NodeBuilder} builder - The current node builder.
  21749. * @return {String} The hash.
  21750. */
  21751. getHash( builder ) {
  21752. return this.getBuiltinName( builder );
  21753. }
  21754. /**
  21755. * This method is overwritten since the node type is simply derived from `nodeType`..
  21756. *
  21757. * @param {NodeBuilder} builder - The current node builder.
  21758. * @return {String} The node type.
  21759. */
  21760. getNodeType( /*builder*/ ) {
  21761. return this.nodeType;
  21762. }
  21763. /**
  21764. * Sets the builtin name.
  21765. *
  21766. * @param {String} builtinName - The built-in name.
  21767. * @return {ComputeBuiltinNode} A reference to this node.
  21768. */
  21769. setBuiltinName( builtinName ) {
  21770. this._builtinName = builtinName;
  21771. return this;
  21772. }
  21773. /**
  21774. * Returns the builtin name.
  21775. *
  21776. * @param {NodeBuilder} builder - The current node builder.
  21777. * @return {String} The builtin name.
  21778. */
  21779. getBuiltinName( /*builder*/ ) {
  21780. return this._builtinName;
  21781. }
  21782. /**
  21783. * Whether the current node builder has the builtin or not.
  21784. *
  21785. * @param {NodeBuilder} builder - The current node builder.
  21786. */
  21787. hasBuiltin( builder ) {
  21788. builder.hasBuiltin( this._builtinName );
  21789. }
  21790. generate( builder, output ) {
  21791. const builtinName = this.getBuiltinName( builder );
  21792. const nodeType = this.getNodeType( builder );
  21793. if ( builder.shaderStage === 'compute' ) {
  21794. return builder.format( builtinName, nodeType, output );
  21795. } else {
  21796. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  21797. return builder.generateConst( nodeType );
  21798. }
  21799. }
  21800. serialize( data ) {
  21801. super.serialize( data );
  21802. data.global = this.global;
  21803. data._builtinName = this._builtinName;
  21804. }
  21805. deserialize( data ) {
  21806. super.deserialize( data );
  21807. this.global = data.global;
  21808. this._builtinName = data._builtinName;
  21809. }
  21810. }
  21811. /**
  21812. * TSL function for creating a compute builtin node.
  21813. *
  21814. * @function
  21815. * @param {String} name - The built-in name.
  21816. * @param {String} nodeType - The node type.
  21817. * @returns {ComputeBuiltinNode}
  21818. */
  21819. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  21820. /**
  21821. * TSL function for creating a `numWorkgroups` builtin node.
  21822. *
  21823. * @function
  21824. * @returns {ComputeBuiltinNode<uvec3>}
  21825. */
  21826. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  21827. /**
  21828. * TSL function for creating a `workgroupId` builtin node.
  21829. *
  21830. * @function
  21831. * @returns {ComputeBuiltinNode<uvec3>}
  21832. */
  21833. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  21834. /**
  21835. * TSL function for creating a `localId` builtin node.
  21836. *
  21837. * @function
  21838. * @returns {ComputeBuiltinNode<uvec3>}
  21839. */
  21840. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  21841. /**
  21842. * TSL function for creating a `subgroupSize` builtin node.
  21843. *
  21844. * @function
  21845. * @returns {ComputeBuiltinNode<uint>}
  21846. */
  21847. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  21848. /** @module BarrierNode **/
  21849. /**
  21850. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  21851. *
  21852. * @augments Node
  21853. */
  21854. class BarrierNode extends Node {
  21855. /**
  21856. * Constructs a new barrier node.
  21857. *
  21858. * @param {String} scope - The scope defines the behavior of the node.
  21859. */
  21860. constructor( scope ) {
  21861. super();
  21862. this.scope = scope;
  21863. }
  21864. generate( builder ) {
  21865. const { scope } = this;
  21866. const { renderer } = builder;
  21867. if ( renderer.backend.isWebGLBackend === true ) {
  21868. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  21869. } else {
  21870. builder.addLineFlowCode( `${scope}Barrier()`, this );
  21871. }
  21872. }
  21873. }
  21874. /**
  21875. * TSL function for creating a barrier node.
  21876. *
  21877. * @function
  21878. * @param {String} scope - The scope defines the behavior of the node..
  21879. * @returns {BarrierNode}
  21880. */
  21881. const barrier = nodeProxy( BarrierNode );
  21882. /**
  21883. * TSL function for creating a workgroup barrier. All compute shader
  21884. * invocations must wait for each invocation within a workgroup to
  21885. * complete before the barrier can be surpassed.
  21886. *
  21887. * @function
  21888. * @returns {BarrierNode}
  21889. */
  21890. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  21891. /**
  21892. * TSL function for creating a storage barrier. All invocations must
  21893. * wait for each access to variables within the 'storage' address space
  21894. * to complete before the barrier can be passed.
  21895. *
  21896. * @function
  21897. * @returns {BarrierNode}
  21898. */
  21899. const storageBarrier = () => barrier( 'storage' ).append();
  21900. /**
  21901. * TSL function for creating a texture barrier. All invocations must
  21902. * wait for each access to variables within the 'texture' address space
  21903. * to complete before the barrier can be passed.
  21904. *
  21905. * @function
  21906. * @returns {BarrierNode}
  21907. */
  21908. const textureBarrier = () => barrier( 'texture' ).append();
  21909. /** @module WorkgroupInfoNode **/
  21910. /**
  21911. * TODO
  21912. *
  21913. * @augments ArrayElementNode
  21914. */
  21915. class WorkgroupInfoElementNode extends ArrayElementNode {
  21916. /**
  21917. * Constructs a new workgroup info element node.
  21918. *
  21919. * @param {Node} workgroupInfoNode - The workgroup info node.
  21920. * @param {Node} indexNode - The index node that defines the element access.
  21921. */
  21922. constructor( workgroupInfoNode, indexNode ) {
  21923. super( workgroupInfoNode, indexNode );
  21924. /**
  21925. * This flag can be used for type testing.
  21926. *
  21927. * @type {Boolean}
  21928. * @readonly
  21929. * @default true
  21930. */
  21931. this.isWorkgroupInfoElementNode = true;
  21932. }
  21933. generate( builder, output ) {
  21934. let snippet;
  21935. const isAssignContext = builder.context.assign;
  21936. snippet = super.generate( builder );
  21937. if ( isAssignContext !== true ) {
  21938. const type = this.getNodeType( builder );
  21939. snippet = builder.format( snippet, type, output );
  21940. }
  21941. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  21942. return snippet;
  21943. }
  21944. }
  21945. /**
  21946. * TODO
  21947. *
  21948. * @augments Node
  21949. */
  21950. class WorkgroupInfoNode extends Node {
  21951. /**
  21952. * Constructs a new workgroup info node.
  21953. *
  21954. * @param {String} scope - TODO.
  21955. * @param {String} bufferType - The buffer type.
  21956. * @param {Number} [bufferCount=0] - The buffer count.
  21957. */
  21958. constructor( scope, bufferType, bufferCount = 0 ) {
  21959. super( bufferType );
  21960. /**
  21961. * The buffer type.
  21962. *
  21963. * @type {String}
  21964. */
  21965. this.bufferType = bufferType;
  21966. /**
  21967. * The buffer count.
  21968. *
  21969. * @type {Number}
  21970. * @default 0
  21971. */
  21972. this.bufferCount = bufferCount;
  21973. /**
  21974. * This flag can be used for type testing.
  21975. *
  21976. * @type {Boolean}
  21977. * @readonly
  21978. * @default true
  21979. */
  21980. this.isWorkgroupInfoNode = true;
  21981. /**
  21982. * TODO.
  21983. *
  21984. * @type {String}
  21985. */
  21986. this.scope = scope;
  21987. }
  21988. /**
  21989. * Sets the name/label of this node.
  21990. *
  21991. * @param {String} name - The name to set.
  21992. * @return {WorkgroupInfoNode} A reference to this node.
  21993. */
  21994. label( name ) {
  21995. this.name = name;
  21996. return this;
  21997. }
  21998. /**
  21999. * Sets the scope of this node.
  22000. *
  22001. * @param {String} scope - The scope to set.
  22002. * @return {WorkgroupInfoNode} A reference to this node.
  22003. */
  22004. setScope( scope ) {
  22005. this.scope = scope;
  22006. return this;
  22007. }
  22008. /**
  22009. * Overwrites the default implementation since the input type
  22010. * is inferred from the scope.
  22011. *
  22012. * @param {NodeBuilder} builder - The current node builder.
  22013. * @return {String} The input type.
  22014. */
  22015. getInputType( /*builder*/ ) {
  22016. return `${this.scope}Array`;
  22017. }
  22018. /**
  22019. * This method can be used to access elements via an index node.
  22020. *
  22021. * @param {IndexNode} indexNode - indexNode.
  22022. * @return {WorkgroupInfoElementNode} A reference to an element.
  22023. */
  22024. element( indexNode ) {
  22025. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  22026. }
  22027. generate( builder ) {
  22028. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  22029. }
  22030. }
  22031. /**
  22032. * TSL function for creating a workgroup info node.
  22033. *
  22034. * @function
  22035. * @param {String} type - The buffer type.
  22036. * @param {Number} [count=0] - The buffer count.
  22037. * @returns {WorkgroupInfoNode}
  22038. */
  22039. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  22040. /** @module AtomicFunctionNode **/
  22041. /**
  22042. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  22043. * within a shader. In an atomic function, any modifiation to an atomic variable will
  22044. * occur as an indivisble step with a defined order relative to other modifications.
  22045. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  22046. * atomic operations will not interfer with each other.
  22047. *
  22048. * @augments TempNode
  22049. */
  22050. class AtomicFunctionNode extends TempNode {
  22051. static get type() {
  22052. return 'AtomicFunctionNode';
  22053. }
  22054. /**
  22055. * Constructs a new atomic function node.
  22056. *
  22057. * @param {String} method - The signature of the atomic function to construct.
  22058. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22059. * @param {Node} valueNode - The value that mutates the atomic variable.
  22060. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22061. */
  22062. constructor( method, pointerNode, valueNode, storeNode = null ) {
  22063. super( 'uint' );
  22064. /**
  22065. * The signature of the atomic function to construct.
  22066. *
  22067. * @type {String}
  22068. */
  22069. this.method = method;
  22070. /**
  22071. * An atomic variable or element of an atomic buffer.
  22072. *
  22073. * @type {Node}
  22074. */
  22075. this.pointerNode = pointerNode;
  22076. /**
  22077. * A value that modifies the atomic variable.
  22078. *
  22079. * @type {Node}
  22080. */
  22081. this.valueNode = valueNode;
  22082. /**
  22083. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22084. *
  22085. * @type {Node?}
  22086. * @default null
  22087. */
  22088. this.storeNode = storeNode;
  22089. }
  22090. /**
  22091. * Overwrites the default implementation to return the type of
  22092. * the pointer node.
  22093. *
  22094. * @param {NodeBuilder} builder - The current node builder.
  22095. * @return {String} The input type.
  22096. */
  22097. getInputType( builder ) {
  22098. return this.pointerNode.getNodeType( builder );
  22099. }
  22100. /**
  22101. * Overwritten since the node type is inferred from the input type.
  22102. *
  22103. * @param {NodeBuilder} builder - The current node builder.
  22104. * @return {String} The node type.
  22105. */
  22106. getNodeType( builder ) {
  22107. return this.getInputType( builder );
  22108. }
  22109. generate( builder ) {
  22110. const method = this.method;
  22111. const type = this.getNodeType( builder );
  22112. const inputType = this.getInputType( builder );
  22113. const a = this.pointerNode;
  22114. const b = this.valueNode;
  22115. const params = [];
  22116. params.push( `&${ a.build( builder, inputType ) }` );
  22117. params.push( b.build( builder, inputType ) );
  22118. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  22119. if ( this.storeNode !== null ) {
  22120. const varSnippet = this.storeNode.build( builder, inputType );
  22121. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  22122. } else {
  22123. builder.addLineFlowCode( methodSnippet, this );
  22124. }
  22125. }
  22126. }
  22127. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  22128. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  22129. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  22130. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  22131. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  22132. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  22133. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  22134. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  22135. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  22136. /**
  22137. * TSL function for creating an atomic function node.
  22138. *
  22139. * @function
  22140. * @param {String} method - The signature of the atomic function to construct.
  22141. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22142. * @param {Node} valueNode - The value that mutates the atomic variable.
  22143. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22144. * @returns {AtomicFunctionNode}
  22145. */
  22146. const atomicNode = nodeProxy( AtomicFunctionNode );
  22147. /**
  22148. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  22149. *
  22150. * @function
  22151. * @param {String} method - The signature of the atomic function to construct.
  22152. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22153. * @param {Node} valueNode - The value that mutates the atomic variable.
  22154. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22155. * @returns {AtomicFunctionNode}
  22156. */
  22157. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  22158. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  22159. node.append();
  22160. return node;
  22161. };
  22162. /**
  22163. * Stores a value in the atomic variable.
  22164. *
  22165. * @function
  22166. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22167. * @param {Node} valueNode - The value that mutates the atomic variable.
  22168. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22169. * @returns {AtomicFunctionNode}
  22170. */
  22171. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  22172. /**
  22173. * Increments the value stored in the atomic variable.
  22174. *
  22175. * @function
  22176. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22177. * @param {Node} valueNode - The value that mutates the atomic variable.
  22178. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22179. * @returns {AtomicFunctionNode}
  22180. */
  22181. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  22182. /**
  22183. * Decrements the value stored in the atomic variable.
  22184. *
  22185. * @function
  22186. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22187. * @param {Node} valueNode - The value that mutates the atomic variable.
  22188. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22189. * @returns {AtomicFunctionNode}
  22190. */
  22191. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  22192. /**
  22193. * Stores in an atomic variable the maximum between its current value and a parameter.
  22194. *
  22195. * @function
  22196. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22197. * @param {Node} valueNode - The value that mutates the atomic variable.
  22198. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22199. * @returns {AtomicFunctionNode}
  22200. */
  22201. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  22202. /**
  22203. * Stores in an atomic variable the minimum between its current value and a parameter.
  22204. *
  22205. * @function
  22206. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22207. * @param {Node} valueNode - The value that mutates the atomic variable.
  22208. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22209. * @returns {AtomicFunctionNode}
  22210. */
  22211. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  22212. /**
  22213. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  22214. *
  22215. * @function
  22216. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22217. * @param {Node} valueNode - The value that mutates the atomic variable.
  22218. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22219. * @returns {AtomicFunctionNode}
  22220. */
  22221. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  22222. /**
  22223. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  22224. *
  22225. * @function
  22226. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22227. * @param {Node} valueNode - The value that mutates the atomic variable.
  22228. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22229. * @returns {AtomicFunctionNode}
  22230. */
  22231. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  22232. /**
  22233. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  22234. *
  22235. * @function
  22236. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  22237. * @param {Node} valueNode - The value that mutates the atomic variable.
  22238. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  22239. * @returns {AtomicFunctionNode}
  22240. */
  22241. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  22242. /** @module Lights **/
  22243. let uniformsLib;
  22244. function getLightData( light ) {
  22245. uniformsLib = uniformsLib || new WeakMap();
  22246. let uniforms = uniformsLib.get( light );
  22247. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  22248. return uniforms;
  22249. }
  22250. /**
  22251. * TSL function for getting a shadow matrix uniform node for the given light.
  22252. *
  22253. * @function
  22254. * @param {Light} light -The light source.
  22255. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  22256. */
  22257. function lightShadowMatrix( light ) {
  22258. const data = getLightData( light );
  22259. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  22260. if ( light.castShadow !== true ) {
  22261. light.shadow.updateMatrices( light );
  22262. }
  22263. return light.shadow.matrix;
  22264. } ) );
  22265. }
  22266. /**
  22267. * TSL function for getting projected uv coordinates for the given light.
  22268. * Relevant when using maps with spot lights.
  22269. *
  22270. * @function
  22271. * @param {Light} light -The light source.
  22272. * @returns {Node<vec3>} The projected uvs.
  22273. */
  22274. function lightProjectionUV( light ) {
  22275. const data = getLightData( light );
  22276. if ( data.projectionUV === undefined ) {
  22277. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  22278. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  22279. }
  22280. return data.projectionUV;
  22281. }
  22282. /**
  22283. * TSL function for getting the position in world space for the given light.
  22284. *
  22285. * @function
  22286. * @param {Light} light -The light source.
  22287. * @returns {UniformNode<vec3>} The light's position in world space.
  22288. */
  22289. function lightPosition( light ) {
  22290. const data = getLightData( light );
  22291. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  22292. }
  22293. /**
  22294. * TSL function for getting the light target position in world space for the given light.
  22295. *
  22296. * @function
  22297. * @param {Light} light -The light source.
  22298. * @returns {UniformNode<vec3>} The light target position in world space.
  22299. */
  22300. function lightTargetPosition( light ) {
  22301. const data = getLightData( light );
  22302. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  22303. }
  22304. /**
  22305. * TSL function for getting the position in view space for the given light.
  22306. *
  22307. * @function
  22308. * @param {Light} light -The light source.
  22309. * @returns {UniformNode<vec3>} The light's position in view space.
  22310. */
  22311. function lightViewPosition( light ) {
  22312. const data = getLightData( light );
  22313. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  22314. self.value = self.value || new Vector3();
  22315. self.value.setFromMatrixPosition( light.matrixWorld );
  22316. self.value.applyMatrix4( camera.matrixWorldInverse );
  22317. } ) );
  22318. }
  22319. /**
  22320. * TSL function for getting the light target direction for the given light.
  22321. *
  22322. * @function
  22323. * @param {Light} light -The light source.
  22324. * @returns {Node<vec3>} The light's target direction.
  22325. */
  22326. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  22327. /** @module LightsNode **/
  22328. const sortLights = ( lights ) => {
  22329. return lights.sort( ( a, b ) => a.id - b.id );
  22330. };
  22331. const getLightNodeById = ( id, lightNodes ) => {
  22332. for ( const lightNode of lightNodes ) {
  22333. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  22334. return lightNode;
  22335. }
  22336. }
  22337. return null;
  22338. };
  22339. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  22340. /**
  22341. * This node represents the scene's lighting and manages the lighting model's life cycle
  22342. * for the current build 3D object. It is responsible for computing the total outgoing
  22343. * light in a given lighting context.
  22344. *
  22345. * @augments Node
  22346. */
  22347. class LightsNode extends Node {
  22348. static get type() {
  22349. return 'LightsNode';
  22350. }
  22351. /**
  22352. * Constructs a new lights node.
  22353. */
  22354. constructor() {
  22355. super( 'vec3' );
  22356. /**
  22357. * A node representing the total diffuse light.
  22358. *
  22359. * @type {Node<vec3>}
  22360. */
  22361. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  22362. /**
  22363. * A node representing the total specular light.
  22364. *
  22365. * @type {Node<vec3>}
  22366. */
  22367. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  22368. /**
  22369. * A node representing the outgoing light.
  22370. *
  22371. * @type {Node<vec3>}
  22372. */
  22373. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  22374. /**
  22375. * An array representing the lights in the scene.
  22376. *
  22377. * @private
  22378. * @type {Array<Light>}
  22379. */
  22380. this._lights = [];
  22381. /**
  22382. * For each light in the scene, this node will create a
  22383. * corresponding light node.
  22384. *
  22385. * @private
  22386. * @type {Array<LightingNode>?}
  22387. * @default null
  22388. */
  22389. this._lightNodes = null;
  22390. /**
  22391. * A hash for identifying the current light nodes setup.
  22392. *
  22393. * @private
  22394. * @type {String?}
  22395. * @default null
  22396. */
  22397. this._lightNodesHash = null;
  22398. /**
  22399. * `LightsNode` sets this property to `true` by default.
  22400. *
  22401. * @type {Boolean}
  22402. * @default true
  22403. */
  22404. this.global = true;
  22405. }
  22406. /**
  22407. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  22408. * light IDs into the cache key.
  22409. *
  22410. * @return {Number} The custom cache key.
  22411. */
  22412. customCacheKey() {
  22413. const lightIDs = [];
  22414. const lights = this._lights;
  22415. for ( let i = 0; i < lights.length; i ++ ) {
  22416. lightIDs.push( lights[ i ].id );
  22417. }
  22418. return hashArray( lightIDs );
  22419. }
  22420. /**
  22421. * Computes a hash value for identifying the current light nodes setup.
  22422. *
  22423. * @param {NodeBuilder} builder - A reference to the current node builder.
  22424. * @return {String} The computed hash.
  22425. */
  22426. getHash( builder ) {
  22427. if ( this._lightNodesHash === null ) {
  22428. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  22429. const hash = [];
  22430. for ( const lightNode of this._lightNodes ) {
  22431. hash.push( lightNode.getSelf().getHash() );
  22432. }
  22433. this._lightNodesHash = 'lights-' + hash.join( ',' );
  22434. }
  22435. return this._lightNodesHash;
  22436. }
  22437. analyze( builder ) {
  22438. const properties = builder.getDataFromNode( this );
  22439. for ( const node of properties.nodes ) {
  22440. node.build( builder );
  22441. }
  22442. }
  22443. /**
  22444. * Creates lighting nodes for each scene light. This makes it possible to further
  22445. * process lights in the node system.
  22446. *
  22447. * @param {NodeBuilder} builder - A reference to the current node builder.
  22448. */
  22449. setupLightsNode( builder ) {
  22450. const lightNodes = [];
  22451. const previousLightNodes = this._lightNodes;
  22452. const lights = sortLights( this._lights );
  22453. const nodeLibrary = builder.renderer.library;
  22454. for ( const light of lights ) {
  22455. if ( light.isNode ) {
  22456. lightNodes.push( nodeObject( light ) );
  22457. } else {
  22458. let lightNode = null;
  22459. if ( previousLightNodes !== null ) {
  22460. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  22461. }
  22462. if ( lightNode === null ) {
  22463. // find the corresponding node type for a given light
  22464. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  22465. if ( lightNodeClass === null ) {
  22466. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  22467. continue;
  22468. }
  22469. let lightNode = null;
  22470. if ( ! _lightsNodeRef.has( light ) ) {
  22471. lightNode = nodeObject( new lightNodeClass( light ) );
  22472. _lightsNodeRef.set( light, lightNode );
  22473. } else {
  22474. lightNode = _lightsNodeRef.get( light );
  22475. }
  22476. lightNodes.push( lightNode );
  22477. }
  22478. }
  22479. }
  22480. this._lightNodes = lightNodes;
  22481. }
  22482. /**
  22483. * Setups the internal lights by building all respective
  22484. * light nodes.
  22485. *
  22486. * @param {NodeBuilder} builder - A reference to the current node builder.
  22487. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  22488. */
  22489. setupLights( builder, lightNodes ) {
  22490. for ( const lightNode of lightNodes ) {
  22491. lightNode.build( builder );
  22492. }
  22493. }
  22494. /**
  22495. * The implementation makes sure that for each light in the scene
  22496. * there is a corresponding light node. By building the light nodes
  22497. * and evaluating the lighting model the outgoing light is computed.
  22498. *
  22499. * @param {NodeBuilder} builder - A reference to the current node builder.
  22500. * @return {Node<vec3>} A node representing the outgoing light.
  22501. */
  22502. setup( builder ) {
  22503. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  22504. const context = builder.context;
  22505. const lightingModel = context.lightingModel;
  22506. let outgoingLightNode = this.outgoingLightNode;
  22507. if ( lightingModel ) {
  22508. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  22509. context.outgoingLight = outgoingLightNode;
  22510. const stack = builder.addStack();
  22511. //
  22512. const properties = builder.getDataFromNode( this );
  22513. properties.nodes = stack.nodes;
  22514. //
  22515. lightingModel.start( context, stack, builder );
  22516. // lights
  22517. this.setupLights( builder, _lightNodes );
  22518. //
  22519. lightingModel.indirect( context, stack, builder );
  22520. //
  22521. const { backdrop, backdropAlpha } = context;
  22522. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  22523. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  22524. if ( backdrop !== null ) {
  22525. if ( backdropAlpha !== null ) {
  22526. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  22527. } else {
  22528. totalDiffuse = vec3( backdrop );
  22529. }
  22530. context.material.transparent = true;
  22531. }
  22532. totalDiffuseNode.assign( totalDiffuse );
  22533. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  22534. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  22535. //
  22536. lightingModel.finish( context, stack, builder );
  22537. //
  22538. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  22539. }
  22540. return outgoingLightNode;
  22541. }
  22542. /**
  22543. * Configures this node with an array of lights.
  22544. *
  22545. * @param {Array<Light>} lights - An array of lights.
  22546. * @return {LightsNode} A reference to this node.
  22547. */
  22548. setLights( lights ) {
  22549. this._lights = lights;
  22550. this._lightNodes = null;
  22551. this._lightNodesHash = null;
  22552. return this;
  22553. }
  22554. /**
  22555. * Returns an array of the scene's lights.
  22556. *
  22557. * @return {Array<Light>} The scene's lights.
  22558. */
  22559. getLights() {
  22560. return this._lights;
  22561. }
  22562. /**
  22563. * Whether the scene has lights or not.
  22564. *
  22565. * @type {Boolean}
  22566. */
  22567. get hasLights() {
  22568. return this._lights.length > 0;
  22569. }
  22570. }
  22571. /**
  22572. * TSL function for creating an instance of `LightsNode` and configuring
  22573. * it with the given array of lights.
  22574. *
  22575. * @function
  22576. * @param {Array<Light>} lights - An array of lights.
  22577. * @return {LightsNode} The created lights node.
  22578. */
  22579. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  22580. /** @module ShadowBaseNode **/
  22581. /**
  22582. * Base class for all shadow nodes.
  22583. *
  22584. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  22585. * Lighting nodes might share the same shadow node type or use specific ones depending on
  22586. * their requirements.
  22587. *
  22588. * @augments Node
  22589. */
  22590. class ShadowBaseNode extends Node {
  22591. static get type() {
  22592. return 'ShadowBaseNode';
  22593. }
  22594. /**
  22595. * Constructs a new shadow base node.
  22596. *
  22597. * @param {Light} light - The shadow casting light.
  22598. */
  22599. constructor( light ) {
  22600. super();
  22601. /**
  22602. * The shadow casting light.
  22603. *
  22604. * @type {Light}
  22605. */
  22606. this.light = light;
  22607. /**
  22608. * Overwritten since shadows are updated by default per render.
  22609. *
  22610. * @type {String}
  22611. * @default 'render'
  22612. */
  22613. this.updateBeforeType = NodeUpdateType.RENDER;
  22614. /**
  22615. * This flag can be used for type testing.
  22616. *
  22617. * @type {Boolean}
  22618. * @readonly
  22619. * @default true
  22620. */
  22621. this.isShadowBaseNode = true;
  22622. }
  22623. /**
  22624. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  22625. *
  22626. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  22627. */
  22628. setupShadowPosition( { material } ) {
  22629. // Use assign inside an Fn()
  22630. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  22631. }
  22632. /**
  22633. * Can be called when the shadow isn't required anymore. That can happen when
  22634. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  22635. * to `false`.
  22636. */
  22637. dispose() {
  22638. this.updateBeforeType = NodeUpdateType.NONE;
  22639. }
  22640. }
  22641. /**
  22642. * TSL object that represents the vertex position in world space during the shadow pass.
  22643. *
  22644. * @type {Node<vec3>}
  22645. */
  22646. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  22647. // renderer state
  22648. function saveRendererState( renderer, state = {} ) {
  22649. state.toneMapping = renderer.toneMapping;
  22650. state.toneMappingExposure = renderer.toneMappingExposure;
  22651. state.outputColorSpace = renderer.outputColorSpace;
  22652. state.renderTarget = renderer.getRenderTarget();
  22653. state.activeCubeFace = renderer.getActiveCubeFace();
  22654. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  22655. state.renderObjectFunction = renderer.getRenderObjectFunction();
  22656. state.pixelRatio = renderer.getPixelRatio();
  22657. state.mrt = renderer.getMRT();
  22658. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  22659. state.clearAlpha = renderer.getClearAlpha();
  22660. state.autoClear = renderer.autoClear;
  22661. state.scissorTest = renderer.getScissorTest();
  22662. return state;
  22663. }
  22664. function resetRendererState( renderer, state ) {
  22665. state = saveRendererState( renderer, state );
  22666. renderer.setMRT( null );
  22667. renderer.setRenderObjectFunction( null );
  22668. renderer.setClearColor( 0x000000, 1 );
  22669. renderer.autoClear = true;
  22670. return state;
  22671. }
  22672. function restoreRendererState( renderer, state ) {
  22673. renderer.toneMapping = state.toneMapping;
  22674. renderer.toneMappingExposure = state.toneMappingExposure;
  22675. renderer.outputColorSpace = state.outputColorSpace;
  22676. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  22677. renderer.setRenderObjectFunction( state.renderObjectFunction );
  22678. renderer.setPixelRatio( state.pixelRatio );
  22679. renderer.setMRT( state.mrt );
  22680. renderer.setClearColor( state.clearColor, state.clearAlpha );
  22681. renderer.autoClear = state.autoClear;
  22682. renderer.setScissorTest( state.scissorTest );
  22683. }
  22684. // scene state
  22685. function saveSceneState( scene, state = {} ) {
  22686. state.background = scene.background;
  22687. state.backgroundNode = scene.backgroundNode;
  22688. state.overrideMaterial = scene.overrideMaterial;
  22689. return state;
  22690. }
  22691. function resetSceneState( scene, state ) {
  22692. state = saveSceneState( scene, state );
  22693. scene.background = null;
  22694. scene.backgroundNode = null;
  22695. scene.overrideMaterial = null;
  22696. return state;
  22697. }
  22698. function restoreSceneState( scene, state ) {
  22699. scene.background = state.background;
  22700. scene.backgroundNode = state.backgroundNode;
  22701. scene.overrideMaterial = state.overrideMaterial;
  22702. }
  22703. // renderer and scene state
  22704. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  22705. state = saveRendererState( renderer, state );
  22706. state = saveSceneState( scene, state );
  22707. return state;
  22708. }
  22709. function resetRendererAndSceneState( renderer, scene, state ) {
  22710. state = resetRendererState( renderer, state );
  22711. state = resetSceneState( scene, state );
  22712. return state;
  22713. }
  22714. function restoreRendererAndSceneState( renderer, scene, state ) {
  22715. restoreRendererState( renderer, state );
  22716. restoreSceneState( scene, state );
  22717. }
  22718. var RendererUtils = /*#__PURE__*/Object.freeze({
  22719. __proto__: null,
  22720. resetRendererAndSceneState: resetRendererAndSceneState,
  22721. resetRendererState: resetRendererState,
  22722. resetSceneState: resetSceneState,
  22723. restoreRendererAndSceneState: restoreRendererAndSceneState,
  22724. restoreRendererState: restoreRendererState,
  22725. restoreSceneState: restoreSceneState,
  22726. saveRendererAndSceneState: saveRendererAndSceneState,
  22727. saveRendererState: saveRendererState,
  22728. saveSceneState: saveSceneState
  22729. });
  22730. /** @module ShadowNode **/
  22731. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  22732. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  22733. let dist = positionWorld.sub( position ).length();
  22734. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  22735. dist = dist.saturate(); // clamp to [ 0, 1 ]
  22736. return dist;
  22737. } );
  22738. const linearShadowDistance = ( light ) => {
  22739. const camera = light.shadow.camera;
  22740. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  22741. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  22742. const referencePosition = objectPosition( light );
  22743. return linearDistance( referencePosition, nearDistance, farDistance );
  22744. };
  22745. const getShadowMaterial = ( light ) => {
  22746. let material = shadowMaterialLib.get( light );
  22747. if ( material === undefined ) {
  22748. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  22749. material = new NodeMaterial();
  22750. material.colorNode = vec4( 0, 0, 0, 1 );
  22751. material.depthNode = depthNode;
  22752. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  22753. material.name = 'ShadowMaterial';
  22754. shadowMaterialLib.set( light, material );
  22755. }
  22756. return material;
  22757. };
  22758. /**
  22759. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  22760. * with a binary `[0,1]` result.
  22761. *
  22762. * @method
  22763. * @param {Object} inputs - The input parameter object.
  22764. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  22765. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  22766. * @return {Node<float>} The filtering result.
  22767. */
  22768. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  22769. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  22770. } );
  22771. /**
  22772. * A shadow filtering function performing PCF filtering.
  22773. *
  22774. * @method
  22775. * @param {Object} inputs - The input parameter object.
  22776. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  22777. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  22778. * @param {LightShadow} inputs.shadow - The light shadow.
  22779. * @return {Node<float>} The filtering result.
  22780. */
  22781. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  22782. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  22783. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  22784. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  22785. const texelSize = vec2( 1 ).div( mapSize );
  22786. const dx0 = texelSize.x.negate().mul( radius );
  22787. const dy0 = texelSize.y.negate().mul( radius );
  22788. const dx1 = texelSize.x.mul( radius );
  22789. const dy1 = texelSize.y.mul( radius );
  22790. const dx2 = dx0.div( 2 );
  22791. const dy2 = dy0.div( 2 );
  22792. const dx3 = dx1.div( 2 );
  22793. const dy3 = dy1.div( 2 );
  22794. return add(
  22795. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  22796. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  22797. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  22798. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  22799. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  22800. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  22801. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  22802. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  22803. depthCompare( shadowCoord.xy, shadowCoord.z ),
  22804. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  22805. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  22806. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  22807. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  22808. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  22809. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  22810. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  22811. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  22812. ).mul( 1 / 17 );
  22813. } );
  22814. /**
  22815. * A shadow filtering function performing PCF soft filtering.
  22816. *
  22817. * @method
  22818. * @param {Object} inputs - The input parameter object.
  22819. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  22820. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  22821. * @param {LightShadow} inputs.shadow - The light shadow.
  22822. * @return {Node<float>} The filtering result.
  22823. */
  22824. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  22825. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  22826. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  22827. const texelSize = vec2( 1 ).div( mapSize );
  22828. const dx = texelSize.x;
  22829. const dy = texelSize.y;
  22830. const uv = shadowCoord.xy;
  22831. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  22832. uv.subAssign( f.mul( texelSize ) );
  22833. return add(
  22834. depthCompare( uv, shadowCoord.z ),
  22835. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  22836. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  22837. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  22838. mix(
  22839. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  22840. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  22841. f.x
  22842. ),
  22843. mix(
  22844. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  22845. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  22846. f.x
  22847. ),
  22848. mix(
  22849. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  22850. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  22851. f.y
  22852. ),
  22853. mix(
  22854. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  22855. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  22856. f.y
  22857. ),
  22858. mix(
  22859. mix(
  22860. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  22861. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  22862. f.x
  22863. ),
  22864. mix(
  22865. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  22866. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  22867. f.x
  22868. ),
  22869. f.y
  22870. )
  22871. ).mul( 1 / 9 );
  22872. } );
  22873. /**
  22874. * A shadow filtering function performing VSM filtering.
  22875. *
  22876. * @method
  22877. * @param {Object} inputs - The input parameter object.
  22878. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  22879. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  22880. * @return {Node<float>} The filtering result.
  22881. */
  22882. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  22883. const occlusion = float( 1 ).toVar();
  22884. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  22885. const hardShadow = step( shadowCoord.z, distribution.x );
  22886. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  22887. const distance = shadowCoord.z.sub( distribution.x );
  22888. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  22889. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  22890. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  22891. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  22892. } );
  22893. return occlusion;
  22894. } );
  22895. /**
  22896. * Represents the shader code for the first VSM render pass.
  22897. *
  22898. * @method
  22899. * @param {Object} inputs - The input parameter object.
  22900. * @param {Node<float>} inputs.samples - The number of samples
  22901. * @param {Node<float>} inputs.radius - The radius.
  22902. * @param {Node<float>} inputs.size - The size.
  22903. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  22904. * @return {Node<vec2>} The VSM output.
  22905. */
  22906. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  22907. const mean = float( 0 ).toVar();
  22908. const squaredMean = float( 0 ).toVar();
  22909. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  22910. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  22911. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  22912. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  22913. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  22914. mean.addAssign( depth );
  22915. squaredMean.addAssign( depth.mul( depth ) );
  22916. } );
  22917. mean.divAssign( samples );
  22918. squaredMean.divAssign( samples );
  22919. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  22920. return vec2( mean, std_dev );
  22921. } );
  22922. /**
  22923. * Represents the shader code for the second VSM render pass.
  22924. *
  22925. * @method
  22926. * @param {Object} inputs - The input parameter object.
  22927. * @param {Node<float>} inputs.samples - The number of samples
  22928. * @param {Node<float>} inputs.radius - The radius.
  22929. * @param {Node<float>} inputs.size - The size.
  22930. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  22931. * @return {Node<vec2>} The VSM output.
  22932. */
  22933. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  22934. const mean = float( 0 ).toVar();
  22935. const squaredMean = float( 0 ).toVar();
  22936. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  22937. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  22938. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  22939. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  22940. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  22941. mean.addAssign( distribution.x );
  22942. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  22943. } );
  22944. mean.divAssign( samples );
  22945. squaredMean.divAssign( samples );
  22946. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  22947. return vec2( mean, std_dev );
  22948. } );
  22949. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  22950. //
  22951. let _rendererState;
  22952. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  22953. /**
  22954. * Represents the default shadow implementation for lighting nodes.
  22955. *
  22956. * @augments module:ShadowBaseNode~ShadowBaseNode
  22957. */
  22958. class ShadowNode extends ShadowBaseNode {
  22959. static get type() {
  22960. return 'ShadowNode';
  22961. }
  22962. /**
  22963. * Constructs a new shadow node.
  22964. *
  22965. * @param {Light} light - The shadow casting light.
  22966. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  22967. */
  22968. constructor( light, shadow = null ) {
  22969. super( light );
  22970. /**
  22971. * The light shadow which defines the properties light's
  22972. * shadow.
  22973. *
  22974. * @type {LightShadow?}
  22975. * @default null
  22976. */
  22977. this.shadow = shadow || light.shadow;
  22978. /**
  22979. * A reference to the shadow map which is a render target.
  22980. *
  22981. * @type {RenderTarget?}
  22982. * @default null
  22983. */
  22984. this.shadowMap = null;
  22985. /**
  22986. * Only relevant for VSM shadows. Render target for the
  22987. * first VSM render pass.
  22988. *
  22989. * @type {RenderTarget?}
  22990. * @default null
  22991. */
  22992. this.vsmShadowMapVertical = null;
  22993. /**
  22994. * Only relevant for VSM shadows. Render target for the
  22995. * second VSM render pass.
  22996. *
  22997. * @type {RenderTarget?}
  22998. * @default null
  22999. */
  23000. this.vsmShadowMapHorizontal = null;
  23001. /**
  23002. * Only relevant for VSM shadows. Node material which
  23003. * is used to render the first VSM pass.
  23004. *
  23005. * @type {NodeMaterial?}
  23006. * @default null
  23007. */
  23008. this.vsmMaterialVertical = null;
  23009. /**
  23010. * Only relevant for VSM shadows. Node material which
  23011. * is used to render the second VSM pass.
  23012. *
  23013. * @type {NodeMaterial?}
  23014. * @default null
  23015. */
  23016. this.vsmMaterialHorizontal = null;
  23017. /**
  23018. * A reference to the output node which defines the
  23019. * final result of this shadow node.
  23020. *
  23021. * @type {Node?}
  23022. * @private
  23023. * @default null
  23024. */
  23025. this._node = null;
  23026. /**
  23027. * This flag can be used for type testing.
  23028. *
  23029. * @type {Boolean}
  23030. * @readonly
  23031. * @default true
  23032. */
  23033. this.isShadowNode = true;
  23034. }
  23035. /**
  23036. * Setups the shadow filtering.
  23037. *
  23038. * @param {NodeBuilder} builder - A reference to the current node builder.
  23039. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  23040. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  23041. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  23042. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  23043. * @param {LightShadow} inputs.shadow - The light shadow.
  23044. * @return {Node<float>} The result node of the shadow filtering.
  23045. */
  23046. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  23047. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  23048. .and( shadowCoord.x.lessThanEqual( 1 ) )
  23049. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  23050. .and( shadowCoord.y.lessThanEqual( 1 ) )
  23051. .and( shadowCoord.z.lessThanEqual( 1 ) );
  23052. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  23053. return frustumTest.select( shadowNode, float( 1 ) );
  23054. }
  23055. /**
  23056. * Setups the shadow coordinates.
  23057. *
  23058. * @param {NodeBuilder} builder - A reference to the current node builder.
  23059. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  23060. * @return {Node<vec3>} The shadow coordinates.
  23061. */
  23062. setupShadowCoord( builder, shadowPosition ) {
  23063. const { shadow } = this;
  23064. const { renderer } = builder;
  23065. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  23066. let shadowCoord = shadowPosition;
  23067. let coordZ;
  23068. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  23069. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  23070. coordZ = shadowCoord.z;
  23071. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23072. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  23073. }
  23074. } else {
  23075. const w = shadowCoord.w;
  23076. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  23077. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  23078. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  23079. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  23080. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  23081. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  23082. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  23083. }
  23084. shadowCoord = vec3(
  23085. shadowCoord.x,
  23086. shadowCoord.y.oneMinus(), // follow webgpu standards
  23087. coordZ.add( bias )
  23088. );
  23089. return shadowCoord;
  23090. }
  23091. /**
  23092. * Returns the shadow filtering function for the given shadow type.
  23093. *
  23094. * @param {Number} type - The shadow type.
  23095. * @return {Function} The filtering function.
  23096. */
  23097. getShadowFilterFn( type ) {
  23098. return _shadowFilterLib[ type ];
  23099. }
  23100. /**
  23101. * Setups the shadow output node.
  23102. *
  23103. * @param {NodeBuilder} builder - A reference to the current node builder.
  23104. * @return {Node<vec3>} The shadow output node.
  23105. */
  23106. setupShadow( builder ) {
  23107. const { renderer } = builder;
  23108. const { light, shadow } = this;
  23109. const shadowMapType = renderer.shadowMap.type;
  23110. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  23111. depthTexture.compareFunction = LessCompare;
  23112. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  23113. shadowMap.depthTexture = depthTexture;
  23114. shadow.camera.updateProjectionMatrix();
  23115. // VSM
  23116. if ( shadowMapType === VSMShadowMap ) {
  23117. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  23118. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  23119. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  23120. const shadowPassVertical = texture( depthTexture );
  23121. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  23122. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  23123. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  23124. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  23125. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  23126. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  23127. material.name = 'VSMVertical';
  23128. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  23129. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  23130. material.name = 'VSMHorizontal';
  23131. }
  23132. //
  23133. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  23134. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  23135. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  23136. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  23137. //
  23138. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  23139. if ( filterFn === null ) {
  23140. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  23141. }
  23142. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  23143. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  23144. const shadowColor = texture( shadowMap.texture, shadowCoord );
  23145. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  23146. this.shadowMap = shadowMap;
  23147. this.shadow.map = shadowMap;
  23148. return shadowOutput;
  23149. }
  23150. /**
  23151. * The implementation performs the setup of the output node. An output is only
  23152. * produces if shadow mapping is globally enabled in the renderer.
  23153. *
  23154. * @param {NodeBuilder} builder - A reference to the current node builder.
  23155. * @return {ShaderCallNodeInternal} The output node.
  23156. */
  23157. setup( builder ) {
  23158. if ( builder.renderer.shadowMap.enabled === false ) return;
  23159. return Fn( () => {
  23160. let node = this._node;
  23161. this.setupShadowPosition( builder );
  23162. if ( node === null ) {
  23163. this._node = node = this.setupShadow( builder );
  23164. }
  23165. if ( builder.material.shadowNode ) { // @deprecated, r171
  23166. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  23167. }
  23168. if ( builder.material.receivedShadowNode ) {
  23169. node = builder.material.receivedShadowNode( node );
  23170. }
  23171. return node;
  23172. } )();
  23173. }
  23174. /**
  23175. * Renders the shadow. The logic of this function could be included
  23176. * into {@link ShadowNode#updateShadow} however more specialized shadow
  23177. * nodes might require a custom shadow map rendering. By having a
  23178. * dedicated method, it's easier to overwrite the default behavior.
  23179. *
  23180. * @param {NodeFrame} frame - A reference to the current node frame.
  23181. */
  23182. renderShadow( frame ) {
  23183. const { shadow, shadowMap, light } = this;
  23184. const { renderer, scene } = frame;
  23185. shadow.updateMatrices( light );
  23186. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  23187. renderer.render( scene, shadow.camera );
  23188. }
  23189. /**
  23190. * Updates the shadow.
  23191. *
  23192. * @param {NodeFrame} frame - A reference to the current node frame.
  23193. */
  23194. updateShadow( frame ) {
  23195. const { shadowMap, light, shadow } = this;
  23196. const { renderer, scene, camera } = frame;
  23197. const shadowType = renderer.shadowMap.type;
  23198. const depthVersion = shadowMap.depthTexture.version;
  23199. this._depthVersionCached = depthVersion;
  23200. shadow.camera.layers.mask = camera.layers.mask;
  23201. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  23202. const currentMRT = renderer.getMRT();
  23203. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  23204. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  23205. scene.overrideMaterial = getShadowMaterial( light );
  23206. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  23207. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  23208. if ( useVelocity ) {
  23209. getDataFromObject( object ).useVelocity = true;
  23210. }
  23211. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  23212. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  23213. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  23214. }
  23215. } );
  23216. renderer.setRenderTarget( shadowMap );
  23217. this.renderShadow( frame );
  23218. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  23219. // vsm blur pass
  23220. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  23221. this.vsmPass( renderer );
  23222. }
  23223. restoreRendererAndSceneState( renderer, scene, _rendererState );
  23224. }
  23225. /**
  23226. * For VSM additional render passes are required.
  23227. *
  23228. * @param {Renderer} renderer - A reference to the current renderer.
  23229. */
  23230. vsmPass( renderer ) {
  23231. const { shadow } = this;
  23232. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  23233. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  23234. renderer.setRenderTarget( this.vsmShadowMapVertical );
  23235. _quadMesh$1.material = this.vsmMaterialVertical;
  23236. _quadMesh$1.render( renderer );
  23237. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  23238. _quadMesh$1.material = this.vsmMaterialHorizontal;
  23239. _quadMesh$1.render( renderer );
  23240. }
  23241. /**
  23242. * Frees the internal resources of this shadow node.
  23243. */
  23244. dispose() {
  23245. this.shadowMap.dispose();
  23246. this.shadowMap = null;
  23247. if ( this.vsmShadowMapVertical !== null ) {
  23248. this.vsmShadowMapVertical.dispose();
  23249. this.vsmShadowMapVertical = null;
  23250. this.vsmMaterialVertical.dispose();
  23251. this.vsmMaterialVertical = null;
  23252. }
  23253. if ( this.vsmShadowMapHorizontal !== null ) {
  23254. this.vsmShadowMapHorizontal.dispose();
  23255. this.vsmShadowMapHorizontal = null;
  23256. this.vsmMaterialHorizontal.dispose();
  23257. this.vsmMaterialHorizontal = null;
  23258. }
  23259. super.dispose();
  23260. }
  23261. /**
  23262. * The implementation performs the update of the shadow map if necessary.
  23263. *
  23264. * @param {NodeFrame} frame - A reference to the current node frame.
  23265. */
  23266. updateBefore( frame ) {
  23267. const { shadow } = this;
  23268. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  23269. if ( needsUpdate ) {
  23270. this.updateShadow( frame );
  23271. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  23272. shadow.needsUpdate = false;
  23273. }
  23274. }
  23275. }
  23276. }
  23277. /**
  23278. * TSL function for creating an instance of `ShadowNode`.
  23279. *
  23280. * @function
  23281. * @param {Light} light - The shadow casting light.
  23282. * @param {LightShadow} shadow - The light shadow.
  23283. * @return {ShadowNode} The created shadow node.
  23284. */
  23285. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  23286. /**
  23287. * Base class for analytic light nodes.
  23288. *
  23289. * @augments LightingNode
  23290. */
  23291. class AnalyticLightNode extends LightingNode {
  23292. static get type() {
  23293. return 'AnalyticLightNode';
  23294. }
  23295. /**
  23296. * Constructs a new analytic light node.
  23297. *
  23298. * @param {Light?} [light=null] - The light source.
  23299. */
  23300. constructor( light = null ) {
  23301. super();
  23302. /**
  23303. * The light source.
  23304. *
  23305. * @type {Light?}
  23306. * @default null
  23307. */
  23308. this.light = light;
  23309. /**
  23310. * The light's color value.
  23311. *
  23312. * @type {Color}
  23313. */
  23314. this.color = new Color();
  23315. /**
  23316. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  23317. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  23318. *
  23319. * @type {Node}
  23320. */
  23321. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  23322. /**
  23323. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  23324. * The final color node is represented by a different node when using shadows.
  23325. *
  23326. * @type {Node?}
  23327. * @default null
  23328. */
  23329. this.baseColorNode = null;
  23330. /**
  23331. * Represents the light's shadow.
  23332. *
  23333. * @type {ShadowNode?}
  23334. * @default null
  23335. */
  23336. this.shadowNode = null;
  23337. /**
  23338. * Represents the light's shadow color.
  23339. *
  23340. * @type {Node?}
  23341. * @default null
  23342. */
  23343. this.shadowColorNode = null;
  23344. /**
  23345. * This flag can be used for type testing.
  23346. *
  23347. * @type {Boolean}
  23348. * @readonly
  23349. * @default true
  23350. */
  23351. this.isAnalyticLightNode = true;
  23352. /**
  23353. * Overwritten since analytic light nodes are updated
  23354. * once per frame.
  23355. *
  23356. * @type {String}
  23357. * @default 'frame'
  23358. */
  23359. this.updateType = NodeUpdateType.FRAME;
  23360. }
  23361. /**
  23362. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  23363. * `light.id` and `light.castShadow` into the cache key.
  23364. *
  23365. * @return {Number} The custom cache key.
  23366. */
  23367. customCacheKey() {
  23368. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  23369. }
  23370. getHash() {
  23371. return this.light.uuid;
  23372. }
  23373. /**
  23374. * Setups the shadow node for this light. The method exists so concrete light classes
  23375. * can setup different types of shadow nodes.
  23376. *
  23377. * @return {ShadowNode} The created shadow node.
  23378. */
  23379. setupShadowNode() {
  23380. return shadow( this.light );
  23381. }
  23382. /**
  23383. * Setups the shadow for this light. This method is only executed if the light
  23384. * cast shadows and the current build object receives shadows. It incorporates
  23385. * shadows into the lighting computation.
  23386. *
  23387. * @param {NodeBuilder} builder - The current node builder.
  23388. */
  23389. setupShadow( builder ) {
  23390. const { renderer } = builder;
  23391. if ( renderer.shadowMap.enabled === false ) return;
  23392. let shadowColorNode = this.shadowColorNode;
  23393. if ( shadowColorNode === null ) {
  23394. const customShadowNode = this.light.shadow.shadowNode;
  23395. let shadowNode;
  23396. if ( customShadowNode !== undefined ) {
  23397. shadowNode = nodeObject( customShadowNode );
  23398. } else {
  23399. shadowNode = this.setupShadowNode( builder );
  23400. }
  23401. this.shadowNode = shadowNode;
  23402. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  23403. this.baseColorNode = this.colorNode;
  23404. }
  23405. //
  23406. this.colorNode = shadowColorNode;
  23407. }
  23408. /**
  23409. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  23410. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  23411. * invocate the respective interface methods.
  23412. *
  23413. * @param {NodeBuilder} builder - The current node builder.
  23414. */
  23415. setup( builder ) {
  23416. this.colorNode = this.baseColorNode || this.colorNode;
  23417. if ( this.light.castShadow ) {
  23418. if ( builder.object.receiveShadow ) {
  23419. this.setupShadow( builder );
  23420. }
  23421. } else if ( this.shadowNode !== null ) {
  23422. this.shadowNode.dispose();
  23423. this.shadowNode = null;
  23424. this.shadowColorNode = null;
  23425. }
  23426. }
  23427. /**
  23428. * The update method is used to update light uniforms per frame.
  23429. * Potentially overwritten in concrete light nodes to update light
  23430. * specific uniforms.
  23431. *
  23432. * @param {NodeFrame} frame - A reference to the current node frame.
  23433. */
  23434. update( /*frame*/ ) {
  23435. const { light } = this;
  23436. this.color.copy( light.color ).multiplyScalar( light.intensity );
  23437. }
  23438. }
  23439. /** @module LightUtils **/
  23440. /**
  23441. * Represents a `discard` shader operation in TSL.
  23442. *
  23443. * @method
  23444. * @param {Object} inputs - The input parameter object.
  23445. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  23446. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  23447. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  23448. * @return {Node<float>} The distance falloff.
  23449. */
  23450. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  23451. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  23452. // based upon Frostbite 3 Moving to Physically-based Rendering
  23453. // page 32, equation 26: E[window1]
  23454. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23455. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  23456. return cutoffDistance.greaterThan( 0 ).select(
  23457. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  23458. distanceFalloff
  23459. );
  23460. } ); // validated
  23461. /** @module PointShadowNode **/
  23462. const _clearColor$2 = /*@__PURE__*/ new Color();
  23463. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  23464. // vector suitable for 2D texture mapping. This code uses the following layout for the
  23465. // 2D texture:
  23466. //
  23467. // xzXZ
  23468. // y Y
  23469. //
  23470. // Y - Positive y direction
  23471. // y - Negative y direction
  23472. // X - Positive x direction
  23473. // x - Negative x direction
  23474. // Z - Positive z direction
  23475. // z - Negative z direction
  23476. //
  23477. // Source and test bed:
  23478. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  23479. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  23480. const v = pos.toVar();
  23481. // Number of texels to avoid at the edge of each square
  23482. const absV = abs( v );
  23483. // Intersect unit cube
  23484. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  23485. absV.mulAssign( scaleToCube );
  23486. // Apply scale to avoid seams
  23487. // two texels less per square (one texel will do for NEAREST)
  23488. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  23489. // Unwrap
  23490. // space: -1 ... 1 range for each square
  23491. //
  23492. // #X## dim := ( 4 , 2 )
  23493. // # # center := ( 1 , 1 )
  23494. const planar = vec2( v.xy ).toVar();
  23495. const almostATexel = texelSizeY.mul( 1.5 );
  23496. const almostOne = almostATexel.oneMinus();
  23497. If( absV.z.greaterThanEqual( almostOne ), () => {
  23498. If( v.z.greaterThan( 0.0 ), () => {
  23499. planar.x.assign( sub( 4.0, v.x ) );
  23500. } );
  23501. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  23502. const signX = sign( v.x );
  23503. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  23504. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  23505. const signY = sign( v.y );
  23506. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  23507. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  23508. } );
  23509. // Transform to UV space
  23510. // scale := 0.5 / dim
  23511. // translate := ( center + 0.5 ) / dim
  23512. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  23513. } ).setLayout( {
  23514. name: 'cubeToUV',
  23515. type: 'vec2',
  23516. inputs: [
  23517. { name: 'pos', type: 'vec3' },
  23518. { name: 'texelSizeY', type: 'float' }
  23519. ]
  23520. } );
  23521. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  23522. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  23523. } );
  23524. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  23525. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  23526. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  23527. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  23528. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  23529. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  23530. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  23531. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  23532. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  23533. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  23534. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  23535. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  23536. .mul( 1.0 / 9.0 );
  23537. } );
  23538. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  23539. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  23540. // the vector from the light to the world-space position of the fragment.
  23541. const lightToPosition = shadowCoord.xyz.toVar();
  23542. const lightToPositionLength = lightToPosition.length();
  23543. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  23544. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  23545. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  23546. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  23547. const result = float( 1.0 ).toVar();
  23548. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  23549. // dp = normalized distance from light to fragment position
  23550. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  23551. dp.addAssign( bias );
  23552. // bd3D = base direction 3D
  23553. const bd3D = lightToPosition.normalize();
  23554. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  23555. // percentage-closer filtering
  23556. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  23557. } );
  23558. return result;
  23559. } );
  23560. const _viewport = /*@__PURE__*/ new Vector4();
  23561. const _viewportSize = /*@__PURE__*/ new Vector2();
  23562. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  23563. /**
  23564. * Represents the shadow implementation for point light nodes.
  23565. *
  23566. * @augments module:ShadowNode~ShadowNode
  23567. */
  23568. class PointShadowNode extends ShadowNode {
  23569. static get type() {
  23570. return 'PointShadowNode';
  23571. }
  23572. /**
  23573. * Constructs a new point shadow node.
  23574. *
  23575. * @param {PointLight} light - The shadow casting point light.
  23576. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  23577. */
  23578. constructor( light, shadow = null ) {
  23579. super( light, shadow );
  23580. }
  23581. /**
  23582. * Overwrites the default implementation to return point light shadow specific
  23583. * filtering functions.
  23584. *
  23585. * @param {Number} type - The shadow type.
  23586. * @return {Function} The filtering function.
  23587. */
  23588. getShadowFilterFn( type ) {
  23589. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  23590. }
  23591. /**
  23592. * Overwrites the default implementation so the unaltered shadow position is used.
  23593. *
  23594. * @param {NodeBuilder} builder - A reference to the current node builder.
  23595. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  23596. * @return {Node<vec3>} The shadow coordinates.
  23597. */
  23598. setupShadowCoord( builder, shadowPosition ) {
  23599. return shadowPosition;
  23600. }
  23601. /**
  23602. * Overwrites the default implementation to only use point light specific
  23603. * shadow filter functions.
  23604. *
  23605. * @param {NodeBuilder} builder - A reference to the current node builder.
  23606. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  23607. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  23608. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  23609. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  23610. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  23611. * @param {LightShadow} inputs.shadow - The light shadow.
  23612. * @return {Node<float>} The result node of the shadow filtering.
  23613. */
  23614. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  23615. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  23616. }
  23617. /**
  23618. * Overwrites the default implementation with point light specific
  23619. * rendering code.
  23620. *
  23621. * @param {NodeFrame} frame - A reference to the current node frame.
  23622. */
  23623. renderShadow( frame ) {
  23624. const { shadow, shadowMap, light } = this;
  23625. const { renderer, scene } = frame;
  23626. const shadowFrameExtents = shadow.getFrameExtents();
  23627. _shadowMapSize.copy( shadow.mapSize );
  23628. _shadowMapSize.multiply( shadowFrameExtents );
  23629. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  23630. _viewportSize.copy( shadow.mapSize );
  23631. //
  23632. const previousAutoClear = renderer.autoClear;
  23633. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  23634. const previousClearAlpha = renderer.getClearAlpha();
  23635. renderer.autoClear = false;
  23636. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  23637. renderer.clear();
  23638. const viewportCount = shadow.getViewportCount();
  23639. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  23640. const viewport = shadow.getViewport( vp );
  23641. const x = _viewportSize.x * viewport.x;
  23642. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  23643. _viewport.set(
  23644. x,
  23645. y,
  23646. _viewportSize.x * viewport.z,
  23647. _viewportSize.y * viewport.w
  23648. );
  23649. shadowMap.viewport.copy( _viewport );
  23650. shadow.updateMatrices( light, vp );
  23651. renderer.render( scene, shadow.camera );
  23652. }
  23653. //
  23654. renderer.autoClear = previousAutoClear;
  23655. renderer.setClearColor( previousClearColor, previousClearAlpha );
  23656. }
  23657. }
  23658. /**
  23659. * TSL function for creating an instance of `PointShadowNode`.
  23660. *
  23661. * @function
  23662. * @param {PointLight} light - The shadow casting point light.
  23663. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  23664. * @return {PointShadowNode} The created point shadow node.
  23665. */
  23666. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  23667. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  23668. const lightingModel = builder.context.lightingModel;
  23669. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  23670. const lightDirection = lVector.normalize();
  23671. const lightDistance = lVector.length();
  23672. const lightAttenuation = getDistanceAttenuation( {
  23673. lightDistance,
  23674. cutoffDistance,
  23675. decayExponent
  23676. } );
  23677. const lightColor = color.mul( lightAttenuation );
  23678. const reflectedLight = builder.context.reflectedLight;
  23679. lightingModel.direct( {
  23680. lightDirection,
  23681. lightColor,
  23682. reflectedLight
  23683. }, builder.stack, builder );
  23684. } );
  23685. /**
  23686. * Module for representing point lights as nodes.
  23687. *
  23688. * @augments AnalyticLightNode
  23689. */
  23690. class PointLightNode extends AnalyticLightNode {
  23691. static get type() {
  23692. return 'PointLightNode';
  23693. }
  23694. /**
  23695. * Constructs a new point light node.
  23696. *
  23697. * @param {PointLight?} [light=null] - The point light source.
  23698. */
  23699. constructor( light = null ) {
  23700. super( light );
  23701. /**
  23702. * Uniform node representing the cutoff distance.
  23703. *
  23704. * @type {UniformNode<float>}
  23705. */
  23706. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  23707. /**
  23708. * Uniform node representing the decay exponent.
  23709. *
  23710. * @type {UniformNode<float>}
  23711. */
  23712. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  23713. }
  23714. /**
  23715. * Overwritten to updated point light specific uniforms.
  23716. *
  23717. * @param {NodeFrame} frame - A reference to the current node frame.
  23718. */
  23719. update( frame ) {
  23720. const { light } = this;
  23721. super.update( frame );
  23722. this.cutoffDistanceNode.value = light.distance;
  23723. this.decayExponentNode.value = light.decay;
  23724. }
  23725. /**
  23726. * Overwritten to setup point light specific shadow.
  23727. *
  23728. * @return {PointShadowNode}
  23729. */
  23730. setupShadowNode() {
  23731. return pointShadow( this.light );
  23732. }
  23733. setup( builder ) {
  23734. super.setup( builder );
  23735. directPointLight( {
  23736. color: this.colorNode,
  23737. lightViewPosition: lightViewPosition( this.light ),
  23738. cutoffDistance: this.cutoffDistanceNode,
  23739. decayExponent: this.decayExponentNode
  23740. } ).append();
  23741. }
  23742. }
  23743. /** @module Procedural **/
  23744. /**
  23745. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  23746. *
  23747. * @method
  23748. * @param {Node<vec2>} coord - The uv coordinates.
  23749. * @return {Node<float>} The result data.
  23750. */
  23751. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  23752. const uv = coord.mul( 2.0 );
  23753. const cx = uv.x.floor();
  23754. const cy = uv.y.floor();
  23755. const result = cx.add( cy ).mod( 2.0 );
  23756. return result.sign();
  23757. } );
  23758. // Three.js Transpiler
  23759. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  23760. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  23761. const f = float( f_immutable ).toVar();
  23762. const t = float( t_immutable ).toVar();
  23763. const b = bool( b_immutable ).toVar();
  23764. return select( b, t, f );
  23765. } ).setLayout( {
  23766. name: 'mx_select',
  23767. type: 'float',
  23768. inputs: [
  23769. { name: 'b', type: 'bool' },
  23770. { name: 't', type: 'float' },
  23771. { name: 'f', type: 'float' }
  23772. ]
  23773. } );
  23774. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  23775. const b = bool( b_immutable ).toVar();
  23776. const val = float( val_immutable ).toVar();
  23777. return select( b, val.negate(), val );
  23778. } ).setLayout( {
  23779. name: 'mx_negate_if',
  23780. type: 'float',
  23781. inputs: [
  23782. { name: 'val', type: 'float' },
  23783. { name: 'b', type: 'bool' }
  23784. ]
  23785. } );
  23786. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  23787. const x = float( x_immutable ).toVar();
  23788. return int( floor( x ) );
  23789. } ).setLayout( {
  23790. name: 'mx_floor',
  23791. type: 'int',
  23792. inputs: [
  23793. { name: 'x', type: 'float' }
  23794. ]
  23795. } );
  23796. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  23797. const x = float( x_immutable ).toVar();
  23798. i.assign( mx_floor( x ) );
  23799. return x.sub( float( i ) );
  23800. } );
  23801. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  23802. const t = float( t_immutable ).toVar();
  23803. const s = float( s_immutable ).toVar();
  23804. const v3 = float( v3_immutable ).toVar();
  23805. const v2 = float( v2_immutable ).toVar();
  23806. const v1 = float( v1_immutable ).toVar();
  23807. const v0 = float( v0_immutable ).toVar();
  23808. const s1 = float( sub( 1.0, s ) ).toVar();
  23809. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  23810. } ).setLayout( {
  23811. name: 'mx_bilerp_0',
  23812. type: 'float',
  23813. inputs: [
  23814. { name: 'v0', type: 'float' },
  23815. { name: 'v1', type: 'float' },
  23816. { name: 'v2', type: 'float' },
  23817. { name: 'v3', type: 'float' },
  23818. { name: 's', type: 'float' },
  23819. { name: 't', type: 'float' }
  23820. ]
  23821. } );
  23822. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  23823. const t = float( t_immutable ).toVar();
  23824. const s = float( s_immutable ).toVar();
  23825. const v3 = vec3( v3_immutable ).toVar();
  23826. const v2 = vec3( v2_immutable ).toVar();
  23827. const v1 = vec3( v1_immutable ).toVar();
  23828. const v0 = vec3( v0_immutable ).toVar();
  23829. const s1 = float( sub( 1.0, s ) ).toVar();
  23830. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  23831. } ).setLayout( {
  23832. name: 'mx_bilerp_1',
  23833. type: 'vec3',
  23834. inputs: [
  23835. { name: 'v0', type: 'vec3' },
  23836. { name: 'v1', type: 'vec3' },
  23837. { name: 'v2', type: 'vec3' },
  23838. { name: 'v3', type: 'vec3' },
  23839. { name: 's', type: 'float' },
  23840. { name: 't', type: 'float' }
  23841. ]
  23842. } );
  23843. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  23844. 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 ] ) => {
  23845. const r = float( r_immutable ).toVar();
  23846. const t = float( t_immutable ).toVar();
  23847. const s = float( s_immutable ).toVar();
  23848. const v7 = float( v7_immutable ).toVar();
  23849. const v6 = float( v6_immutable ).toVar();
  23850. const v5 = float( v5_immutable ).toVar();
  23851. const v4 = float( v4_immutable ).toVar();
  23852. const v3 = float( v3_immutable ).toVar();
  23853. const v2 = float( v2_immutable ).toVar();
  23854. const v1 = float( v1_immutable ).toVar();
  23855. const v0 = float( v0_immutable ).toVar();
  23856. const s1 = float( sub( 1.0, s ) ).toVar();
  23857. const t1 = float( sub( 1.0, t ) ).toVar();
  23858. const r1 = float( sub( 1.0, r ) ).toVar();
  23859. 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 ) ) ) ) ) );
  23860. } ).setLayout( {
  23861. name: 'mx_trilerp_0',
  23862. type: 'float',
  23863. inputs: [
  23864. { name: 'v0', type: 'float' },
  23865. { name: 'v1', type: 'float' },
  23866. { name: 'v2', type: 'float' },
  23867. { name: 'v3', type: 'float' },
  23868. { name: 'v4', type: 'float' },
  23869. { name: 'v5', type: 'float' },
  23870. { name: 'v6', type: 'float' },
  23871. { name: 'v7', type: 'float' },
  23872. { name: 's', type: 'float' },
  23873. { name: 't', type: 'float' },
  23874. { name: 'r', type: 'float' }
  23875. ]
  23876. } );
  23877. 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 ] ) => {
  23878. const r = float( r_immutable ).toVar();
  23879. const t = float( t_immutable ).toVar();
  23880. const s = float( s_immutable ).toVar();
  23881. const v7 = vec3( v7_immutable ).toVar();
  23882. const v6 = vec3( v6_immutable ).toVar();
  23883. const v5 = vec3( v5_immutable ).toVar();
  23884. const v4 = vec3( v4_immutable ).toVar();
  23885. const v3 = vec3( v3_immutable ).toVar();
  23886. const v2 = vec3( v2_immutable ).toVar();
  23887. const v1 = vec3( v1_immutable ).toVar();
  23888. const v0 = vec3( v0_immutable ).toVar();
  23889. const s1 = float( sub( 1.0, s ) ).toVar();
  23890. const t1 = float( sub( 1.0, t ) ).toVar();
  23891. const r1 = float( sub( 1.0, r ) ).toVar();
  23892. 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 ) ) ) ) ) );
  23893. } ).setLayout( {
  23894. name: 'mx_trilerp_1',
  23895. type: 'vec3',
  23896. inputs: [
  23897. { name: 'v0', type: 'vec3' },
  23898. { name: 'v1', type: 'vec3' },
  23899. { name: 'v2', type: 'vec3' },
  23900. { name: 'v3', type: 'vec3' },
  23901. { name: 'v4', type: 'vec3' },
  23902. { name: 'v5', type: 'vec3' },
  23903. { name: 'v6', type: 'vec3' },
  23904. { name: 'v7', type: 'vec3' },
  23905. { name: 's', type: 'float' },
  23906. { name: 't', type: 'float' },
  23907. { name: 'r', type: 'float' }
  23908. ]
  23909. } );
  23910. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  23911. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  23912. const y = float( y_immutable ).toVar();
  23913. const x = float( x_immutable ).toVar();
  23914. const hash = uint( hash_immutable ).toVar();
  23915. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  23916. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  23917. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  23918. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  23919. } ).setLayout( {
  23920. name: 'mx_gradient_float_0',
  23921. type: 'float',
  23922. inputs: [
  23923. { name: 'hash', type: 'uint' },
  23924. { name: 'x', type: 'float' },
  23925. { name: 'y', type: 'float' }
  23926. ]
  23927. } );
  23928. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  23929. const z = float( z_immutable ).toVar();
  23930. const y = float( y_immutable ).toVar();
  23931. const x = float( x_immutable ).toVar();
  23932. const hash = uint( hash_immutable ).toVar();
  23933. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  23934. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  23935. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  23936. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  23937. } ).setLayout( {
  23938. name: 'mx_gradient_float_1',
  23939. type: 'float',
  23940. inputs: [
  23941. { name: 'hash', type: 'uint' },
  23942. { name: 'x', type: 'float' },
  23943. { name: 'y', type: 'float' },
  23944. { name: 'z', type: 'float' }
  23945. ]
  23946. } );
  23947. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  23948. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  23949. const y = float( y_immutable ).toVar();
  23950. const x = float( x_immutable ).toVar();
  23951. const hash = uvec3( hash_immutable ).toVar();
  23952. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  23953. } ).setLayout( {
  23954. name: 'mx_gradient_vec3_0',
  23955. type: 'vec3',
  23956. inputs: [
  23957. { name: 'hash', type: 'uvec3' },
  23958. { name: 'x', type: 'float' },
  23959. { name: 'y', type: 'float' }
  23960. ]
  23961. } );
  23962. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  23963. const z = float( z_immutable ).toVar();
  23964. const y = float( y_immutable ).toVar();
  23965. const x = float( x_immutable ).toVar();
  23966. const hash = uvec3( hash_immutable ).toVar();
  23967. 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 ) );
  23968. } ).setLayout( {
  23969. name: 'mx_gradient_vec3_1',
  23970. type: 'vec3',
  23971. inputs: [
  23972. { name: 'hash', type: 'uvec3' },
  23973. { name: 'x', type: 'float' },
  23974. { name: 'y', type: 'float' },
  23975. { name: 'z', type: 'float' }
  23976. ]
  23977. } );
  23978. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  23979. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  23980. const v = float( v_immutable ).toVar();
  23981. return mul( 0.6616, v );
  23982. } ).setLayout( {
  23983. name: 'mx_gradient_scale2d_0',
  23984. type: 'float',
  23985. inputs: [
  23986. { name: 'v', type: 'float' }
  23987. ]
  23988. } );
  23989. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  23990. const v = float( v_immutable ).toVar();
  23991. return mul( 0.9820, v );
  23992. } ).setLayout( {
  23993. name: 'mx_gradient_scale3d_0',
  23994. type: 'float',
  23995. inputs: [
  23996. { name: 'v', type: 'float' }
  23997. ]
  23998. } );
  23999. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  24000. const v = vec3( v_immutable ).toVar();
  24001. return mul( 0.6616, v );
  24002. } ).setLayout( {
  24003. name: 'mx_gradient_scale2d_1',
  24004. type: 'vec3',
  24005. inputs: [
  24006. { name: 'v', type: 'vec3' }
  24007. ]
  24008. } );
  24009. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  24010. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  24011. const v = vec3( v_immutable ).toVar();
  24012. return mul( 0.9820, v );
  24013. } ).setLayout( {
  24014. name: 'mx_gradient_scale3d_1',
  24015. type: 'vec3',
  24016. inputs: [
  24017. { name: 'v', type: 'vec3' }
  24018. ]
  24019. } );
  24020. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  24021. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  24022. const k = int( k_immutable ).toVar();
  24023. const x = uint( x_immutable ).toVar();
  24024. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  24025. } ).setLayout( {
  24026. name: 'mx_rotl32',
  24027. type: 'uint',
  24028. inputs: [
  24029. { name: 'x', type: 'uint' },
  24030. { name: 'k', type: 'int' }
  24031. ]
  24032. } );
  24033. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  24034. a.subAssign( c );
  24035. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  24036. c.addAssign( b );
  24037. b.subAssign( a );
  24038. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  24039. a.addAssign( c );
  24040. c.subAssign( b );
  24041. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  24042. b.addAssign( a );
  24043. a.subAssign( c );
  24044. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  24045. c.addAssign( b );
  24046. b.subAssign( a );
  24047. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  24048. a.addAssign( c );
  24049. c.subAssign( b );
  24050. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  24051. b.addAssign( a );
  24052. } );
  24053. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  24054. const c = uint( c_immutable ).toVar();
  24055. const b = uint( b_immutable ).toVar();
  24056. const a = uint( a_immutable ).toVar();
  24057. c.bitXorAssign( b );
  24058. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  24059. a.bitXorAssign( c );
  24060. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  24061. b.bitXorAssign( a );
  24062. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  24063. c.bitXorAssign( b );
  24064. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  24065. a.bitXorAssign( c );
  24066. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  24067. b.bitXorAssign( a );
  24068. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  24069. c.bitXorAssign( b );
  24070. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  24071. return c;
  24072. } ).setLayout( {
  24073. name: 'mx_bjfinal',
  24074. type: 'uint',
  24075. inputs: [
  24076. { name: 'a', type: 'uint' },
  24077. { name: 'b', type: 'uint' },
  24078. { name: 'c', type: 'uint' }
  24079. ]
  24080. } );
  24081. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  24082. const bits = uint( bits_immutable ).toVar();
  24083. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  24084. } ).setLayout( {
  24085. name: 'mx_bits_to_01',
  24086. type: 'float',
  24087. inputs: [
  24088. { name: 'bits', type: 'uint' }
  24089. ]
  24090. } );
  24091. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  24092. const t = float( t_immutable ).toVar();
  24093. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  24094. } ).setLayout( {
  24095. name: 'mx_fade',
  24096. type: 'float',
  24097. inputs: [
  24098. { name: 't', type: 'float' }
  24099. ]
  24100. } );
  24101. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  24102. const x = int( x_immutable ).toVar();
  24103. const len = uint( uint( 1 ) ).toVar();
  24104. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  24105. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  24106. } ).setLayout( {
  24107. name: 'mx_hash_int_0',
  24108. type: 'uint',
  24109. inputs: [
  24110. { name: 'x', type: 'int' }
  24111. ]
  24112. } );
  24113. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  24114. const y = int( y_immutable ).toVar();
  24115. const x = int( x_immutable ).toVar();
  24116. const len = uint( uint( 2 ) ).toVar();
  24117. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  24118. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  24119. a.addAssign( uint( x ) );
  24120. b.addAssign( uint( y ) );
  24121. return mx_bjfinal( a, b, c );
  24122. } ).setLayout( {
  24123. name: 'mx_hash_int_1',
  24124. type: 'uint',
  24125. inputs: [
  24126. { name: 'x', type: 'int' },
  24127. { name: 'y', type: 'int' }
  24128. ]
  24129. } );
  24130. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  24131. const z = int( z_immutable ).toVar();
  24132. const y = int( y_immutable ).toVar();
  24133. const x = int( x_immutable ).toVar();
  24134. const len = uint( uint( 3 ) ).toVar();
  24135. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  24136. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  24137. a.addAssign( uint( x ) );
  24138. b.addAssign( uint( y ) );
  24139. c.addAssign( uint( z ) );
  24140. return mx_bjfinal( a, b, c );
  24141. } ).setLayout( {
  24142. name: 'mx_hash_int_2',
  24143. type: 'uint',
  24144. inputs: [
  24145. { name: 'x', type: 'int' },
  24146. { name: 'y', type: 'int' },
  24147. { name: 'z', type: 'int' }
  24148. ]
  24149. } );
  24150. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  24151. const xx = int( xx_immutable ).toVar();
  24152. const z = int( z_immutable ).toVar();
  24153. const y = int( y_immutable ).toVar();
  24154. const x = int( x_immutable ).toVar();
  24155. const len = uint( uint( 4 ) ).toVar();
  24156. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  24157. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  24158. a.addAssign( uint( x ) );
  24159. b.addAssign( uint( y ) );
  24160. c.addAssign( uint( z ) );
  24161. mx_bjmix( a, b, c );
  24162. a.addAssign( uint( xx ) );
  24163. return mx_bjfinal( a, b, c );
  24164. } ).setLayout( {
  24165. name: 'mx_hash_int_3',
  24166. type: 'uint',
  24167. inputs: [
  24168. { name: 'x', type: 'int' },
  24169. { name: 'y', type: 'int' },
  24170. { name: 'z', type: 'int' },
  24171. { name: 'xx', type: 'int' }
  24172. ]
  24173. } );
  24174. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  24175. const yy = int( yy_immutable ).toVar();
  24176. const xx = int( xx_immutable ).toVar();
  24177. const z = int( z_immutable ).toVar();
  24178. const y = int( y_immutable ).toVar();
  24179. const x = int( x_immutable ).toVar();
  24180. const len = uint( uint( 5 ) ).toVar();
  24181. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  24182. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  24183. a.addAssign( uint( x ) );
  24184. b.addAssign( uint( y ) );
  24185. c.addAssign( uint( z ) );
  24186. mx_bjmix( a, b, c );
  24187. a.addAssign( uint( xx ) );
  24188. b.addAssign( uint( yy ) );
  24189. return mx_bjfinal( a, b, c );
  24190. } ).setLayout( {
  24191. name: 'mx_hash_int_4',
  24192. type: 'uint',
  24193. inputs: [
  24194. { name: 'x', type: 'int' },
  24195. { name: 'y', type: 'int' },
  24196. { name: 'z', type: 'int' },
  24197. { name: 'xx', type: 'int' },
  24198. { name: 'yy', type: 'int' }
  24199. ]
  24200. } );
  24201. 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 ] );
  24202. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  24203. const y = int( y_immutable ).toVar();
  24204. const x = int( x_immutable ).toVar();
  24205. const h = uint( mx_hash_int( x, y ) ).toVar();
  24206. const result = uvec3().toVar();
  24207. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  24208. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  24209. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  24210. return result;
  24211. } ).setLayout( {
  24212. name: 'mx_hash_vec3_0',
  24213. type: 'uvec3',
  24214. inputs: [
  24215. { name: 'x', type: 'int' },
  24216. { name: 'y', type: 'int' }
  24217. ]
  24218. } );
  24219. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  24220. const z = int( z_immutable ).toVar();
  24221. const y = int( y_immutable ).toVar();
  24222. const x = int( x_immutable ).toVar();
  24223. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  24224. const result = uvec3().toVar();
  24225. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  24226. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  24227. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  24228. return result;
  24229. } ).setLayout( {
  24230. name: 'mx_hash_vec3_1',
  24231. type: 'uvec3',
  24232. inputs: [
  24233. { name: 'x', type: 'int' },
  24234. { name: 'y', type: 'int' },
  24235. { name: 'z', type: 'int' }
  24236. ]
  24237. } );
  24238. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  24239. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24240. const p = vec2( p_immutable ).toVar();
  24241. const X = int().toVar(), Y = int().toVar();
  24242. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  24243. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  24244. const u = float( mx_fade( fx ) ).toVar();
  24245. const v = float( mx_fade( fy ) ).toVar();
  24246. 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();
  24247. return mx_gradient_scale2d( result );
  24248. } ).setLayout( {
  24249. name: 'mx_perlin_noise_float_0',
  24250. type: 'float',
  24251. inputs: [
  24252. { name: 'p', type: 'vec2' }
  24253. ]
  24254. } );
  24255. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24256. const p = vec3( p_immutable ).toVar();
  24257. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  24258. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  24259. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  24260. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  24261. const u = float( mx_fade( fx ) ).toVar();
  24262. const v = float( mx_fade( fy ) ).toVar();
  24263. const w = float( mx_fade( fz ) ).toVar();
  24264. 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();
  24265. return mx_gradient_scale3d( result );
  24266. } ).setLayout( {
  24267. name: 'mx_perlin_noise_float_1',
  24268. type: 'float',
  24269. inputs: [
  24270. { name: 'p', type: 'vec3' }
  24271. ]
  24272. } );
  24273. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  24274. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24275. const p = vec2( p_immutable ).toVar();
  24276. const X = int().toVar(), Y = int().toVar();
  24277. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  24278. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  24279. const u = float( mx_fade( fx ) ).toVar();
  24280. const v = float( mx_fade( fy ) ).toVar();
  24281. 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();
  24282. return mx_gradient_scale2d( result );
  24283. } ).setLayout( {
  24284. name: 'mx_perlin_noise_vec3_0',
  24285. type: 'vec3',
  24286. inputs: [
  24287. { name: 'p', type: 'vec2' }
  24288. ]
  24289. } );
  24290. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24291. const p = vec3( p_immutable ).toVar();
  24292. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  24293. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  24294. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  24295. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  24296. const u = float( mx_fade( fx ) ).toVar();
  24297. const v = float( mx_fade( fy ) ).toVar();
  24298. const w = float( mx_fade( fz ) ).toVar();
  24299. 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();
  24300. return mx_gradient_scale3d( result );
  24301. } ).setLayout( {
  24302. name: 'mx_perlin_noise_vec3_1',
  24303. type: 'vec3',
  24304. inputs: [
  24305. { name: 'p', type: 'vec3' }
  24306. ]
  24307. } );
  24308. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  24309. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24310. const p = float( p_immutable ).toVar();
  24311. const ix = int( mx_floor( p ) ).toVar();
  24312. return mx_bits_to_01( mx_hash_int( ix ) );
  24313. } ).setLayout( {
  24314. name: 'mx_cell_noise_float_0',
  24315. type: 'float',
  24316. inputs: [
  24317. { name: 'p', type: 'float' }
  24318. ]
  24319. } );
  24320. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24321. const p = vec2( p_immutable ).toVar();
  24322. const ix = int( mx_floor( p.x ) ).toVar();
  24323. const iy = int( mx_floor( p.y ) ).toVar();
  24324. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  24325. } ).setLayout( {
  24326. name: 'mx_cell_noise_float_1',
  24327. type: 'float',
  24328. inputs: [
  24329. { name: 'p', type: 'vec2' }
  24330. ]
  24331. } );
  24332. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24333. const p = vec3( p_immutable ).toVar();
  24334. const ix = int( mx_floor( p.x ) ).toVar();
  24335. const iy = int( mx_floor( p.y ) ).toVar();
  24336. const iz = int( mx_floor( p.z ) ).toVar();
  24337. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  24338. } ).setLayout( {
  24339. name: 'mx_cell_noise_float_2',
  24340. type: 'float',
  24341. inputs: [
  24342. { name: 'p', type: 'vec3' }
  24343. ]
  24344. } );
  24345. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24346. const p = vec4( p_immutable ).toVar();
  24347. const ix = int( mx_floor( p.x ) ).toVar();
  24348. const iy = int( mx_floor( p.y ) ).toVar();
  24349. const iz = int( mx_floor( p.z ) ).toVar();
  24350. const iw = int( mx_floor( p.w ) ).toVar();
  24351. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  24352. } ).setLayout( {
  24353. name: 'mx_cell_noise_float_3',
  24354. type: 'float',
  24355. inputs: [
  24356. { name: 'p', type: 'vec4' }
  24357. ]
  24358. } );
  24359. 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 ] );
  24360. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24361. const p = float( p_immutable ).toVar();
  24362. const ix = int( mx_floor( p ) ).toVar();
  24363. 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 ) ) ) );
  24364. } ).setLayout( {
  24365. name: 'mx_cell_noise_vec3_0',
  24366. type: 'vec3',
  24367. inputs: [
  24368. { name: 'p', type: 'float' }
  24369. ]
  24370. } );
  24371. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24372. const p = vec2( p_immutable ).toVar();
  24373. const ix = int( mx_floor( p.x ) ).toVar();
  24374. const iy = int( mx_floor( p.y ) ).toVar();
  24375. 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 ) ) ) );
  24376. } ).setLayout( {
  24377. name: 'mx_cell_noise_vec3_1',
  24378. type: 'vec3',
  24379. inputs: [
  24380. { name: 'p', type: 'vec2' }
  24381. ]
  24382. } );
  24383. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24384. const p = vec3( p_immutable ).toVar();
  24385. const ix = int( mx_floor( p.x ) ).toVar();
  24386. const iy = int( mx_floor( p.y ) ).toVar();
  24387. const iz = int( mx_floor( p.z ) ).toVar();
  24388. 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 ) ) ) );
  24389. } ).setLayout( {
  24390. name: 'mx_cell_noise_vec3_2',
  24391. type: 'vec3',
  24392. inputs: [
  24393. { name: 'p', type: 'vec3' }
  24394. ]
  24395. } );
  24396. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  24397. const p = vec4( p_immutable ).toVar();
  24398. const ix = int( mx_floor( p.x ) ).toVar();
  24399. const iy = int( mx_floor( p.y ) ).toVar();
  24400. const iz = int( mx_floor( p.z ) ).toVar();
  24401. const iw = int( mx_floor( p.w ) ).toVar();
  24402. 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 ) ) ) );
  24403. } ).setLayout( {
  24404. name: 'mx_cell_noise_vec3_3',
  24405. type: 'vec3',
  24406. inputs: [
  24407. { name: 'p', type: 'vec4' }
  24408. ]
  24409. } );
  24410. 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 ] );
  24411. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  24412. const diminish = float( diminish_immutable ).toVar();
  24413. const lacunarity = float( lacunarity_immutable ).toVar();
  24414. const octaves = int( octaves_immutable ).toVar();
  24415. const p = vec3( p_immutable ).toVar();
  24416. const result = float( 0.0 ).toVar();
  24417. const amplitude = float( 1.0 ).toVar();
  24418. Loop( octaves, () => {
  24419. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  24420. amplitude.mulAssign( diminish );
  24421. p.mulAssign( lacunarity );
  24422. } );
  24423. return result;
  24424. } ).setLayout( {
  24425. name: 'mx_fractal_noise_float',
  24426. type: 'float',
  24427. inputs: [
  24428. { name: 'p', type: 'vec3' },
  24429. { name: 'octaves', type: 'int' },
  24430. { name: 'lacunarity', type: 'float' },
  24431. { name: 'diminish', type: 'float' }
  24432. ]
  24433. } );
  24434. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  24435. const diminish = float( diminish_immutable ).toVar();
  24436. const lacunarity = float( lacunarity_immutable ).toVar();
  24437. const octaves = int( octaves_immutable ).toVar();
  24438. const p = vec3( p_immutable ).toVar();
  24439. const result = vec3( 0.0 ).toVar();
  24440. const amplitude = float( 1.0 ).toVar();
  24441. Loop( octaves, () => {
  24442. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  24443. amplitude.mulAssign( diminish );
  24444. p.mulAssign( lacunarity );
  24445. } );
  24446. return result;
  24447. } ).setLayout( {
  24448. name: 'mx_fractal_noise_vec3',
  24449. type: 'vec3',
  24450. inputs: [
  24451. { name: 'p', type: 'vec3' },
  24452. { name: 'octaves', type: 'int' },
  24453. { name: 'lacunarity', type: 'float' },
  24454. { name: 'diminish', type: 'float' }
  24455. ]
  24456. } );
  24457. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  24458. const diminish = float( diminish_immutable ).toVar();
  24459. const lacunarity = float( lacunarity_immutable ).toVar();
  24460. const octaves = int( octaves_immutable ).toVar();
  24461. const p = vec3( p_immutable ).toVar();
  24462. 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 ) );
  24463. } ).setLayout( {
  24464. name: 'mx_fractal_noise_vec2',
  24465. type: 'vec2',
  24466. inputs: [
  24467. { name: 'p', type: 'vec3' },
  24468. { name: 'octaves', type: 'int' },
  24469. { name: 'lacunarity', type: 'float' },
  24470. { name: 'diminish', type: 'float' }
  24471. ]
  24472. } );
  24473. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  24474. const diminish = float( diminish_immutable ).toVar();
  24475. const lacunarity = float( lacunarity_immutable ).toVar();
  24476. const octaves = int( octaves_immutable ).toVar();
  24477. const p = vec3( p_immutable ).toVar();
  24478. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  24479. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  24480. return vec4( c, f );
  24481. } ).setLayout( {
  24482. name: 'mx_fractal_noise_vec4',
  24483. type: 'vec4',
  24484. inputs: [
  24485. { name: 'p', type: 'vec3' },
  24486. { name: 'octaves', type: 'int' },
  24487. { name: 'lacunarity', type: 'float' },
  24488. { name: 'diminish', type: 'float' }
  24489. ]
  24490. } );
  24491. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  24492. const metric = int( metric_immutable ).toVar();
  24493. const jitter = float( jitter_immutable ).toVar();
  24494. const yoff = int( yoff_immutable ).toVar();
  24495. const xoff = int( xoff_immutable ).toVar();
  24496. const y = int( y_immutable ).toVar();
  24497. const x = int( x_immutable ).toVar();
  24498. const p = vec2( p_immutable ).toVar();
  24499. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  24500. const off = vec2( tmp.x, tmp.y ).toVar();
  24501. off.subAssign( 0.5 );
  24502. off.mulAssign( jitter );
  24503. off.addAssign( 0.5 );
  24504. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  24505. const diff = vec2( cellpos.sub( p ) ).toVar();
  24506. If( metric.equal( int( 2 ) ), () => {
  24507. return abs( diff.x ).add( abs( diff.y ) );
  24508. } );
  24509. If( metric.equal( int( 3 ) ), () => {
  24510. return max$1( abs( diff.x ), abs( diff.y ) );
  24511. } );
  24512. return dot( diff, diff );
  24513. } ).setLayout( {
  24514. name: 'mx_worley_distance_0',
  24515. type: 'float',
  24516. inputs: [
  24517. { name: 'p', type: 'vec2' },
  24518. { name: 'x', type: 'int' },
  24519. { name: 'y', type: 'int' },
  24520. { name: 'xoff', type: 'int' },
  24521. { name: 'yoff', type: 'int' },
  24522. { name: 'jitter', type: 'float' },
  24523. { name: 'metric', type: 'int' }
  24524. ]
  24525. } );
  24526. 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 ] ) => {
  24527. const metric = int( metric_immutable ).toVar();
  24528. const jitter = float( jitter_immutable ).toVar();
  24529. const zoff = int( zoff_immutable ).toVar();
  24530. const yoff = int( yoff_immutable ).toVar();
  24531. const xoff = int( xoff_immutable ).toVar();
  24532. const z = int( z_immutable ).toVar();
  24533. const y = int( y_immutable ).toVar();
  24534. const x = int( x_immutable ).toVar();
  24535. const p = vec3( p_immutable ).toVar();
  24536. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  24537. off.subAssign( 0.5 );
  24538. off.mulAssign( jitter );
  24539. off.addAssign( 0.5 );
  24540. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  24541. const diff = vec3( cellpos.sub( p ) ).toVar();
  24542. If( metric.equal( int( 2 ) ), () => {
  24543. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  24544. } );
  24545. If( metric.equal( int( 3 ) ), () => {
  24546. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  24547. } );
  24548. return dot( diff, diff );
  24549. } ).setLayout( {
  24550. name: 'mx_worley_distance_1',
  24551. type: 'float',
  24552. inputs: [
  24553. { name: 'p', type: 'vec3' },
  24554. { name: 'x', type: 'int' },
  24555. { name: 'y', type: 'int' },
  24556. { name: 'z', type: 'int' },
  24557. { name: 'xoff', type: 'int' },
  24558. { name: 'yoff', type: 'int' },
  24559. { name: 'zoff', type: 'int' },
  24560. { name: 'jitter', type: 'float' },
  24561. { name: 'metric', type: 'int' }
  24562. ]
  24563. } );
  24564. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  24565. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24566. const metric = int( metric_immutable ).toVar();
  24567. const jitter = float( jitter_immutable ).toVar();
  24568. const p = vec2( p_immutable ).toVar();
  24569. const X = int().toVar(), Y = int().toVar();
  24570. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  24571. const sqdist = float( 1e6 ).toVar();
  24572. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24573. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24574. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  24575. sqdist.assign( min$1( sqdist, dist ) );
  24576. } );
  24577. } );
  24578. If( metric.equal( int( 0 ) ), () => {
  24579. sqdist.assign( sqrt( sqdist ) );
  24580. } );
  24581. return sqdist;
  24582. } ).setLayout( {
  24583. name: 'mx_worley_noise_float_0',
  24584. type: 'float',
  24585. inputs: [
  24586. { name: 'p', type: 'vec2' },
  24587. { name: 'jitter', type: 'float' },
  24588. { name: 'metric', type: 'int' }
  24589. ]
  24590. } );
  24591. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24592. const metric = int( metric_immutable ).toVar();
  24593. const jitter = float( jitter_immutable ).toVar();
  24594. const p = vec2( p_immutable ).toVar();
  24595. const X = int().toVar(), Y = int().toVar();
  24596. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  24597. const sqdist = vec2( 1e6, 1e6 ).toVar();
  24598. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24599. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24600. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  24601. If( dist.lessThan( sqdist.x ), () => {
  24602. sqdist.y.assign( sqdist.x );
  24603. sqdist.x.assign( dist );
  24604. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  24605. sqdist.y.assign( dist );
  24606. } );
  24607. } );
  24608. } );
  24609. If( metric.equal( int( 0 ) ), () => {
  24610. sqdist.assign( sqrt( sqdist ) );
  24611. } );
  24612. return sqdist;
  24613. } ).setLayout( {
  24614. name: 'mx_worley_noise_vec2_0',
  24615. type: 'vec2',
  24616. inputs: [
  24617. { name: 'p', type: 'vec2' },
  24618. { name: 'jitter', type: 'float' },
  24619. { name: 'metric', type: 'int' }
  24620. ]
  24621. } );
  24622. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24623. const metric = int( metric_immutable ).toVar();
  24624. const jitter = float( jitter_immutable ).toVar();
  24625. const p = vec2( p_immutable ).toVar();
  24626. const X = int().toVar(), Y = int().toVar();
  24627. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  24628. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  24629. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24630. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24631. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  24632. If( dist.lessThan( sqdist.x ), () => {
  24633. sqdist.z.assign( sqdist.y );
  24634. sqdist.y.assign( sqdist.x );
  24635. sqdist.x.assign( dist );
  24636. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  24637. sqdist.z.assign( sqdist.y );
  24638. sqdist.y.assign( dist );
  24639. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  24640. sqdist.z.assign( dist );
  24641. } );
  24642. } );
  24643. } );
  24644. If( metric.equal( int( 0 ) ), () => {
  24645. sqdist.assign( sqrt( sqdist ) );
  24646. } );
  24647. return sqdist;
  24648. } ).setLayout( {
  24649. name: 'mx_worley_noise_vec3_0',
  24650. type: 'vec3',
  24651. inputs: [
  24652. { name: 'p', type: 'vec2' },
  24653. { name: 'jitter', type: 'float' },
  24654. { name: 'metric', type: 'int' }
  24655. ]
  24656. } );
  24657. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24658. const metric = int( metric_immutable ).toVar();
  24659. const jitter = float( jitter_immutable ).toVar();
  24660. const p = vec3( p_immutable ).toVar();
  24661. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  24662. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  24663. const sqdist = float( 1e6 ).toVar();
  24664. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24665. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24666. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  24667. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  24668. sqdist.assign( min$1( sqdist, dist ) );
  24669. } );
  24670. } );
  24671. } );
  24672. If( metric.equal( int( 0 ) ), () => {
  24673. sqdist.assign( sqrt( sqdist ) );
  24674. } );
  24675. return sqdist;
  24676. } ).setLayout( {
  24677. name: 'mx_worley_noise_float_1',
  24678. type: 'float',
  24679. inputs: [
  24680. { name: 'p', type: 'vec3' },
  24681. { name: 'jitter', type: 'float' },
  24682. { name: 'metric', type: 'int' }
  24683. ]
  24684. } );
  24685. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  24686. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24687. const metric = int( metric_immutable ).toVar();
  24688. const jitter = float( jitter_immutable ).toVar();
  24689. const p = vec3( p_immutable ).toVar();
  24690. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  24691. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  24692. const sqdist = vec2( 1e6, 1e6 ).toVar();
  24693. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24694. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24695. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  24696. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  24697. If( dist.lessThan( sqdist.x ), () => {
  24698. sqdist.y.assign( sqdist.x );
  24699. sqdist.x.assign( dist );
  24700. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  24701. sqdist.y.assign( dist );
  24702. } );
  24703. } );
  24704. } );
  24705. } );
  24706. If( metric.equal( int( 0 ) ), () => {
  24707. sqdist.assign( sqrt( sqdist ) );
  24708. } );
  24709. return sqdist;
  24710. } ).setLayout( {
  24711. name: 'mx_worley_noise_vec2_1',
  24712. type: 'vec2',
  24713. inputs: [
  24714. { name: 'p', type: 'vec3' },
  24715. { name: 'jitter', type: 'float' },
  24716. { name: 'metric', type: 'int' }
  24717. ]
  24718. } );
  24719. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  24720. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  24721. const metric = int( metric_immutable ).toVar();
  24722. const jitter = float( jitter_immutable ).toVar();
  24723. const p = vec3( p_immutable ).toVar();
  24724. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  24725. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  24726. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  24727. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  24728. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  24729. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  24730. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  24731. If( dist.lessThan( sqdist.x ), () => {
  24732. sqdist.z.assign( sqdist.y );
  24733. sqdist.y.assign( sqdist.x );
  24734. sqdist.x.assign( dist );
  24735. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  24736. sqdist.z.assign( sqdist.y );
  24737. sqdist.y.assign( dist );
  24738. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  24739. sqdist.z.assign( dist );
  24740. } );
  24741. } );
  24742. } );
  24743. } );
  24744. If( metric.equal( int( 0 ) ), () => {
  24745. sqdist.assign( sqrt( sqdist ) );
  24746. } );
  24747. return sqdist;
  24748. } ).setLayout( {
  24749. name: 'mx_worley_noise_vec3_1',
  24750. type: 'vec3',
  24751. inputs: [
  24752. { name: 'p', type: 'vec3' },
  24753. { name: 'jitter', type: 'float' },
  24754. { name: 'metric', type: 'int' }
  24755. ]
  24756. } );
  24757. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  24758. // Three.js Transpiler
  24759. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  24760. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  24761. const s = hsv.y;
  24762. const v = hsv.z;
  24763. const result = vec3().toVar();
  24764. If( s.lessThan( 0.0001 ), () => {
  24765. result.assign( vec3( v, v, v ) );
  24766. } ).Else( () => {
  24767. let h = hsv.x;
  24768. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  24769. const hi = int( trunc( h ) );
  24770. const f = h.sub( float( hi ) );
  24771. const p = v.mul( s.oneMinus() );
  24772. const q = v.mul( s.mul( f ).oneMinus() );
  24773. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  24774. If( hi.equal( int( 0 ) ), () => {
  24775. result.assign( vec3( v, t, p ) );
  24776. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  24777. result.assign( vec3( q, v, p ) );
  24778. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  24779. result.assign( vec3( p, v, t ) );
  24780. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  24781. result.assign( vec3( p, q, v ) );
  24782. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  24783. result.assign( vec3( t, p, v ) );
  24784. } ).Else( () => {
  24785. result.assign( vec3( v, p, q ) );
  24786. } );
  24787. } );
  24788. return result;
  24789. } ).setLayout( {
  24790. name: 'mx_hsvtorgb',
  24791. type: 'vec3',
  24792. inputs: [
  24793. { name: 'hsv', type: 'vec3' }
  24794. ]
  24795. } );
  24796. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  24797. const c = vec3( c_immutable ).toVar();
  24798. const r = float( c.x ).toVar();
  24799. const g = float( c.y ).toVar();
  24800. const b = float( c.z ).toVar();
  24801. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  24802. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  24803. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  24804. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  24805. v.assign( maxcomp );
  24806. If( maxcomp.greaterThan( 0.0 ), () => {
  24807. s.assign( delta.div( maxcomp ) );
  24808. } ).Else( () => {
  24809. s.assign( 0.0 );
  24810. } );
  24811. If( s.lessThanEqual( 0.0 ), () => {
  24812. h.assign( 0.0 );
  24813. } ).Else( () => {
  24814. If( r.greaterThanEqual( maxcomp ), () => {
  24815. h.assign( g.sub( b ).div( delta ) );
  24816. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  24817. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  24818. } ).Else( () => {
  24819. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  24820. } );
  24821. h.mulAssign( 1.0 / 6.0 );
  24822. If( h.lessThan( 0.0 ), () => {
  24823. h.addAssign( 1.0 );
  24824. } );
  24825. } );
  24826. return vec3( h, s, v );
  24827. } ).setLayout( {
  24828. name: 'mx_rgbtohsv',
  24829. type: 'vec3',
  24830. inputs: [
  24831. { name: 'c', type: 'vec3' }
  24832. ]
  24833. } );
  24834. // Three.js Transpiler
  24835. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  24836. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  24837. const color = vec3( color_immutable ).toVar();
  24838. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  24839. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  24840. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  24841. return mix( linSeg, powSeg, isAbove );
  24842. } ).setLayout( {
  24843. name: 'mx_srgb_texture_to_lin_rec709',
  24844. type: 'vec3',
  24845. inputs: [
  24846. { name: 'color', type: 'vec3' }
  24847. ]
  24848. } );
  24849. const mx_aastep = ( threshold, value ) => {
  24850. threshold = float( threshold );
  24851. value = float( value );
  24852. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  24853. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  24854. };
  24855. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  24856. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  24857. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  24858. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  24859. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  24860. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  24861. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  24862. const mx_safepower = ( in1, in2 = 1 ) => {
  24863. in1 = float( in1 );
  24864. return in1.abs().pow( in2 ).mul( in1.sign() );
  24865. };
  24866. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  24867. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  24868. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  24869. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  24870. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  24871. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  24872. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  24873. return noise_vec4.mul( amplitude ).add( pivot );
  24874. };
  24875. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  24876. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  24877. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  24878. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  24879. 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 );
  24880. 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 );
  24881. 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 );
  24882. 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 );
  24883. /** @module getParallaxCorrectNormal **/
  24884. /**
  24885. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  24886. *
  24887. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  24888. *
  24889. * ```js
  24890. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  24891. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  24892. * ```
  24893. * @function
  24894. * @param {Node<vec3>} normal - The normal to correct.
  24895. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  24896. * @param {Node<vec3>} cubePos - The cube position.
  24897. * @return {Node<vec3>} The parallax corrected normal.
  24898. */
  24899. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  24900. const nDir = normalize( normal ).toVar( 'nDir' );
  24901. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  24902. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  24903. const rbminmax = vec3().toVar( 'rbminmax' );
  24904. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  24905. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  24906. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  24907. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  24908. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  24909. return boxIntersection.sub( cubePos );
  24910. } );
  24911. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  24912. // normal is assumed to have unit length
  24913. const x = normal.x, y = normal.y, z = normal.z;
  24914. // band 0
  24915. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  24916. // band 1
  24917. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  24918. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  24919. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  24920. // band 2
  24921. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  24922. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  24923. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  24924. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  24925. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  24926. return result;
  24927. } );
  24928. // constants
  24929. var TSL = /*#__PURE__*/Object.freeze({
  24930. __proto__: null,
  24931. BRDF_GGX: BRDF_GGX,
  24932. BRDF_Lambert: BRDF_Lambert,
  24933. BasicShadowFilter: BasicShadowFilter,
  24934. Break: Break,
  24935. Continue: Continue,
  24936. DFGApprox: DFGApprox,
  24937. D_GGX: D_GGX,
  24938. Discard: Discard,
  24939. EPSILON: EPSILON,
  24940. F_Schlick: F_Schlick,
  24941. Fn: Fn,
  24942. INFINITY: INFINITY,
  24943. If: If,
  24944. Loop: Loop,
  24945. NodeAccess: NodeAccess,
  24946. NodeShaderStage: NodeShaderStage,
  24947. NodeType: NodeType,
  24948. NodeUpdateType: NodeUpdateType,
  24949. PCFShadowFilter: PCFShadowFilter,
  24950. PCFSoftShadowFilter: PCFSoftShadowFilter,
  24951. PI: PI,
  24952. PI2: PI2,
  24953. Return: Return,
  24954. Schlick_to_F0: Schlick_to_F0,
  24955. ScriptableNodeResources: ScriptableNodeResources,
  24956. ShaderNode: ShaderNode,
  24957. TBNViewMatrix: TBNViewMatrix,
  24958. VSMShadowFilter: VSMShadowFilter,
  24959. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  24960. abs: abs,
  24961. acesFilmicToneMapping: acesFilmicToneMapping,
  24962. acos: acos,
  24963. add: add,
  24964. addMethodChaining: addMethodChaining,
  24965. addNodeElement: addNodeElement,
  24966. agxToneMapping: agxToneMapping,
  24967. all: all,
  24968. alphaT: alphaT,
  24969. and: and,
  24970. anisotropy: anisotropy,
  24971. anisotropyB: anisotropyB,
  24972. anisotropyT: anisotropyT,
  24973. any: any,
  24974. append: append,
  24975. arrayBuffer: arrayBuffer,
  24976. asin: asin,
  24977. assign: assign,
  24978. atan: atan,
  24979. atan2: atan2,
  24980. atomicAdd: atomicAdd,
  24981. atomicAnd: atomicAnd,
  24982. atomicFunc: atomicFunc,
  24983. atomicMax: atomicMax,
  24984. atomicMin: atomicMin,
  24985. atomicOr: atomicOr,
  24986. atomicStore: atomicStore,
  24987. atomicSub: atomicSub,
  24988. atomicXor: atomicXor,
  24989. attenuationColor: attenuationColor,
  24990. attenuationDistance: attenuationDistance,
  24991. attribute: attribute,
  24992. attributeArray: attributeArray,
  24993. backgroundBlurriness: backgroundBlurriness,
  24994. backgroundIntensity: backgroundIntensity,
  24995. backgroundRotation: backgroundRotation,
  24996. batch: batch,
  24997. billboarding: billboarding,
  24998. bitAnd: bitAnd,
  24999. bitNot: bitNot,
  25000. bitOr: bitOr,
  25001. bitXor: bitXor,
  25002. bitangentGeometry: bitangentGeometry,
  25003. bitangentLocal: bitangentLocal,
  25004. bitangentView: bitangentView,
  25005. bitangentWorld: bitangentWorld,
  25006. bitcast: bitcast,
  25007. blendBurn: blendBurn,
  25008. blendColor: blendColor,
  25009. blendDodge: blendDodge,
  25010. blendOverlay: blendOverlay,
  25011. blendScreen: blendScreen,
  25012. blur: blur,
  25013. bool: bool,
  25014. buffer: buffer,
  25015. bufferAttribute: bufferAttribute,
  25016. bumpMap: bumpMap,
  25017. burn: burn,
  25018. bvec2: bvec2,
  25019. bvec3: bvec3,
  25020. bvec4: bvec4,
  25021. bypass: bypass,
  25022. cache: cache,
  25023. call: call,
  25024. cameraFar: cameraFar,
  25025. cameraNear: cameraNear,
  25026. cameraNormalMatrix: cameraNormalMatrix,
  25027. cameraPosition: cameraPosition,
  25028. cameraProjectionMatrix: cameraProjectionMatrix,
  25029. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  25030. cameraViewMatrix: cameraViewMatrix,
  25031. cameraWorldMatrix: cameraWorldMatrix,
  25032. cbrt: cbrt,
  25033. cdl: cdl,
  25034. ceil: ceil,
  25035. checker: checker,
  25036. cineonToneMapping: cineonToneMapping,
  25037. clamp: clamp,
  25038. clearcoat: clearcoat,
  25039. clearcoatRoughness: clearcoatRoughness,
  25040. code: code,
  25041. color: color,
  25042. colorSpaceToWorking: colorSpaceToWorking,
  25043. colorToDirection: colorToDirection,
  25044. compute: compute,
  25045. cond: cond,
  25046. context: context,
  25047. convert: convert,
  25048. convertColorSpace: convertColorSpace,
  25049. convertToTexture: convertToTexture,
  25050. cos: cos,
  25051. cross: cross,
  25052. cubeTexture: cubeTexture,
  25053. dFdx: dFdx,
  25054. dFdy: dFdy,
  25055. dashSize: dashSize,
  25056. defaultBuildStages: defaultBuildStages,
  25057. defaultShaderStages: defaultShaderStages,
  25058. defined: defined,
  25059. degrees: degrees,
  25060. deltaTime: deltaTime,
  25061. densityFog: densityFog,
  25062. densityFogFactor: densityFogFactor,
  25063. depth: depth,
  25064. depthPass: depthPass,
  25065. difference: difference,
  25066. diffuseColor: diffuseColor,
  25067. directPointLight: directPointLight,
  25068. directionToColor: directionToColor,
  25069. dispersion: dispersion,
  25070. distance: distance,
  25071. div: div,
  25072. dodge: dodge,
  25073. dot: dot,
  25074. drawIndex: drawIndex,
  25075. dynamicBufferAttribute: dynamicBufferAttribute,
  25076. element: element,
  25077. emissive: emissive,
  25078. equal: equal,
  25079. equals: equals,
  25080. equirectUV: equirectUV,
  25081. exp: exp,
  25082. exp2: exp2,
  25083. expression: expression,
  25084. faceDirection: faceDirection,
  25085. faceForward: faceForward,
  25086. faceforward: faceforward,
  25087. float: float,
  25088. floor: floor,
  25089. fog: fog,
  25090. fract: fract,
  25091. frameGroup: frameGroup,
  25092. frameId: frameId,
  25093. frontFacing: frontFacing,
  25094. fwidth: fwidth,
  25095. gain: gain,
  25096. gapSize: gapSize,
  25097. getConstNodeType: getConstNodeType,
  25098. getCurrentStack: getCurrentStack,
  25099. getDirection: getDirection,
  25100. getDistanceAttenuation: getDistanceAttenuation,
  25101. getGeometryRoughness: getGeometryRoughness,
  25102. getNormalFromDepth: getNormalFromDepth,
  25103. getParallaxCorrectNormal: getParallaxCorrectNormal,
  25104. getRoughness: getRoughness,
  25105. getScreenPosition: getScreenPosition,
  25106. getShIrradianceAt: getShIrradianceAt,
  25107. getTextureIndex: getTextureIndex,
  25108. getViewPosition: getViewPosition,
  25109. glsl: glsl,
  25110. glslFn: glslFn,
  25111. grayscale: grayscale,
  25112. greaterThan: greaterThan,
  25113. greaterThanEqual: greaterThanEqual,
  25114. hash: hash,
  25115. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  25116. highpModelViewMatrix: highpModelViewMatrix,
  25117. hue: hue,
  25118. instance: instance,
  25119. instanceIndex: instanceIndex,
  25120. instancedArray: instancedArray,
  25121. instancedBufferAttribute: instancedBufferAttribute,
  25122. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  25123. instancedMesh: instancedMesh,
  25124. int: int,
  25125. inverseSqrt: inverseSqrt,
  25126. inversesqrt: inversesqrt,
  25127. invocationLocalIndex: invocationLocalIndex,
  25128. invocationSubgroupIndex: invocationSubgroupIndex,
  25129. ior: ior,
  25130. iridescence: iridescence,
  25131. iridescenceIOR: iridescenceIOR,
  25132. iridescenceThickness: iridescenceThickness,
  25133. ivec2: ivec2,
  25134. ivec3: ivec3,
  25135. ivec4: ivec4,
  25136. js: js,
  25137. label: label,
  25138. length: length,
  25139. lengthSq: lengthSq,
  25140. lessThan: lessThan,
  25141. lessThanEqual: lessThanEqual,
  25142. lightPosition: lightPosition,
  25143. lightProjectionUV: lightProjectionUV,
  25144. lightShadowMatrix: lightShadowMatrix,
  25145. lightTargetDirection: lightTargetDirection,
  25146. lightTargetPosition: lightTargetPosition,
  25147. lightViewPosition: lightViewPosition,
  25148. lightingContext: lightingContext,
  25149. lights: lights,
  25150. linearDepth: linearDepth,
  25151. linearToneMapping: linearToneMapping,
  25152. localId: localId,
  25153. log: log,
  25154. log2: log2,
  25155. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  25156. loop: loop,
  25157. luminance: luminance,
  25158. mat2: mat2,
  25159. mat3: mat3,
  25160. mat4: mat4,
  25161. matcapUV: matcapUV,
  25162. materialAO: materialAO,
  25163. materialAlphaTest: materialAlphaTest,
  25164. materialAnisotropy: materialAnisotropy,
  25165. materialAnisotropyVector: materialAnisotropyVector,
  25166. materialAttenuationColor: materialAttenuationColor,
  25167. materialAttenuationDistance: materialAttenuationDistance,
  25168. materialClearcoat: materialClearcoat,
  25169. materialClearcoatNormal: materialClearcoatNormal,
  25170. materialClearcoatRoughness: materialClearcoatRoughness,
  25171. materialColor: materialColor,
  25172. materialDispersion: materialDispersion,
  25173. materialEmissive: materialEmissive,
  25174. materialIOR: materialIOR,
  25175. materialIridescence: materialIridescence,
  25176. materialIridescenceIOR: materialIridescenceIOR,
  25177. materialIridescenceThickness: materialIridescenceThickness,
  25178. materialLightMap: materialLightMap,
  25179. materialLineDashOffset: materialLineDashOffset,
  25180. materialLineDashSize: materialLineDashSize,
  25181. materialLineGapSize: materialLineGapSize,
  25182. materialLineScale: materialLineScale,
  25183. materialLineWidth: materialLineWidth,
  25184. materialMetalness: materialMetalness,
  25185. materialNormal: materialNormal,
  25186. materialOpacity: materialOpacity,
  25187. materialPointWidth: materialPointWidth,
  25188. materialReference: materialReference,
  25189. materialReflectivity: materialReflectivity,
  25190. materialRefractionRatio: materialRefractionRatio,
  25191. materialRotation: materialRotation,
  25192. materialRoughness: materialRoughness,
  25193. materialSheen: materialSheen,
  25194. materialSheenRoughness: materialSheenRoughness,
  25195. materialShininess: materialShininess,
  25196. materialSpecular: materialSpecular,
  25197. materialSpecularColor: materialSpecularColor,
  25198. materialSpecularIntensity: materialSpecularIntensity,
  25199. materialSpecularStrength: materialSpecularStrength,
  25200. materialThickness: materialThickness,
  25201. materialTransmission: materialTransmission,
  25202. max: max$1,
  25203. maxMipLevel: maxMipLevel,
  25204. mediumpModelViewMatrix: mediumpModelViewMatrix,
  25205. metalness: metalness,
  25206. min: min$1,
  25207. mix: mix,
  25208. mixElement: mixElement,
  25209. mod: mod,
  25210. modInt: modInt,
  25211. modelDirection: modelDirection,
  25212. modelNormalMatrix: modelNormalMatrix,
  25213. modelPosition: modelPosition,
  25214. modelScale: modelScale,
  25215. modelViewMatrix: modelViewMatrix,
  25216. modelViewPosition: modelViewPosition,
  25217. modelViewProjection: modelViewProjection,
  25218. modelWorldMatrix: modelWorldMatrix,
  25219. modelWorldMatrixInverse: modelWorldMatrixInverse,
  25220. morphReference: morphReference,
  25221. mrt: mrt,
  25222. mul: mul,
  25223. mx_aastep: mx_aastep,
  25224. mx_cell_noise_float: mx_cell_noise_float,
  25225. mx_contrast: mx_contrast,
  25226. mx_fractal_noise_float: mx_fractal_noise_float,
  25227. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  25228. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  25229. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  25230. mx_hsvtorgb: mx_hsvtorgb,
  25231. mx_noise_float: mx_noise_float,
  25232. mx_noise_vec3: mx_noise_vec3,
  25233. mx_noise_vec4: mx_noise_vec4,
  25234. mx_ramplr: mx_ramplr,
  25235. mx_ramptb: mx_ramptb,
  25236. mx_rgbtohsv: mx_rgbtohsv,
  25237. mx_safepower: mx_safepower,
  25238. mx_splitlr: mx_splitlr,
  25239. mx_splittb: mx_splittb,
  25240. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  25241. mx_transform_uv: mx_transform_uv,
  25242. mx_worley_noise_float: mx_worley_noise_float,
  25243. mx_worley_noise_vec2: mx_worley_noise_vec2,
  25244. mx_worley_noise_vec3: mx_worley_noise_vec3,
  25245. negate: negate,
  25246. neutralToneMapping: neutralToneMapping,
  25247. nodeArray: nodeArray,
  25248. nodeImmutable: nodeImmutable,
  25249. nodeObject: nodeObject,
  25250. nodeObjects: nodeObjects,
  25251. nodeProxy: nodeProxy,
  25252. normalFlat: normalFlat,
  25253. normalGeometry: normalGeometry,
  25254. normalLocal: normalLocal,
  25255. normalMap: normalMap,
  25256. normalView: normalView,
  25257. normalWorld: normalWorld,
  25258. normalize: normalize,
  25259. not: not,
  25260. notEqual: notEqual,
  25261. numWorkgroups: numWorkgroups,
  25262. objectDirection: objectDirection,
  25263. objectGroup: objectGroup,
  25264. objectPosition: objectPosition,
  25265. objectScale: objectScale,
  25266. objectViewPosition: objectViewPosition,
  25267. objectWorldMatrix: objectWorldMatrix,
  25268. oneMinus: oneMinus,
  25269. or: or,
  25270. orthographicDepthToViewZ: orthographicDepthToViewZ,
  25271. oscSawtooth: oscSawtooth,
  25272. oscSine: oscSine,
  25273. oscSquare: oscSquare,
  25274. oscTriangle: oscTriangle,
  25275. output: output,
  25276. outputStruct: outputStruct,
  25277. overlay: overlay,
  25278. overloadingFn: overloadingFn,
  25279. parabola: parabola,
  25280. parallaxDirection: parallaxDirection,
  25281. parallaxUV: parallaxUV,
  25282. parameter: parameter,
  25283. pass: pass,
  25284. passTexture: passTexture,
  25285. pcurve: pcurve,
  25286. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  25287. pmremTexture: pmremTexture,
  25288. pointUV: pointUV,
  25289. pointWidth: pointWidth,
  25290. positionGeometry: positionGeometry,
  25291. positionLocal: positionLocal,
  25292. positionPrevious: positionPrevious,
  25293. positionView: positionView,
  25294. positionViewDirection: positionViewDirection,
  25295. positionWorld: positionWorld,
  25296. positionWorldDirection: positionWorldDirection,
  25297. posterize: posterize,
  25298. pow: pow,
  25299. pow2: pow2,
  25300. pow3: pow3,
  25301. pow4: pow4,
  25302. property: property,
  25303. radians: radians,
  25304. rand: rand,
  25305. range: range,
  25306. rangeFog: rangeFog,
  25307. rangeFogFactor: rangeFogFactor,
  25308. reciprocal: reciprocal,
  25309. reference: reference,
  25310. referenceBuffer: referenceBuffer,
  25311. reflect: reflect,
  25312. reflectVector: reflectVector,
  25313. reflectView: reflectView,
  25314. reflector: reflector,
  25315. refract: refract,
  25316. refractVector: refractVector,
  25317. refractView: refractView,
  25318. reinhardToneMapping: reinhardToneMapping,
  25319. remainder: remainder,
  25320. remap: remap,
  25321. remapClamp: remapClamp,
  25322. renderGroup: renderGroup,
  25323. renderOutput: renderOutput,
  25324. rendererReference: rendererReference,
  25325. rotate: rotate,
  25326. rotateUV: rotateUV,
  25327. roughness: roughness,
  25328. round: round,
  25329. rtt: rtt,
  25330. sRGBTransferEOTF: sRGBTransferEOTF,
  25331. sRGBTransferOETF: sRGBTransferOETF,
  25332. sampler: sampler,
  25333. saturate: saturate,
  25334. saturation: saturation,
  25335. screen: screen,
  25336. screenCoordinate: screenCoordinate,
  25337. screenSize: screenSize,
  25338. screenUV: screenUV,
  25339. scriptable: scriptable,
  25340. scriptableValue: scriptableValue,
  25341. select: select,
  25342. setCurrentStack: setCurrentStack,
  25343. shaderStages: shaderStages,
  25344. shadow: shadow,
  25345. shadowPositionWorld: shadowPositionWorld,
  25346. sharedUniformGroup: sharedUniformGroup,
  25347. sheen: sheen,
  25348. sheenRoughness: sheenRoughness,
  25349. shiftLeft: shiftLeft,
  25350. shiftRight: shiftRight,
  25351. shininess: shininess,
  25352. sign: sign,
  25353. sin: sin,
  25354. sinc: sinc,
  25355. skinning: skinning,
  25356. skinningReference: skinningReference,
  25357. smoothstep: smoothstep,
  25358. smoothstepElement: smoothstepElement,
  25359. specularColor: specularColor,
  25360. specularF90: specularF90,
  25361. spherizeUV: spherizeUV,
  25362. split: split,
  25363. spritesheetUV: spritesheetUV,
  25364. sqrt: sqrt,
  25365. stack: stack,
  25366. step: step,
  25367. storage: storage,
  25368. storageBarrier: storageBarrier,
  25369. storageObject: storageObject,
  25370. storageTexture: storageTexture,
  25371. string: string,
  25372. sub: sub,
  25373. subgroupIndex: subgroupIndex,
  25374. subgroupSize: subgroupSize,
  25375. tan: tan,
  25376. tangentGeometry: tangentGeometry,
  25377. tangentLocal: tangentLocal,
  25378. tangentView: tangentView,
  25379. tangentWorld: tangentWorld,
  25380. temp: temp,
  25381. texture: texture,
  25382. texture3D: texture3D,
  25383. textureBarrier: textureBarrier,
  25384. textureBicubic: textureBicubic,
  25385. textureCubeUV: textureCubeUV,
  25386. textureLoad: textureLoad,
  25387. textureSize: textureSize,
  25388. textureStore: textureStore,
  25389. thickness: thickness,
  25390. time: time,
  25391. timerDelta: timerDelta,
  25392. timerGlobal: timerGlobal,
  25393. timerLocal: timerLocal,
  25394. toOutputColorSpace: toOutputColorSpace,
  25395. toWorkingColorSpace: toWorkingColorSpace,
  25396. toneMapping: toneMapping,
  25397. toneMappingExposure: toneMappingExposure,
  25398. toonOutlinePass: toonOutlinePass,
  25399. transformDirection: transformDirection,
  25400. transformNormal: transformNormal,
  25401. transformNormalToView: transformNormalToView,
  25402. transformedBentNormalView: transformedBentNormalView,
  25403. transformedBitangentView: transformedBitangentView,
  25404. transformedBitangentWorld: transformedBitangentWorld,
  25405. transformedClearcoatNormalView: transformedClearcoatNormalView,
  25406. transformedNormalView: transformedNormalView,
  25407. transformedNormalWorld: transformedNormalWorld,
  25408. transformedTangentView: transformedTangentView,
  25409. transformedTangentWorld: transformedTangentWorld,
  25410. transmission: transmission,
  25411. transpose: transpose,
  25412. triNoise3D: triNoise3D,
  25413. triplanarTexture: triplanarTexture,
  25414. triplanarTextures: triplanarTextures,
  25415. trunc: trunc,
  25416. tslFn: tslFn,
  25417. uint: uint,
  25418. uniform: uniform,
  25419. uniformArray: uniformArray,
  25420. uniformGroup: uniformGroup,
  25421. uniforms: uniforms,
  25422. userData: userData,
  25423. uv: uv,
  25424. uvec2: uvec2,
  25425. uvec3: uvec3,
  25426. uvec4: uvec4,
  25427. varying: varying,
  25428. varyingProperty: varyingProperty,
  25429. vec2: vec2,
  25430. vec3: vec3,
  25431. vec4: vec4,
  25432. vectorComponents: vectorComponents,
  25433. velocity: velocity,
  25434. vertexColor: vertexColor,
  25435. vertexIndex: vertexIndex,
  25436. vertexStage: vertexStage,
  25437. vibrance: vibrance,
  25438. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  25439. viewZToOrthographicDepth: viewZToOrthographicDepth,
  25440. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  25441. viewport: viewport,
  25442. viewportBottomLeft: viewportBottomLeft,
  25443. viewportCoordinate: viewportCoordinate,
  25444. viewportDepthTexture: viewportDepthTexture,
  25445. viewportLinearDepth: viewportLinearDepth,
  25446. viewportMipTexture: viewportMipTexture,
  25447. viewportResolution: viewportResolution,
  25448. viewportSafeUV: viewportSafeUV,
  25449. viewportSharedTexture: viewportSharedTexture,
  25450. viewportSize: viewportSize,
  25451. viewportTexture: viewportTexture,
  25452. viewportTopLeft: viewportTopLeft,
  25453. viewportUV: viewportUV,
  25454. wgsl: wgsl,
  25455. wgslFn: wgslFn,
  25456. workgroupArray: workgroupArray,
  25457. workgroupBarrier: workgroupBarrier,
  25458. workgroupId: workgroupId,
  25459. workingToColorSpace: workingToColorSpace,
  25460. xor: xor
  25461. });
  25462. const _clearColor$1 = /*@__PURE__*/ new Color4();
  25463. class Background extends DataMap {
  25464. constructor( renderer, nodes ) {
  25465. super();
  25466. this.renderer = renderer;
  25467. this.nodes = nodes;
  25468. }
  25469. update( scene, renderList, renderContext ) {
  25470. const renderer = this.renderer;
  25471. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  25472. let forceClear = false;
  25473. if ( background === null ) {
  25474. // no background settings, use clear color configuration from the renderer
  25475. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  25476. _clearColor$1.a = renderer._clearColor.a;
  25477. } else if ( background.isColor === true ) {
  25478. // background is an opaque color
  25479. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  25480. _clearColor$1.a = 1;
  25481. forceClear = true;
  25482. } else if ( background.isNode === true ) {
  25483. const sceneData = this.get( scene );
  25484. const backgroundNode = background;
  25485. _clearColor$1.copy( renderer._clearColor );
  25486. let backgroundMesh = sceneData.backgroundMesh;
  25487. if ( backgroundMesh === undefined ) {
  25488. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  25489. // @TODO: Add Texture2D support using node context
  25490. getUV: () => backgroundRotation.mul( normalWorld ),
  25491. getTextureLevel: () => backgroundBlurriness
  25492. } );
  25493. let viewProj = modelViewProjection;
  25494. viewProj = viewProj.setZ( viewProj.w );
  25495. const nodeMaterial = new NodeMaterial();
  25496. nodeMaterial.name = 'Background.material';
  25497. nodeMaterial.side = BackSide;
  25498. nodeMaterial.depthTest = false;
  25499. nodeMaterial.depthWrite = false;
  25500. nodeMaterial.fog = false;
  25501. nodeMaterial.lights = false;
  25502. nodeMaterial.vertexNode = viewProj;
  25503. nodeMaterial.colorNode = backgroundMeshNode;
  25504. sceneData.backgroundMeshNode = backgroundMeshNode;
  25505. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  25506. backgroundMesh.frustumCulled = false;
  25507. backgroundMesh.name = 'Background.mesh';
  25508. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  25509. this.matrixWorld.copyPosition( camera.matrixWorld );
  25510. };
  25511. }
  25512. const backgroundCacheKey = backgroundNode.getCacheKey();
  25513. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  25514. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  25515. sceneData.backgroundMeshNode.needsUpdate = true;
  25516. backgroundMesh.material.needsUpdate = true;
  25517. sceneData.backgroundCacheKey = backgroundCacheKey;
  25518. }
  25519. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  25520. } else {
  25521. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  25522. }
  25523. //
  25524. if ( renderer.autoClear === true || forceClear === true ) {
  25525. const clearColorValue = renderContext.clearColorValue;
  25526. clearColorValue.r = _clearColor$1.r;
  25527. clearColorValue.g = _clearColor$1.g;
  25528. clearColorValue.b = _clearColor$1.b;
  25529. clearColorValue.a = _clearColor$1.a;
  25530. // premultiply alpha
  25531. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  25532. clearColorValue.r *= clearColorValue.a;
  25533. clearColorValue.g *= clearColorValue.a;
  25534. clearColorValue.b *= clearColorValue.a;
  25535. }
  25536. //
  25537. renderContext.depthClearValue = renderer._clearDepth;
  25538. renderContext.stencilClearValue = renderer._clearStencil;
  25539. renderContext.clearColor = renderer.autoClearColor === true;
  25540. renderContext.clearDepth = renderer.autoClearDepth === true;
  25541. renderContext.clearStencil = renderer.autoClearStencil === true;
  25542. } else {
  25543. renderContext.clearColor = false;
  25544. renderContext.clearDepth = false;
  25545. renderContext.clearStencil = false;
  25546. }
  25547. }
  25548. }
  25549. let _id$6 = 0;
  25550. class BindGroup {
  25551. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  25552. this.name = name;
  25553. this.bindings = bindings;
  25554. this.index = index;
  25555. this.bindingsReference = bindingsReference;
  25556. this.id = _id$6 ++;
  25557. }
  25558. }
  25559. class NodeBuilderState {
  25560. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  25561. this.vertexShader = vertexShader;
  25562. this.fragmentShader = fragmentShader;
  25563. this.computeShader = computeShader;
  25564. this.transforms = transforms;
  25565. this.nodeAttributes = nodeAttributes;
  25566. this.bindings = bindings;
  25567. this.updateNodes = updateNodes;
  25568. this.updateBeforeNodes = updateBeforeNodes;
  25569. this.updateAfterNodes = updateAfterNodes;
  25570. this.monitor = monitor;
  25571. this.usedTimes = 0;
  25572. }
  25573. createBindings() {
  25574. const bindings = [];
  25575. for ( const instanceGroup of this.bindings ) {
  25576. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  25577. if ( shared !== true ) {
  25578. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  25579. bindings.push( bindingsGroup );
  25580. for ( const instanceBinding of instanceGroup.bindings ) {
  25581. bindingsGroup.bindings.push( instanceBinding.clone() );
  25582. }
  25583. } else {
  25584. bindings.push( instanceGroup );
  25585. }
  25586. }
  25587. return bindings;
  25588. }
  25589. }
  25590. /**
  25591. * {@link NodeBuilder} is going to create instances of this class during the build process
  25592. * of nodes. They represent the final shader attributes that are going to be generated
  25593. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  25594. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  25595. */
  25596. class NodeAttribute {
  25597. /**
  25598. * Constructs a new node attribute.
  25599. *
  25600. * @param {String} name - The name of the attribute.
  25601. * @param {String} type - The type of the attribute.
  25602. * @param {Node?} node - An optional reference to the node.
  25603. */
  25604. constructor( name, type, node = null ) {
  25605. /**
  25606. * This flag can be used for type testing.
  25607. *
  25608. * @type {Boolean}
  25609. * @readonly
  25610. * @default true
  25611. */
  25612. this.isNodeAttribute = true;
  25613. /**
  25614. * The name of the attribute.
  25615. *
  25616. * @type {String}
  25617. */
  25618. this.name = name;
  25619. /**
  25620. * The type of the attribute.
  25621. *
  25622. * @type {String}
  25623. */
  25624. this.type = type;
  25625. /**
  25626. * An optional reference to the node.
  25627. *
  25628. * @type {Node?}
  25629. * @default null
  25630. */
  25631. this.node = node;
  25632. }
  25633. }
  25634. /**
  25635. * {@link NodeBuilder} is going to create instances of this class during the build process
  25636. * of nodes. They represent the final shader uniforms that are going to be generated
  25637. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  25638. * for this purpose.
  25639. */
  25640. class NodeUniform {
  25641. /**
  25642. * Constructs a new node uniform.
  25643. *
  25644. * @param {String} name - The name of the uniform.
  25645. * @param {String} type - The type of the uniform.
  25646. * @param {UniformNode} node - An reference to the node.
  25647. */
  25648. constructor( name, type, node ) {
  25649. /**
  25650. * This flag can be used for type testing.
  25651. *
  25652. * @type {Boolean}
  25653. * @readonly
  25654. * @default true
  25655. */
  25656. this.isNodeUniform = true;
  25657. /**
  25658. * The name of the uniform.
  25659. *
  25660. * @type {String}
  25661. */
  25662. this.name = name;
  25663. /**
  25664. * The type of the uniform.
  25665. *
  25666. * @type {String}
  25667. */
  25668. this.type = type;
  25669. /**
  25670. * An reference to the node.
  25671. *
  25672. * @type {UniformNode}
  25673. */
  25674. this.node = node.getSelf();
  25675. }
  25676. /**
  25677. * The value of the uniform node.
  25678. *
  25679. * @type {Any}
  25680. */
  25681. get value() {
  25682. return this.node.value;
  25683. }
  25684. set value( val ) {
  25685. this.node.value = val;
  25686. }
  25687. /**
  25688. * The id of the uniform node.
  25689. *
  25690. * @type {Number}
  25691. */
  25692. get id() {
  25693. return this.node.id;
  25694. }
  25695. /**
  25696. * The uniform node's group.
  25697. *
  25698. * @type {UniformGroupNode}
  25699. */
  25700. get groupNode() {
  25701. return this.node.groupNode;
  25702. }
  25703. }
  25704. /**
  25705. * {@link NodeBuilder} is going to create instances of this class during the build process
  25706. * of nodes. They represent the final shader variables that are going to be generated
  25707. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  25708. * this purpose.
  25709. */
  25710. class NodeVar {
  25711. /**
  25712. * Constructs a new node variable.
  25713. *
  25714. * @param {String} name - The name of the variable.
  25715. * @param {String} type - The type of the variable.
  25716. */
  25717. constructor( name, type ) {
  25718. /**
  25719. * This flag can be used for type testing.
  25720. *
  25721. * @type {Boolean}
  25722. * @readonly
  25723. * @default true
  25724. */
  25725. this.isNodeVar = true;
  25726. /**
  25727. * The name of the variable.
  25728. *
  25729. * @type {String}
  25730. */
  25731. this.name = name;
  25732. /**
  25733. * The type of the variable.
  25734. *
  25735. * @type {String}
  25736. */
  25737. this.type = type;
  25738. }
  25739. }
  25740. /**
  25741. * {@link NodeBuilder} is going to create instances of this class during the build process
  25742. * of nodes. They represent the final shader varyings that are going to be generated
  25743. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  25744. * this purpose.
  25745. *
  25746. * @augments NodeVar
  25747. */
  25748. class NodeVarying extends NodeVar {
  25749. /**
  25750. * Constructs a new node varying.
  25751. *
  25752. * @param {String} name - The name of the varying.
  25753. * @param {String} type - The type of the varying.
  25754. */
  25755. constructor( name, type ) {
  25756. super( name, type );
  25757. /**
  25758. * Whether this varying requires interpolation or not. This property can be used
  25759. * to check if the varying can be optimized for a variable.
  25760. *
  25761. * @type {Boolean}
  25762. * @default false
  25763. */
  25764. this.needsInterpolation = false;
  25765. /**
  25766. * This flag can be used for type testing.
  25767. *
  25768. * @type {Boolean}
  25769. * @readonly
  25770. * @default true
  25771. */
  25772. this.isNodeVarying = true;
  25773. }
  25774. }
  25775. /**
  25776. * {@link NodeBuilder} is going to create instances of this class during the build process
  25777. * of nodes. They represent user-defined, native shader code portions that are going to be
  25778. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  25779. * for this purpose.
  25780. */
  25781. class NodeCode {
  25782. /**
  25783. * Constructs a new code node.
  25784. *
  25785. * @param {String} name - The name of the code.
  25786. * @param {String} type - The node type.
  25787. * @param {String} [code=''] - The native shader code.
  25788. */
  25789. constructor( name, type, code = '' ) {
  25790. /**
  25791. * The name of the code.
  25792. *
  25793. * @type {String}
  25794. */
  25795. this.name = name;
  25796. /**
  25797. * The node type.
  25798. *
  25799. * @type {String}
  25800. */
  25801. this.type = type;
  25802. /**
  25803. * The native shader code.
  25804. *
  25805. * @type {String}
  25806. * @default ''
  25807. */
  25808. this.code = code;
  25809. Object.defineProperty( this, 'isNodeCode', { value: true } );
  25810. }
  25811. }
  25812. let _id$5 = 0;
  25813. /**
  25814. * This utility class is used in {@link NodeBuilder} as an internal
  25815. * cache data structure for node data.
  25816. */
  25817. class NodeCache {
  25818. /**
  25819. * Constructs a new node cache.
  25820. *
  25821. * @param {NodeCache?} parent - A reference to a parent cache.
  25822. */
  25823. constructor( parent = null ) {
  25824. /**
  25825. * The id of the cache.
  25826. *
  25827. * @type {Number}
  25828. * @readonly
  25829. */
  25830. this.id = _id$5 ++;
  25831. /**
  25832. * A weak map for managing node data.
  25833. *
  25834. * @type {WeakMap<Node, Object>}
  25835. */
  25836. this.nodesData = new WeakMap();
  25837. /**
  25838. * Reference to a parent node cache.
  25839. *
  25840. * @type {NodeCache?}
  25841. * @default null
  25842. */
  25843. this.parent = parent;
  25844. }
  25845. /**
  25846. * Returns the data for the given node.
  25847. *
  25848. * @param {Node} node - The node.
  25849. * @return {Object?} The data for the node.
  25850. */
  25851. getData( node ) {
  25852. let data = this.nodesData.get( node );
  25853. if ( data === undefined && this.parent !== null ) {
  25854. data = this.parent.getData( node );
  25855. }
  25856. return data;
  25857. }
  25858. /**
  25859. * Sets the data for a given node.
  25860. *
  25861. * @param {Node} node - The node.
  25862. * @param {Object} data - The data that should be cached.
  25863. */
  25864. setData( node, data ) {
  25865. this.nodesData.set( node, data );
  25866. }
  25867. }
  25868. /**
  25869. * {@link NodeBuilder} is going to create instances of this class during the build process
  25870. * of nodes. They represent the final shader struct data that are going to be generated
  25871. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  25872. * for this purpose.
  25873. */
  25874. class StructTypeNode extends Node {
  25875. static get type() {
  25876. return 'StructTypeNode';
  25877. }
  25878. /**
  25879. * Constructs a new struct type node.
  25880. *
  25881. * @param {String} name - The name of the struct.
  25882. * @param {Array<String>} types - An array of types.
  25883. */
  25884. constructor( name, types ) {
  25885. super();
  25886. /**
  25887. * The name of the struct.
  25888. *
  25889. * @type {String}
  25890. */
  25891. this.name = name;
  25892. /**
  25893. * An array of types.
  25894. *
  25895. * @type {Array<String>}
  25896. */
  25897. this.types = types;
  25898. /**
  25899. * This flag can be used for type testing.
  25900. *
  25901. * @type {Boolean}
  25902. * @readonly
  25903. * @default true
  25904. */
  25905. this.isStructTypeNode = true;
  25906. }
  25907. /**
  25908. * Returns the member types.
  25909. *
  25910. * @return {Array<String>} The types.
  25911. */
  25912. getMemberTypes() {
  25913. return this.types;
  25914. }
  25915. }
  25916. class Uniform {
  25917. constructor( name, value ) {
  25918. this.name = name;
  25919. this.value = value;
  25920. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  25921. this.itemSize = 0;
  25922. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  25923. }
  25924. setValue( value ) {
  25925. this.value = value;
  25926. }
  25927. getValue() {
  25928. return this.value;
  25929. }
  25930. }
  25931. class NumberUniform extends Uniform {
  25932. constructor( name, value = 0 ) {
  25933. super( name, value );
  25934. this.isNumberUniform = true;
  25935. this.boundary = 4;
  25936. this.itemSize = 1;
  25937. }
  25938. }
  25939. class Vector2Uniform extends Uniform {
  25940. constructor( name, value = new Vector2() ) {
  25941. super( name, value );
  25942. this.isVector2Uniform = true;
  25943. this.boundary = 8;
  25944. this.itemSize = 2;
  25945. }
  25946. }
  25947. class Vector3Uniform extends Uniform {
  25948. constructor( name, value = new Vector3() ) {
  25949. super( name, value );
  25950. this.isVector3Uniform = true;
  25951. this.boundary = 16;
  25952. this.itemSize = 3;
  25953. }
  25954. }
  25955. class Vector4Uniform extends Uniform {
  25956. constructor( name, value = new Vector4() ) {
  25957. super( name, value );
  25958. this.isVector4Uniform = true;
  25959. this.boundary = 16;
  25960. this.itemSize = 4;
  25961. }
  25962. }
  25963. class ColorUniform extends Uniform {
  25964. constructor( name, value = new Color() ) {
  25965. super( name, value );
  25966. this.isColorUniform = true;
  25967. this.boundary = 16;
  25968. this.itemSize = 3;
  25969. }
  25970. }
  25971. class Matrix3Uniform extends Uniform {
  25972. constructor( name, value = new Matrix3() ) {
  25973. super( name, value );
  25974. this.isMatrix3Uniform = true;
  25975. this.boundary = 48;
  25976. this.itemSize = 12;
  25977. }
  25978. }
  25979. class Matrix4Uniform extends Uniform {
  25980. constructor( name, value = new Matrix4() ) {
  25981. super( name, value );
  25982. this.isMatrix4Uniform = true;
  25983. this.boundary = 64;
  25984. this.itemSize = 16;
  25985. }
  25986. }
  25987. class NumberNodeUniform extends NumberUniform {
  25988. constructor( nodeUniform ) {
  25989. super( nodeUniform.name, nodeUniform.value );
  25990. this.nodeUniform = nodeUniform;
  25991. }
  25992. getValue() {
  25993. return this.nodeUniform.value;
  25994. }
  25995. getType() {
  25996. return this.nodeUniform.type;
  25997. }
  25998. }
  25999. class Vector2NodeUniform extends Vector2Uniform {
  26000. constructor( nodeUniform ) {
  26001. super( nodeUniform.name, nodeUniform.value );
  26002. this.nodeUniform = nodeUniform;
  26003. }
  26004. getValue() {
  26005. return this.nodeUniform.value;
  26006. }
  26007. getType() {
  26008. return this.nodeUniform.type;
  26009. }
  26010. }
  26011. class Vector3NodeUniform extends Vector3Uniform {
  26012. constructor( nodeUniform ) {
  26013. super( nodeUniform.name, nodeUniform.value );
  26014. this.nodeUniform = nodeUniform;
  26015. }
  26016. getValue() {
  26017. return this.nodeUniform.value;
  26018. }
  26019. getType() {
  26020. return this.nodeUniform.type;
  26021. }
  26022. }
  26023. class Vector4NodeUniform extends Vector4Uniform {
  26024. constructor( nodeUniform ) {
  26025. super( nodeUniform.name, nodeUniform.value );
  26026. this.nodeUniform = nodeUniform;
  26027. }
  26028. getValue() {
  26029. return this.nodeUniform.value;
  26030. }
  26031. getType() {
  26032. return this.nodeUniform.type;
  26033. }
  26034. }
  26035. class ColorNodeUniform extends ColorUniform {
  26036. constructor( nodeUniform ) {
  26037. super( nodeUniform.name, nodeUniform.value );
  26038. this.nodeUniform = nodeUniform;
  26039. }
  26040. getValue() {
  26041. return this.nodeUniform.value;
  26042. }
  26043. getType() {
  26044. return this.nodeUniform.type;
  26045. }
  26046. }
  26047. class Matrix3NodeUniform extends Matrix3Uniform {
  26048. constructor( nodeUniform ) {
  26049. super( nodeUniform.name, nodeUniform.value );
  26050. this.nodeUniform = nodeUniform;
  26051. }
  26052. getValue() {
  26053. return this.nodeUniform.value;
  26054. }
  26055. getType() {
  26056. return this.nodeUniform.type;
  26057. }
  26058. }
  26059. class Matrix4NodeUniform extends Matrix4Uniform {
  26060. constructor( nodeUniform ) {
  26061. super( nodeUniform.name, nodeUniform.value );
  26062. this.nodeUniform = nodeUniform;
  26063. }
  26064. getValue() {
  26065. return this.nodeUniform.value;
  26066. }
  26067. getType() {
  26068. return this.nodeUniform.type;
  26069. }
  26070. }
  26071. const LOD_MIN = 4;
  26072. // The standard deviations (radians) associated with the extra mips. These are
  26073. // chosen to approximate a Trowbridge-Reitz distribution function times the
  26074. // geometric shadowing function. These sigma values squared must match the
  26075. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  26076. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  26077. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  26078. // samples and exit early, but not recompile the shader.
  26079. const MAX_SAMPLES = 20;
  26080. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  26081. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  26082. const _clearColor = /*@__PURE__*/ new Color();
  26083. let _oldTarget = null;
  26084. let _oldActiveCubeFace = 0;
  26085. let _oldActiveMipmapLevel = 0;
  26086. // Golden Ratio
  26087. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  26088. const INV_PHI = 1 / PHI;
  26089. // Vertices of a dodecahedron (except the opposites, which represent the
  26090. // same axis), used as axis directions evenly spread on a sphere.
  26091. const _axisDirections = [
  26092. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  26093. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  26094. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  26095. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  26096. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  26097. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  26098. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  26099. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  26100. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  26101. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  26102. ];
  26103. //
  26104. // WebGPU Face indices
  26105. const _faceLib = [
  26106. 3, 1, 5,
  26107. 0, 4, 2
  26108. ];
  26109. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  26110. const outputDirection = vec3( direction.x, direction.y, direction.z );
  26111. /**
  26112. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  26113. * (PMREM) from a cubeMap environment texture. This allows different levels of
  26114. * blur to be quickly accessed based on material roughness. It is packed into a
  26115. * special CubeUV format that allows us to perform custom interpolation so that
  26116. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  26117. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  26118. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  26119. * higher roughness levels. In this way we maintain resolution to smoothly
  26120. * interpolate diffuse lighting while limiting sampling computation.
  26121. *
  26122. * Paper: Fast, Accurate Image-Based Lighting
  26123. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  26124. */
  26125. class PMREMGenerator {
  26126. constructor( renderer ) {
  26127. this._renderer = renderer;
  26128. this._pingPongRenderTarget = null;
  26129. this._lodMax = 0;
  26130. this._cubeSize = 0;
  26131. this._lodPlanes = [];
  26132. this._sizeLods = [];
  26133. this._sigmas = [];
  26134. this._lodMeshes = [];
  26135. this._blurMaterial = null;
  26136. this._cubemapMaterial = null;
  26137. this._equirectMaterial = null;
  26138. this._backgroundBox = null;
  26139. }
  26140. get _hasInitialized() {
  26141. return this._renderer.hasInitialized();
  26142. }
  26143. /**
  26144. * Generates a PMREM from a supplied Scene, which can be faster than using an
  26145. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  26146. * in radians to be applied to the scene before PMREM generation. Optional near
  26147. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  26148. * is placed at the origin).
  26149. *
  26150. * @param {Scene} scene - The scene to be captured.
  26151. * @param {Number} [sigma=0] - The blur radius in radians.
  26152. * @param {Number} [near=0.1] - The near plane distance.
  26153. * @param {Number} [far=100] - The far plane distance.
  26154. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  26155. * @return {RenderTarget} The resulting PMREM.
  26156. */
  26157. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  26158. this._setSize( 256 );
  26159. if ( this._hasInitialized === false ) {
  26160. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  26161. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  26162. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  26163. return cubeUVRenderTarget;
  26164. }
  26165. _oldTarget = this._renderer.getRenderTarget();
  26166. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  26167. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  26168. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  26169. cubeUVRenderTarget.depthBuffer = true;
  26170. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  26171. if ( sigma > 0 ) {
  26172. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  26173. }
  26174. this._applyPMREM( cubeUVRenderTarget );
  26175. this._cleanup( cubeUVRenderTarget );
  26176. return cubeUVRenderTarget;
  26177. }
  26178. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  26179. if ( this._hasInitialized === false ) await this._renderer.init();
  26180. return this.fromScene( scene, sigma, near, far, renderTarget );
  26181. }
  26182. /**
  26183. * Generates a PMREM from an equirectangular texture, which can be either LDR
  26184. * or HDR. The ideal input image size is 1k (1024 x 512),
  26185. * as this matches best with the 256 x 256 cubemap output.
  26186. *
  26187. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  26188. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  26189. * @return {RenderTarget} The resulting PMREM.
  26190. */
  26191. fromEquirectangular( equirectangular, renderTarget = null ) {
  26192. if ( this._hasInitialized === false ) {
  26193. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  26194. this._setSizeFromTexture( equirectangular );
  26195. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  26196. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  26197. return cubeUVRenderTarget;
  26198. }
  26199. return this._fromTexture( equirectangular, renderTarget );
  26200. }
  26201. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  26202. if ( this._hasInitialized === false ) await this._renderer.init();
  26203. return this._fromTexture( equirectangular, renderTarget );
  26204. }
  26205. /**
  26206. * Generates a PMREM from an cubemap texture, which can be either LDR
  26207. * or HDR. The ideal input cube size is 256 x 256,
  26208. * as this matches best with the 256 x 256 cubemap output.
  26209. *
  26210. * @param {Texture} cubemap - The cubemap texture to be converted.
  26211. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  26212. * @return {RenderTarget} The resulting PMREM.
  26213. */
  26214. fromCubemap( cubemap, renderTarget = null ) {
  26215. if ( this._hasInitialized === false ) {
  26216. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  26217. this._setSizeFromTexture( cubemap );
  26218. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  26219. this.fromCubemapAsync( cubemap, renderTarget );
  26220. return cubeUVRenderTarget;
  26221. }
  26222. return this._fromTexture( cubemap, renderTarget );
  26223. }
  26224. async fromCubemapAsync( cubemap, renderTarget = null ) {
  26225. if ( this._hasInitialized === false ) await this._renderer.init();
  26226. return this._fromTexture( cubemap, renderTarget );
  26227. }
  26228. /**
  26229. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  26230. * your texture's network fetch for increased concurrency.
  26231. */
  26232. async compileCubemapShader() {
  26233. if ( this._cubemapMaterial === null ) {
  26234. this._cubemapMaterial = _getCubemapMaterial();
  26235. await this._compileMaterial( this._cubemapMaterial );
  26236. }
  26237. }
  26238. /**
  26239. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  26240. * your texture's network fetch for increased concurrency.
  26241. */
  26242. async compileEquirectangularShader() {
  26243. if ( this._equirectMaterial === null ) {
  26244. this._equirectMaterial = _getEquirectMaterial();
  26245. await this._compileMaterial( this._equirectMaterial );
  26246. }
  26247. }
  26248. /**
  26249. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  26250. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  26251. * one of them will cause any others to also become unusable.
  26252. */
  26253. dispose() {
  26254. this._dispose();
  26255. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  26256. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  26257. if ( this._backgroundBox !== null ) {
  26258. this._backgroundBox.geometry.dispose();
  26259. this._backgroundBox.material.dispose();
  26260. }
  26261. }
  26262. // private interface
  26263. _setSizeFromTexture( texture ) {
  26264. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  26265. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  26266. } else { // Equirectangular
  26267. this._setSize( texture.image.width / 4 );
  26268. }
  26269. }
  26270. _setSize( cubeSize ) {
  26271. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  26272. this._cubeSize = Math.pow( 2, this._lodMax );
  26273. }
  26274. _dispose() {
  26275. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  26276. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  26277. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  26278. this._lodPlanes[ i ].dispose();
  26279. }
  26280. }
  26281. _cleanup( outputTarget ) {
  26282. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  26283. outputTarget.scissorTest = false;
  26284. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  26285. }
  26286. _fromTexture( texture, renderTarget ) {
  26287. this._setSizeFromTexture( texture );
  26288. _oldTarget = this._renderer.getRenderTarget();
  26289. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  26290. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  26291. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  26292. this._textureToCubeUV( texture, cubeUVRenderTarget );
  26293. this._applyPMREM( cubeUVRenderTarget );
  26294. this._cleanup( cubeUVRenderTarget );
  26295. return cubeUVRenderTarget;
  26296. }
  26297. _allocateTargets() {
  26298. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  26299. const height = 4 * this._cubeSize;
  26300. const params = {
  26301. magFilter: LinearFilter,
  26302. minFilter: LinearFilter,
  26303. generateMipmaps: false,
  26304. type: HalfFloatType,
  26305. format: RGBAFormat,
  26306. colorSpace: LinearSRGBColorSpace,
  26307. //depthBuffer: false
  26308. };
  26309. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  26310. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  26311. if ( this._pingPongRenderTarget !== null ) {
  26312. this._dispose();
  26313. }
  26314. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  26315. const { _lodMax } = this;
  26316. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  26317. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  26318. }
  26319. return cubeUVRenderTarget;
  26320. }
  26321. async _compileMaterial( material ) {
  26322. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  26323. await this._renderer.compile( tmpMesh, _flatCamera );
  26324. }
  26325. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  26326. const cubeCamera = _cubeCamera;
  26327. cubeCamera.near = near;
  26328. cubeCamera.far = far;
  26329. // px, py, pz, nx, ny, nz
  26330. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  26331. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  26332. const renderer = this._renderer;
  26333. const originalAutoClear = renderer.autoClear;
  26334. renderer.getClearColor( _clearColor );
  26335. renderer.autoClear = false;
  26336. let backgroundBox = this._backgroundBox;
  26337. if ( backgroundBox === null ) {
  26338. const backgroundMaterial = new MeshBasicMaterial( {
  26339. name: 'PMREM.Background',
  26340. side: BackSide,
  26341. depthWrite: false,
  26342. depthTest: false
  26343. } );
  26344. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  26345. }
  26346. let useSolidColor = false;
  26347. const background = scene.background;
  26348. if ( background ) {
  26349. if ( background.isColor ) {
  26350. backgroundBox.material.color.copy( background );
  26351. scene.background = null;
  26352. useSolidColor = true;
  26353. }
  26354. } else {
  26355. backgroundBox.material.color.copy( _clearColor );
  26356. useSolidColor = true;
  26357. }
  26358. renderer.setRenderTarget( cubeUVRenderTarget );
  26359. renderer.clear();
  26360. if ( useSolidColor ) {
  26361. renderer.render( backgroundBox, cubeCamera );
  26362. }
  26363. for ( let i = 0; i < 6; i ++ ) {
  26364. const col = i % 3;
  26365. if ( col === 0 ) {
  26366. cubeCamera.up.set( 0, upSign[ i ], 0 );
  26367. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  26368. } else if ( col === 1 ) {
  26369. cubeCamera.up.set( 0, 0, upSign[ i ] );
  26370. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  26371. } else {
  26372. cubeCamera.up.set( 0, upSign[ i ], 0 );
  26373. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  26374. }
  26375. const size = this._cubeSize;
  26376. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  26377. renderer.render( scene, cubeCamera );
  26378. }
  26379. renderer.autoClear = originalAutoClear;
  26380. scene.background = background;
  26381. }
  26382. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  26383. const renderer = this._renderer;
  26384. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  26385. if ( isCubeTexture ) {
  26386. if ( this._cubemapMaterial === null ) {
  26387. this._cubemapMaterial = _getCubemapMaterial( texture );
  26388. }
  26389. } else {
  26390. if ( this._equirectMaterial === null ) {
  26391. this._equirectMaterial = _getEquirectMaterial( texture );
  26392. }
  26393. }
  26394. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  26395. material.fragmentNode.value = texture;
  26396. const mesh = this._lodMeshes[ 0 ];
  26397. mesh.material = material;
  26398. const size = this._cubeSize;
  26399. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  26400. renderer.setRenderTarget( cubeUVRenderTarget );
  26401. renderer.render( mesh, _flatCamera );
  26402. }
  26403. _applyPMREM( cubeUVRenderTarget ) {
  26404. const renderer = this._renderer;
  26405. const autoClear = renderer.autoClear;
  26406. renderer.autoClear = false;
  26407. const n = this._lodPlanes.length;
  26408. for ( let i = 1; i < n; i ++ ) {
  26409. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  26410. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  26411. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  26412. }
  26413. renderer.autoClear = autoClear;
  26414. }
  26415. /**
  26416. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  26417. * vertically and horizontally, but this breaks down on a cube. Here we apply
  26418. * the blur latitudinally (around the poles), and then longitudinally (towards
  26419. * the poles) to approximate the orthogonally-separable blur. It is least
  26420. * accurate at the poles, but still does a decent job.
  26421. *
  26422. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  26423. * @param {Number} lodIn - The input level-of-detail.
  26424. * @param {Number} lodOut - The output level-of-detail.
  26425. * @param {Number} sigma - The blur radius in radians.
  26426. * @param {Vector3} [poleAxis] - The pole axis.
  26427. */
  26428. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  26429. const pingPongRenderTarget = this._pingPongRenderTarget;
  26430. this._halfBlur(
  26431. cubeUVRenderTarget,
  26432. pingPongRenderTarget,
  26433. lodIn,
  26434. lodOut,
  26435. sigma,
  26436. 'latitudinal',
  26437. poleAxis );
  26438. this._halfBlur(
  26439. pingPongRenderTarget,
  26440. cubeUVRenderTarget,
  26441. lodOut,
  26442. lodOut,
  26443. sigma,
  26444. 'longitudinal',
  26445. poleAxis );
  26446. }
  26447. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  26448. const renderer = this._renderer;
  26449. const blurMaterial = this._blurMaterial;
  26450. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  26451. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  26452. }
  26453. // Number of standard deviations at which to cut off the discrete approximation.
  26454. const STANDARD_DEVIATIONS = 3;
  26455. const blurMesh = this._lodMeshes[ lodOut ];
  26456. blurMesh.material = blurMaterial;
  26457. const blurUniforms = blurMaterial.uniforms;
  26458. const pixels = this._sizeLods[ lodIn ] - 1;
  26459. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  26460. const sigmaPixels = sigmaRadians / radiansPerPixel;
  26461. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  26462. if ( samples > MAX_SAMPLES ) {
  26463. console.warn( `sigmaRadians, ${
  26464. sigmaRadians}, is too large and will clip, as it requested ${
  26465. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  26466. }
  26467. const weights = [];
  26468. let sum = 0;
  26469. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  26470. const x = i / sigmaPixels;
  26471. const weight = Math.exp( - x * x / 2 );
  26472. weights.push( weight );
  26473. if ( i === 0 ) {
  26474. sum += weight;
  26475. } else if ( i < samples ) {
  26476. sum += 2 * weight;
  26477. }
  26478. }
  26479. for ( let i = 0; i < weights.length; i ++ ) {
  26480. weights[ i ] = weights[ i ] / sum;
  26481. }
  26482. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  26483. blurUniforms.envMap.value = targetIn.texture;
  26484. blurUniforms.samples.value = samples;
  26485. blurUniforms.weights.array = weights;
  26486. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  26487. if ( poleAxis ) {
  26488. blurUniforms.poleAxis.value = poleAxis;
  26489. }
  26490. const { _lodMax } = this;
  26491. blurUniforms.dTheta.value = radiansPerPixel;
  26492. blurUniforms.mipInt.value = _lodMax - lodIn;
  26493. const outputSize = this._sizeLods[ lodOut ];
  26494. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  26495. const y = 4 * ( this._cubeSize - outputSize );
  26496. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  26497. renderer.setRenderTarget( targetOut );
  26498. renderer.render( blurMesh, _flatCamera );
  26499. }
  26500. }
  26501. function _createPlanes( lodMax ) {
  26502. const lodPlanes = [];
  26503. const sizeLods = [];
  26504. const sigmas = [];
  26505. const lodMeshes = [];
  26506. let lod = lodMax;
  26507. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  26508. for ( let i = 0; i < totalLods; i ++ ) {
  26509. const sizeLod = Math.pow( 2, lod );
  26510. sizeLods.push( sizeLod );
  26511. let sigma = 1.0 / sizeLod;
  26512. if ( i > lodMax - LOD_MIN ) {
  26513. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  26514. } else if ( i === 0 ) {
  26515. sigma = 0;
  26516. }
  26517. sigmas.push( sigma );
  26518. const texelSize = 1.0 / ( sizeLod - 2 );
  26519. const min = - texelSize;
  26520. const max = 1 + texelSize;
  26521. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  26522. const cubeFaces = 6;
  26523. const vertices = 6;
  26524. const positionSize = 3;
  26525. const uvSize = 2;
  26526. const faceIndexSize = 1;
  26527. const position = new Float32Array( positionSize * vertices * cubeFaces );
  26528. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  26529. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  26530. for ( let face = 0; face < cubeFaces; face ++ ) {
  26531. const x = ( face % 3 ) * 2 / 3 - 1;
  26532. const y = face > 2 ? 0 : - 1;
  26533. const coordinates = [
  26534. x, y, 0,
  26535. x + 2 / 3, y, 0,
  26536. x + 2 / 3, y + 1, 0,
  26537. x, y, 0,
  26538. x + 2 / 3, y + 1, 0,
  26539. x, y + 1, 0
  26540. ];
  26541. const faceIdx = _faceLib[ face ];
  26542. position.set( coordinates, positionSize * vertices * faceIdx );
  26543. uv.set( uv1, uvSize * vertices * faceIdx );
  26544. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  26545. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  26546. }
  26547. const planes = new BufferGeometry();
  26548. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  26549. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  26550. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  26551. lodPlanes.push( planes );
  26552. lodMeshes.push( new Mesh( planes, null ) );
  26553. if ( lod > LOD_MIN ) {
  26554. lod --;
  26555. }
  26556. }
  26557. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  26558. }
  26559. function _createRenderTarget( width, height, params ) {
  26560. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  26561. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  26562. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  26563. cubeUVRenderTarget.texture.isPMREMTexture = true;
  26564. cubeUVRenderTarget.scissorTest = true;
  26565. return cubeUVRenderTarget;
  26566. }
  26567. function _setViewport( target, x, y, width, height ) {
  26568. target.viewport.set( x, y, width, height );
  26569. target.scissor.set( x, y, width, height );
  26570. }
  26571. function _getMaterial( type ) {
  26572. const material = new NodeMaterial();
  26573. material.depthTest = false;
  26574. material.depthWrite = false;
  26575. material.blending = NoBlending;
  26576. material.name = `PMREM_${ type }`;
  26577. return material;
  26578. }
  26579. function _getBlurShader( lodMax, width, height ) {
  26580. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  26581. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  26582. const dTheta = uniform( 0 );
  26583. const n = float( MAX_SAMPLES );
  26584. const latitudinal = uniform( 0 ); // false, bool
  26585. const samples = uniform( 1 ); // int
  26586. const envMap = texture( null );
  26587. const mipInt = uniform( 0 ); // int
  26588. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  26589. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  26590. const CUBEUV_MAX_MIP = float( lodMax );
  26591. const materialUniforms = {
  26592. n,
  26593. latitudinal,
  26594. weights,
  26595. poleAxis,
  26596. outputDirection,
  26597. dTheta,
  26598. samples,
  26599. envMap,
  26600. mipInt,
  26601. CUBEUV_TEXEL_WIDTH,
  26602. CUBEUV_TEXEL_HEIGHT,
  26603. CUBEUV_MAX_MIP
  26604. };
  26605. const material = _getMaterial( 'blur' );
  26606. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  26607. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  26608. return material;
  26609. }
  26610. function _getCubemapMaterial( envTexture ) {
  26611. const material = _getMaterial( 'cubemap' );
  26612. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  26613. return material;
  26614. }
  26615. function _getEquirectMaterial( envTexture ) {
  26616. const material = _getMaterial( 'equirect' );
  26617. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  26618. return material;
  26619. }
  26620. const rendererCache = new WeakMap();
  26621. const typeFromArray = new Map( [
  26622. [ Int8Array, 'int' ],
  26623. [ Int16Array, 'int' ],
  26624. [ Int32Array, 'int' ],
  26625. [ Uint8Array, 'uint' ],
  26626. [ Uint16Array, 'uint' ],
  26627. [ Uint32Array, 'uint' ],
  26628. [ Float32Array, 'float' ]
  26629. ] );
  26630. const toFloat = ( value ) => {
  26631. if ( /e/g.test( value ) ) {
  26632. return String( value ).replace( /\+/g, '' );
  26633. } else {
  26634. value = Number( value );
  26635. return value + ( value % 1 ? '' : '.0' );
  26636. }
  26637. };
  26638. /**
  26639. * Base class for builders which generate a shader program based
  26640. * on a 3D object and its node material definition.
  26641. */
  26642. class NodeBuilder {
  26643. /**
  26644. * Constructs a new node builder.
  26645. *
  26646. * @param {Object3D} object - The 3D object.
  26647. * @param {Renderer} renderer - The current renderer.
  26648. * @param {NodeParser} parser - A reference to a node parser.
  26649. */
  26650. constructor( object, renderer, parser ) {
  26651. /**
  26652. * The 3D object.
  26653. *
  26654. * @type {Object3D}
  26655. */
  26656. this.object = object;
  26657. /**
  26658. * The material of the 3D object.
  26659. *
  26660. * @type {Material?}
  26661. */
  26662. this.material = ( object && object.material ) || null;
  26663. /**
  26664. * The geometry of the 3D object.
  26665. *
  26666. * @type {BufferGeometry?}
  26667. */
  26668. this.geometry = ( object && object.geometry ) || null;
  26669. /**
  26670. * The current renderer.
  26671. *
  26672. * @type {Renderer}
  26673. */
  26674. this.renderer = renderer;
  26675. /**
  26676. * A reference to a node parser.
  26677. *
  26678. * @type {NodeParser}
  26679. */
  26680. this.parser = parser;
  26681. /**
  26682. * The scene the 3D object belongs to.
  26683. *
  26684. * @type {Scene?}
  26685. * @default null
  26686. */
  26687. this.scene = null;
  26688. /**
  26689. * The camera the 3D object is rendered with.
  26690. *
  26691. * @type {Camera?}
  26692. * @default null
  26693. */
  26694. this.camera = null;
  26695. /**
  26696. * A list of all nodes the builder is processing
  26697. * for this 3D object.
  26698. *
  26699. * @type {Array<Node>}
  26700. */
  26701. this.nodes = [];
  26702. /**
  26703. * A list of all sequential nodes.
  26704. *
  26705. * @type {Array<Node>}
  26706. */
  26707. this.sequentialNodes = [];
  26708. /**
  26709. * A list of all nodes which {@link Node#update} method should be executed.
  26710. *
  26711. * @type {Array<Node>}
  26712. */
  26713. this.updateNodes = [];
  26714. /**
  26715. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  26716. *
  26717. * @type {Array<Node>}
  26718. */
  26719. this.updateBeforeNodes = [];
  26720. /**
  26721. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  26722. *
  26723. * @type {Array<Node>}
  26724. */
  26725. this.updateAfterNodes = [];
  26726. /**
  26727. * A dictionary that assigns each node to a unique hash.
  26728. *
  26729. * @type {Object<Number,Node>}
  26730. */
  26731. this.hashNodes = {};
  26732. /**
  26733. * A reference to a node material observer.
  26734. *
  26735. * @type {NodeMaterialObserver?}
  26736. * @default null
  26737. */
  26738. this.monitor = null;
  26739. /**
  26740. * A reference to the current lights node.
  26741. *
  26742. * @type {LightsNode?}
  26743. * @default null
  26744. */
  26745. this.lightsNode = null;
  26746. /**
  26747. * A reference to the current environment node.
  26748. *
  26749. * @type {Node?}
  26750. * @default null
  26751. */
  26752. this.environmentNode = null;
  26753. /**
  26754. * A reference to the current fog node.
  26755. *
  26756. * @type {FogNode?}
  26757. * @default null
  26758. */
  26759. this.fogNode = null;
  26760. /**
  26761. * The current clipping context.
  26762. *
  26763. * @type {ClippingContext?}
  26764. */
  26765. this.clippingContext = null;
  26766. /**
  26767. * The generated vertex shader.
  26768. *
  26769. * @type {String?}
  26770. */
  26771. this.vertexShader = null;
  26772. /**
  26773. * The generated fragment shader.
  26774. *
  26775. * @type {String?}
  26776. */
  26777. this.fragmentShader = null;
  26778. /**
  26779. * The generated compute shader.
  26780. *
  26781. * @type {String?}
  26782. */
  26783. this.computeShader = null;
  26784. /**
  26785. * Nodes used in the primary flow of code generation.
  26786. *
  26787. * @type {Object<String,Array<Node>>}
  26788. */
  26789. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  26790. /**
  26791. * Nodes code from `.flowNodes`.
  26792. *
  26793. * @type {Object<String,String>}
  26794. */
  26795. this.flowCode = { vertex: '', fragment: '', compute: '' };
  26796. /**
  26797. * This dictionary holds the node uniforms of the builder.
  26798. * The uniforms are maintained in an array for each shader stage.
  26799. *
  26800. * @type {Object}
  26801. */
  26802. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  26803. /**
  26804. * This dictionary holds the output structs of the builder.
  26805. * The structs are maintained in an array for each shader stage.
  26806. *
  26807. * @type {Object}
  26808. */
  26809. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  26810. /**
  26811. * This dictionary holds the bindings for each shader stage.
  26812. *
  26813. * @type {Object}
  26814. */
  26815. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  26816. /**
  26817. * This dictionary maintains the binding indices per bind group.
  26818. *
  26819. * @type {Object}
  26820. */
  26821. this.bindingsIndexes = {};
  26822. /**
  26823. * Reference to the array of bind groups.
  26824. *
  26825. * @type {Array<BindGroup>?}
  26826. */
  26827. this.bindGroups = null;
  26828. /**
  26829. * This array holds the node attributes of this builder
  26830. * created via {@link AttributeNode}.
  26831. *
  26832. * @type {Array<NodeAttribute>}
  26833. */
  26834. this.attributes = [];
  26835. /**
  26836. * This array holds the node attributes of this builder
  26837. * created via {@link BufferAttributeNode}.
  26838. *
  26839. * @type {Array<NodeAttribute>}
  26840. */
  26841. this.bufferAttributes = [];
  26842. /**
  26843. * This array holds the node varyings of this builder.
  26844. *
  26845. * @type {Array<NodeVarying>}
  26846. */
  26847. this.varyings = [];
  26848. /**
  26849. * This dictionary holds the (native) node codes of this builder.
  26850. * The codes are maintained in an array for each shader stage.
  26851. *
  26852. * @type {Object<String,Array<NodeCode>>}
  26853. */
  26854. this.codes = {};
  26855. /**
  26856. * This dictionary holds the node variables of this builder.
  26857. * The variables are maintained in an array for each shader stage.
  26858. *
  26859. * @type {Object<String,Array<NodeVar>>}
  26860. */
  26861. this.vars = {};
  26862. /**
  26863. * Current code flow.
  26864. * All code generated in this stack will be stored in `.flow`.
  26865. *
  26866. * @type {{code: String}}
  26867. */
  26868. this.flow = { code: '' };
  26869. /**
  26870. * A chain of nodes.
  26871. * Used to check recursive calls in node-graph.
  26872. *
  26873. * @type {Array<Node>}
  26874. */
  26875. this.chaining = [];
  26876. /**
  26877. * The current stack.
  26878. * This reflects the current process in the code block hierarchy,
  26879. * it is useful to know if the current process is inside a conditional for example.
  26880. *
  26881. * @type {StackNode}
  26882. */
  26883. this.stack = stack();
  26884. /**
  26885. * List of stack nodes.
  26886. * The current stack hierarchy is stored in an array.
  26887. *
  26888. * @type {Array<StackNode>}
  26889. */
  26890. this.stacks = [];
  26891. /**
  26892. * A tab value. Used for shader string generation.
  26893. *
  26894. * @type {String}
  26895. * @default '\t'
  26896. */
  26897. this.tab = '\t';
  26898. /**
  26899. * Reference to the current function node.
  26900. *
  26901. * @type {FunctionNode?}
  26902. * @default null
  26903. */
  26904. this.currentFunctionNode = null;
  26905. /**
  26906. * The builder's context.
  26907. *
  26908. * @type {Object}
  26909. */
  26910. this.context = {
  26911. material: this.material
  26912. };
  26913. /**
  26914. * The builder's cache.
  26915. *
  26916. * @type {NodeCache}
  26917. */
  26918. this.cache = new NodeCache();
  26919. /**
  26920. * Since the {@link NodeBuilder#cache} might be temporarily
  26921. * overwritten by other caches, this member retains the reference
  26922. * to the builder's own cache.
  26923. *
  26924. * @type {NodeCache}
  26925. * @default this.cache
  26926. */
  26927. this.globalCache = this.cache;
  26928. this.flowsData = new WeakMap();
  26929. /**
  26930. * The current shader stage.
  26931. *
  26932. * @type {('vertex'|'fragment'|'compute'|'any')?}
  26933. */
  26934. this.shaderStage = null;
  26935. /**
  26936. * The current build stage.
  26937. *
  26938. * @type {('setup'|'analyze'|'generate')?}
  26939. */
  26940. this.buildStage = null;
  26941. /**
  26942. * Whether comparison in shader code are generated with methods or not.
  26943. *
  26944. * @type {Boolean}
  26945. * @default false
  26946. */
  26947. this.useComparisonMethod = false;
  26948. }
  26949. /**
  26950. * Returns the bind groups of the current renderer.
  26951. *
  26952. * @return {ChainMap} The cache.
  26953. */
  26954. getBindGroupsCache() {
  26955. let bindGroupsCache = rendererCache.get( this.renderer );
  26956. if ( bindGroupsCache === undefined ) {
  26957. bindGroupsCache = new ChainMap();
  26958. rendererCache.set( this.renderer, bindGroupsCache );
  26959. }
  26960. return bindGroupsCache;
  26961. }
  26962. /**
  26963. * Factory method for creating an instance of {@link RenderTarget} with the given
  26964. * dimensions and options.
  26965. *
  26966. * @param {Number} width - The width of the render target.
  26967. * @param {Number} height - The height of the render target.
  26968. * @param {Object} options - The options of the render target.
  26969. * @return {RenderTarget} The render target.
  26970. */
  26971. createRenderTarget( width, height, options ) {
  26972. return new RenderTarget( width, height, options );
  26973. }
  26974. /**
  26975. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  26976. * dimensions and options.
  26977. *
  26978. * @param {Number} size - The size of the cube render target.
  26979. * @param {Object} options - The options of the cube render target.
  26980. * @return {CubeRenderTarget} The cube render target.
  26981. */
  26982. createCubeRenderTarget( size, options ) {
  26983. return new CubeRenderTarget( size, options );
  26984. }
  26985. /**
  26986. * Factory method for creating an instance of {@link PMREMGenerator}.
  26987. *
  26988. * @return {PMREMGenerator} The PMREM generator.
  26989. */
  26990. createPMREMGenerator() {
  26991. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  26992. return new PMREMGenerator( this.renderer );
  26993. }
  26994. /**
  26995. * Whether the given node is included in the internal array of nodes or not.
  26996. *
  26997. * @param {Node} node - The node to test.
  26998. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  26999. */
  27000. includes( node ) {
  27001. return this.nodes.includes( node );
  27002. }
  27003. /**
  27004. * Returns a bind group for the given group name and binding.
  27005. *
  27006. * @private
  27007. * @param {String} groupName - The group name.
  27008. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  27009. * @return {BindGroup} The bind group
  27010. */
  27011. _getBindGroup( groupName, bindings ) {
  27012. const bindGroupsCache = this.getBindGroupsCache();
  27013. //
  27014. const bindingsArray = [];
  27015. let sharedGroup = true;
  27016. for ( const binding of bindings ) {
  27017. bindingsArray.push( binding );
  27018. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  27019. }
  27020. //
  27021. let bindGroup;
  27022. if ( sharedGroup ) {
  27023. bindGroup = bindGroupsCache.get( bindingsArray );
  27024. if ( bindGroup === undefined ) {
  27025. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  27026. bindGroupsCache.set( bindingsArray, bindGroup );
  27027. }
  27028. } else {
  27029. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  27030. }
  27031. return bindGroup;
  27032. }
  27033. /**
  27034. * Returns an array of node uniform groups for the given group name and shader stage.
  27035. *
  27036. * @param {String} groupName - The group name.
  27037. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  27038. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  27039. */
  27040. getBindGroupArray( groupName, shaderStage ) {
  27041. const bindings = this.bindings[ shaderStage ];
  27042. let bindGroup = bindings[ groupName ];
  27043. if ( bindGroup === undefined ) {
  27044. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  27045. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  27046. }
  27047. bindings[ groupName ] = bindGroup = [];
  27048. }
  27049. return bindGroup;
  27050. }
  27051. /**
  27052. * Returns a list bindings of all shader stages separated by groups.
  27053. *
  27054. * @return {Array<BindGroup>} The list of bindings.
  27055. */
  27056. getBindings() {
  27057. let bindingsGroups = this.bindGroups;
  27058. if ( bindingsGroups === null ) {
  27059. const groups = {};
  27060. const bindings = this.bindings;
  27061. for ( const shaderStage of shaderStages ) {
  27062. for ( const groupName in bindings[ shaderStage ] ) {
  27063. const uniforms = bindings[ shaderStage ][ groupName ];
  27064. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  27065. groupUniforms.push( ...uniforms );
  27066. }
  27067. }
  27068. bindingsGroups = [];
  27069. for ( const groupName in groups ) {
  27070. const group = groups[ groupName ];
  27071. const bindingsGroup = this._getBindGroup( groupName, group );
  27072. bindingsGroups.push( bindingsGroup );
  27073. }
  27074. this.bindGroups = bindingsGroups;
  27075. }
  27076. return bindingsGroups;
  27077. }
  27078. /**
  27079. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  27080. */
  27081. sortBindingGroups() {
  27082. const bindingsGroups = this.getBindings();
  27083. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  27084. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  27085. const bindingGroup = bindingsGroups[ i ];
  27086. this.bindingsIndexes[ bindingGroup.name ].group = i;
  27087. bindingGroup.index = i;
  27088. }
  27089. }
  27090. /**
  27091. * The builder maintains each node in a hash-based dictionary.
  27092. * This method sets the given node (value) with the given hash (key) into this dictionary.
  27093. *
  27094. * @param {Node} node - The node to add.
  27095. * @param {Number} hash - The hash of the node.
  27096. */
  27097. setHashNode( node, hash ) {
  27098. this.hashNodes[ hash ] = node;
  27099. }
  27100. /**
  27101. * Adds a node to this builder.
  27102. *
  27103. * @param {Node} node - The node to add.
  27104. */
  27105. addNode( node ) {
  27106. if ( this.nodes.includes( node ) === false ) {
  27107. this.nodes.push( node );
  27108. this.setHashNode( node, node.getHash( this ) );
  27109. }
  27110. }
  27111. /**
  27112. * It is used to add Nodes that will be used as FRAME and RENDER events,
  27113. * and need to follow a certain sequence in the calls to work correctly.
  27114. *
  27115. * @param {Node} node - The node to add.
  27116. */
  27117. addSequentialNode( node ) {
  27118. if ( this.sequentialNodes.includes( node ) === false ) {
  27119. this.sequentialNodes.push( node );
  27120. }
  27121. }
  27122. /**
  27123. * Checks the update types of nodes
  27124. */
  27125. buildUpdateNodes() {
  27126. for ( const node of this.nodes ) {
  27127. const updateType = node.getUpdateType();
  27128. if ( updateType !== NodeUpdateType.NONE ) {
  27129. this.updateNodes.push( node.getSelf() );
  27130. }
  27131. }
  27132. for ( const node of this.sequentialNodes ) {
  27133. const updateBeforeType = node.getUpdateBeforeType();
  27134. const updateAfterType = node.getUpdateAfterType();
  27135. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  27136. this.updateBeforeNodes.push( node.getSelf() );
  27137. }
  27138. if ( updateAfterType !== NodeUpdateType.NONE ) {
  27139. this.updateAfterNodes.push( node.getSelf() );
  27140. }
  27141. }
  27142. }
  27143. /**
  27144. * A reference the current node which is the
  27145. * last node in the chain of nodes.
  27146. *
  27147. * @type {Node}
  27148. */
  27149. get currentNode() {
  27150. return this.chaining[ this.chaining.length - 1 ];
  27151. }
  27152. /**
  27153. * Whether the given texture is filtered or not.
  27154. *
  27155. * @param {Texture} texture - The texture to check.
  27156. * @return {Boolean} Whether the given texture is filtered or not.
  27157. */
  27158. isFilteredTexture( texture ) {
  27159. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  27160. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  27161. }
  27162. /**
  27163. * Adds the given node to the internal node chain.
  27164. * This is used to check recursive calls in node-graph.
  27165. *
  27166. * @param {Node} node - The node to add.
  27167. */
  27168. addChain( node ) {
  27169. /*
  27170. if ( this.chaining.indexOf( node ) !== - 1 ) {
  27171. console.warn( 'Recursive node: ', node );
  27172. }
  27173. */
  27174. this.chaining.push( node );
  27175. }
  27176. /**
  27177. * Removes the given node from the internal node chain.
  27178. *
  27179. * @param {Node} node - The node to remove.
  27180. */
  27181. removeChain( node ) {
  27182. const lastChain = this.chaining.pop();
  27183. if ( lastChain !== node ) {
  27184. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  27185. }
  27186. }
  27187. /**
  27188. * Returns the native shader method name for a given generic name. E.g.
  27189. * the method name `textureDimensions` matches the WGSL name but must be
  27190. * resolved to `textureSize` in GLSL.
  27191. *
  27192. * @abstract
  27193. * @param {String} method - The method name to resolve.
  27194. * @return {String} The resolved method name.
  27195. */
  27196. getMethod( method ) {
  27197. return method;
  27198. }
  27199. /**
  27200. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  27201. *
  27202. * @param {Number} hash - The hash of the node.
  27203. * @return {Node} The found node.
  27204. */
  27205. getNodeFromHash( hash ) {
  27206. return this.hashNodes[ hash ];
  27207. }
  27208. /**
  27209. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  27210. *
  27211. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  27212. * @param {Node} node - The node to add.
  27213. * @return {Node} The node.
  27214. */
  27215. addFlow( shaderStage, node ) {
  27216. this.flowNodes[ shaderStage ].push( node );
  27217. return node;
  27218. }
  27219. /**
  27220. * Sets builder's context.
  27221. *
  27222. * @param {Object} context - The context to set.
  27223. */
  27224. setContext( context ) {
  27225. this.context = context;
  27226. }
  27227. /**
  27228. * Returns the builder's current context.
  27229. *
  27230. * @return {Object} The builder's current context.
  27231. */
  27232. getContext() {
  27233. return this.context;
  27234. }
  27235. /**
  27236. * Gets a context used in shader construction that can be shared across different materials.
  27237. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  27238. *
  27239. * @return {Object} The builder's current context without material.
  27240. */
  27241. getSharedContext() {
  27242. ({ ...this.context });
  27243. return this.context;
  27244. }
  27245. /**
  27246. * Sets builder's cache.
  27247. *
  27248. * @param {NodeCache} cache - The cache to set.
  27249. */
  27250. setCache( cache ) {
  27251. this.cache = cache;
  27252. }
  27253. /**
  27254. * Returns the builder's current cache.
  27255. *
  27256. * @return {NodeCache} The builder's current cache.
  27257. */
  27258. getCache() {
  27259. return this.cache;
  27260. }
  27261. /**
  27262. * Returns a cache for the given node.
  27263. *
  27264. * @param {Node} node - The node.
  27265. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  27266. * @return {NodeCache} The cache.
  27267. */
  27268. getCacheFromNode( node, parent = true ) {
  27269. const data = this.getDataFromNode( node );
  27270. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  27271. return data.cache;
  27272. }
  27273. /**
  27274. * Whether the requested feature is available or not.
  27275. *
  27276. * @abstract
  27277. * @param {String} name - The requested feature.
  27278. * @return {Boolean} Whether the requested feature is supported or not.
  27279. */
  27280. isAvailable( /*name*/ ) {
  27281. return false;
  27282. }
  27283. /**
  27284. * Returns the vertexIndex input variable as a native shader string.
  27285. *
  27286. * @abstract
  27287. * @return {String} The instanceIndex shader string.
  27288. */
  27289. getVertexIndex() {
  27290. console.warn( 'Abstract function.' );
  27291. }
  27292. /**
  27293. * Returns the instanceIndex input variable as a native shader string.
  27294. *
  27295. * @abstract
  27296. * @return {String} The instanceIndex shader string.
  27297. */
  27298. getInstanceIndex() {
  27299. console.warn( 'Abstract function.' );
  27300. }
  27301. /**
  27302. * Returns the drawIndex input variable as a native shader string.
  27303. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  27304. *
  27305. * @abstract
  27306. * @return {String} The drawIndex shader string.
  27307. */
  27308. getDrawIndex() {
  27309. console.warn( 'Abstract function.' );
  27310. }
  27311. /**
  27312. * Returns the frontFacing input variable as a native shader string.
  27313. *
  27314. * @abstract
  27315. * @return {String} The frontFacing shader string.
  27316. */
  27317. getFrontFacing() {
  27318. console.warn( 'Abstract function.' );
  27319. }
  27320. /**
  27321. * Returns the fragCoord input variable as a native shader string.
  27322. *
  27323. * @abstract
  27324. * @return {String} The fragCoord shader string.
  27325. */
  27326. getFragCoord() {
  27327. console.warn( 'Abstract function.' );
  27328. }
  27329. /**
  27330. * Whether to flip texture data along its vertical axis or not. WebGL needs
  27331. * this method evaluate to `true`, WebGPU to `false`.
  27332. *
  27333. * @abstract
  27334. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  27335. */
  27336. isFlipY() {
  27337. return false;
  27338. }
  27339. /**
  27340. * Calling this method increases the usage count for the given node by one.
  27341. *
  27342. * @param {Node} node - The node to increase the usage count for.
  27343. * @return {Number} The updated usage count.
  27344. */
  27345. increaseUsage( node ) {
  27346. const nodeData = this.getDataFromNode( node );
  27347. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  27348. return nodeData.usageCount;
  27349. }
  27350. /**
  27351. * Generates a texture sample shader string for the given texture data.
  27352. *
  27353. * @abstract
  27354. * @param {Texture} texture - The texture.
  27355. * @param {String} textureProperty - The texture property name.
  27356. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  27357. * @return {String} The generated shader string.
  27358. */
  27359. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  27360. console.warn( 'Abstract function.' );
  27361. }
  27362. /**
  27363. * Generates a texture LOD shader string for the given texture data.
  27364. *
  27365. * @abstract
  27366. * @param {Texture} texture - The texture.
  27367. * @param {String} textureProperty - The texture property name.
  27368. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  27369. * @param {String} levelSnippet - Snippet defining the mip level.
  27370. * @return {String} The generated shader string.
  27371. */
  27372. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  27373. console.warn( 'Abstract function.' );
  27374. }
  27375. /**
  27376. * Generates the shader string for the given type and value.
  27377. *
  27378. * @param {String} type - The type.
  27379. * @param {Any?} [value=null] - The value.
  27380. * @return {String} The generated value as a shader string.
  27381. */
  27382. generateConst( type, value = null ) {
  27383. if ( value === null ) {
  27384. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  27385. else if ( type === 'bool' ) value = false;
  27386. else if ( type === 'color' ) value = new Color();
  27387. else if ( type === 'vec2' ) value = new Vector2();
  27388. else if ( type === 'vec3' ) value = new Vector3();
  27389. else if ( type === 'vec4' ) value = new Vector4();
  27390. }
  27391. if ( type === 'float' ) return toFloat( value );
  27392. if ( type === 'int' ) return `${ Math.round( value ) }`;
  27393. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  27394. if ( type === 'bool' ) return value ? 'true' : 'false';
  27395. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  27396. const typeLength = this.getTypeLength( type );
  27397. const componentType = this.getComponentType( type );
  27398. const generateConst = value => this.generateConst( componentType, value );
  27399. if ( typeLength === 2 ) {
  27400. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  27401. } else if ( typeLength === 3 ) {
  27402. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  27403. } else if ( typeLength === 4 ) {
  27404. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  27405. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  27406. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  27407. } else if ( typeLength > 4 ) {
  27408. return `${ this.getType( type ) }()`;
  27409. }
  27410. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  27411. }
  27412. /**
  27413. * It might be necessary to convert certain data types to different ones
  27414. * so this method can be used to hide the conversion.
  27415. *
  27416. * @param {String} type - The type.
  27417. * @return {String} The updated type.
  27418. */
  27419. getType( type ) {
  27420. if ( type === 'color' ) return 'vec3';
  27421. return type;
  27422. }
  27423. /**
  27424. * Whether the given attribute name is defined in the geometry or not.
  27425. *
  27426. * @param {String} name - The attribute name.
  27427. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  27428. */
  27429. hasGeometryAttribute( name ) {
  27430. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  27431. }
  27432. /**
  27433. * Returns a node attribute for the given name and type.
  27434. *
  27435. * @param {String} name - The attribute's name.
  27436. * @param {String} type - The attribute's type.
  27437. * @return {NodeAttribute} The node attribute.
  27438. */
  27439. getAttribute( name, type ) {
  27440. const attributes = this.attributes;
  27441. // find attribute
  27442. for ( const attribute of attributes ) {
  27443. if ( attribute.name === name ) {
  27444. return attribute;
  27445. }
  27446. }
  27447. // create a new if no exist
  27448. const attribute = new NodeAttribute( name, type );
  27449. attributes.push( attribute );
  27450. return attribute;
  27451. }
  27452. /**
  27453. * Returns for the given node and shader stage the property name for the shader.
  27454. *
  27455. * @param {Node} node - The node.
  27456. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  27457. * @return {String} The property name.
  27458. */
  27459. getPropertyName( node/*, shaderStage*/ ) {
  27460. return node.name;
  27461. }
  27462. /**
  27463. * Whether the given type is a vector type or not.
  27464. *
  27465. * @param {String} type - The type to check.
  27466. * @return {Boolean} Whether the given type is a vector type or not.
  27467. */
  27468. isVector( type ) {
  27469. return /vec\d/.test( type );
  27470. }
  27471. /**
  27472. * Whether the given type is a matrix type or not.
  27473. *
  27474. * @param {String} type - The type to check.
  27475. * @return {Boolean} Whether the given type is a matrix type or not.
  27476. */
  27477. isMatrix( type ) {
  27478. return /mat\d/.test( type );
  27479. }
  27480. /**
  27481. * Whether the given type is a reference type or not.
  27482. *
  27483. * @param {String} type - The type to check.
  27484. * @return {Boolean} Whether the given type is a reference type or not.
  27485. */
  27486. isReference( type ) {
  27487. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  27488. }
  27489. /**
  27490. * Whether the given texture needs a conversion to working color space.
  27491. *
  27492. * @abstract
  27493. * @param {Texture} texture - The texture to check.
  27494. * @return {Boolean} Whether a color space conversion is required or not.
  27495. */
  27496. needsToWorkingColorSpace( /*texture*/ ) {
  27497. return false;
  27498. }
  27499. /**
  27500. * Returns the component type of a given texture.
  27501. *
  27502. * @param {Texture} texture - The texture.
  27503. * @return {String} The component type.
  27504. */
  27505. getComponentTypeFromTexture( texture ) {
  27506. const type = texture.type;
  27507. if ( texture.isDataTexture ) {
  27508. if ( type === IntType ) return 'int';
  27509. if ( type === UnsignedIntType ) return 'uint';
  27510. }
  27511. return 'float';
  27512. }
  27513. /**
  27514. * Returns the element type for a given type.
  27515. *
  27516. * @param {String} type - The type.
  27517. * @return {String} The element type.
  27518. */
  27519. getElementType( type ) {
  27520. if ( type === 'mat2' ) return 'vec2';
  27521. if ( type === 'mat3' ) return 'vec3';
  27522. if ( type === 'mat4' ) return 'vec4';
  27523. return this.getComponentType( type );
  27524. }
  27525. /**
  27526. * Returns the component type for a given type.
  27527. *
  27528. * @param {String} type - The type.
  27529. * @return {String} The component type.
  27530. */
  27531. getComponentType( type ) {
  27532. type = this.getVectorType( type );
  27533. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  27534. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  27535. if ( componentType === null ) return null;
  27536. if ( componentType[ 1 ] === 'b' ) return 'bool';
  27537. if ( componentType[ 1 ] === 'i' ) return 'int';
  27538. if ( componentType[ 1 ] === 'u' ) return 'uint';
  27539. return 'float';
  27540. }
  27541. /**
  27542. * Returns the vector type for a given type.
  27543. *
  27544. * @param {String} type - The type.
  27545. * @return {String} The vector type.
  27546. */
  27547. getVectorType( type ) {
  27548. if ( type === 'color' ) return 'vec3';
  27549. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  27550. return type;
  27551. }
  27552. /**
  27553. * Returns the data type for the given the length and component type.
  27554. *
  27555. * @param {Number} length - The length.
  27556. * @param {String} [componentType='float'] - The component type.
  27557. * @return {String} The type.
  27558. */
  27559. getTypeFromLength( length, componentType = 'float' ) {
  27560. if ( length === 1 ) return componentType;
  27561. const baseType = getTypeFromLength( length );
  27562. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  27563. return prefix + baseType;
  27564. }
  27565. /**
  27566. * Returns the type for a given typed array.
  27567. *
  27568. * @param {TypedArray} array - The typed array.
  27569. * @return {String} The type.
  27570. */
  27571. getTypeFromArray( array ) {
  27572. return typeFromArray.get( array.constructor );
  27573. }
  27574. /**
  27575. * Returns the type for a given buffer attribute.
  27576. *
  27577. * @param {BufferAttribute} attribute - The buffer attribute.
  27578. * @return {String} The type.
  27579. */
  27580. getTypeFromAttribute( attribute ) {
  27581. let dataAttribute = attribute;
  27582. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  27583. const array = dataAttribute.array;
  27584. const itemSize = attribute.itemSize;
  27585. const normalized = attribute.normalized;
  27586. let arrayType;
  27587. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  27588. arrayType = this.getTypeFromArray( array );
  27589. }
  27590. return this.getTypeFromLength( itemSize, arrayType );
  27591. }
  27592. /**
  27593. * Returns the length for the given data type.
  27594. *
  27595. * @param {String} type - The data type.
  27596. * @return {Number} The length.
  27597. */
  27598. getTypeLength( type ) {
  27599. const vecType = this.getVectorType( type );
  27600. const vecNum = /vec([2-4])/.exec( vecType );
  27601. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  27602. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  27603. if ( /mat2/.test( type ) === true ) return 4;
  27604. if ( /mat3/.test( type ) === true ) return 9;
  27605. if ( /mat4/.test( type ) === true ) return 16;
  27606. return 0;
  27607. }
  27608. /**
  27609. * Returns the vector type for a given matrix type.
  27610. *
  27611. * @param {String} type - The matrix type.
  27612. * @return {String} The vector type.
  27613. */
  27614. getVectorFromMatrix( type ) {
  27615. return type.replace( 'mat', 'vec' );
  27616. }
  27617. /**
  27618. * For a given type this method changes the component type to the
  27619. * given value. E.g. `vec4` should be changed to the new component type
  27620. * `uint` which results in `uvec4`.
  27621. *
  27622. * @param {String} type - The type.
  27623. * @param {String} newComponentType - The new component type.
  27624. * @return {String} The new type.
  27625. */
  27626. changeComponentType( type, newComponentType ) {
  27627. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  27628. }
  27629. /**
  27630. * Returns the integer type pendant for the given type.
  27631. *
  27632. * @param {String} type - The type.
  27633. * @return {String} The integer type.
  27634. */
  27635. getIntegerType( type ) {
  27636. const componentType = this.getComponentType( type );
  27637. if ( componentType === 'int' || componentType === 'uint' ) return type;
  27638. return this.changeComponentType( type, 'int' );
  27639. }
  27640. /**
  27641. * Adds a stack node to the internal stack.
  27642. *
  27643. * @return {StackNode} The added stack node.
  27644. */
  27645. addStack() {
  27646. this.stack = stack( this.stack );
  27647. this.stacks.push( getCurrentStack() || this.stack );
  27648. setCurrentStack( this.stack );
  27649. return this.stack;
  27650. }
  27651. /**
  27652. * Removes the last stack node from the internal stack.
  27653. *
  27654. * @return {StackNode} The removed stack node.
  27655. */
  27656. removeStack() {
  27657. const lastStack = this.stack;
  27658. this.stack = lastStack.parent;
  27659. setCurrentStack( this.stacks.pop() );
  27660. return lastStack;
  27661. }
  27662. /**
  27663. * The builder maintains (cached) data for each node during the building process. This method
  27664. * can be used to get these data for a specific shader stage and cache.
  27665. *
  27666. * @param {Node} node - The node to get the data for.
  27667. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  27668. * @param {NodeCache?} cache - An optional cache.
  27669. * @return {Object} The node data.
  27670. */
  27671. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  27672. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  27673. let nodeData = cache.getData( node );
  27674. if ( nodeData === undefined ) {
  27675. nodeData = {};
  27676. cache.setData( node, nodeData );
  27677. }
  27678. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  27679. return nodeData[ shaderStage ];
  27680. }
  27681. /**
  27682. * Returns the properties for the given node and shader stage.
  27683. *
  27684. * @param {Node} node - The node to get the properties for.
  27685. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  27686. * @return {Object} The node properties.
  27687. */
  27688. getNodeProperties( node, shaderStage = 'any' ) {
  27689. const nodeData = this.getDataFromNode( node, shaderStage );
  27690. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  27691. }
  27692. /**
  27693. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  27694. *
  27695. * @param {BufferAttributeNode} node - The buffer attribute node.
  27696. * @param {String} type - The node type.
  27697. * @return {NodeAttribute} The node attribute.
  27698. */
  27699. getBufferAttributeFromNode( node, type ) {
  27700. const nodeData = this.getDataFromNode( node );
  27701. let bufferAttribute = nodeData.bufferAttribute;
  27702. if ( bufferAttribute === undefined ) {
  27703. const index = this.uniforms.index ++;
  27704. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  27705. this.bufferAttributes.push( bufferAttribute );
  27706. nodeData.bufferAttribute = bufferAttribute;
  27707. }
  27708. return bufferAttribute;
  27709. }
  27710. /**
  27711. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  27712. *
  27713. * @param {OutputStructNode} node - The output struct node.
  27714. * @param {Array<String>} types - The output struct types.
  27715. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  27716. * @return {StructTypeNode} The struct type attribute.
  27717. */
  27718. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  27719. const nodeData = this.getDataFromNode( node, shaderStage );
  27720. let structType = nodeData.structType;
  27721. if ( structType === undefined ) {
  27722. const index = this.structs.index ++;
  27723. structType = new StructTypeNode( 'StructType' + index, types );
  27724. this.structs[ shaderStage ].push( structType );
  27725. nodeData.structType = structType;
  27726. }
  27727. return structType;
  27728. }
  27729. /**
  27730. * Returns an instance of {@link NodeUniform} for the given uniform node.
  27731. *
  27732. * @param {UniformNode} node - The uniform node.
  27733. * @param {String} type - The uniform type.
  27734. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  27735. * @param {String?} name - The name of the uniform.
  27736. * @return {NodeUniform} The node uniform.
  27737. */
  27738. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  27739. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  27740. let nodeUniform = nodeData.uniform;
  27741. if ( nodeUniform === undefined ) {
  27742. const index = this.uniforms.index ++;
  27743. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  27744. this.uniforms[ shaderStage ].push( nodeUniform );
  27745. nodeData.uniform = nodeUniform;
  27746. }
  27747. return nodeUniform;
  27748. }
  27749. /**
  27750. * Returns an instance of {@link NodeVar} for the given variable node.
  27751. *
  27752. * @param {VarNode} node - The variable node.
  27753. * @param {String?} name - The variable's name.
  27754. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  27755. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  27756. * @return {NodeVar} The node variable.
  27757. */
  27758. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  27759. const nodeData = this.getDataFromNode( node, shaderStage );
  27760. let nodeVar = nodeData.variable;
  27761. if ( nodeVar === undefined ) {
  27762. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  27763. if ( name === null ) name = 'nodeVar' + vars.length;
  27764. nodeVar = new NodeVar( name, type );
  27765. vars.push( nodeVar );
  27766. nodeData.variable = nodeVar;
  27767. }
  27768. return nodeVar;
  27769. }
  27770. /**
  27771. * Returns an instance of {@link NodeVarying} for the given varying node.
  27772. *
  27773. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  27774. * @param {String?} name - The varying's name.
  27775. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  27776. * @return {NodeVar} The node varying.
  27777. */
  27778. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  27779. const nodeData = this.getDataFromNode( node, 'any' );
  27780. let nodeVarying = nodeData.varying;
  27781. if ( nodeVarying === undefined ) {
  27782. const varyings = this.varyings;
  27783. const index = varyings.length;
  27784. if ( name === null ) name = 'nodeVarying' + index;
  27785. nodeVarying = new NodeVarying( name, type );
  27786. varyings.push( nodeVarying );
  27787. nodeData.varying = nodeVarying;
  27788. }
  27789. return nodeVarying;
  27790. }
  27791. /**
  27792. * Returns an instance of {@link NodeCode} for the given code node.
  27793. *
  27794. * @param {CodeNode} node - The code node.
  27795. * @param {String} type - The node type.
  27796. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  27797. * @return {NodeCode} The node code.
  27798. */
  27799. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  27800. const nodeData = this.getDataFromNode( node );
  27801. let nodeCode = nodeData.code;
  27802. if ( nodeCode === undefined ) {
  27803. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  27804. const index = codes.length;
  27805. nodeCode = new NodeCode( 'nodeCode' + index, type );
  27806. codes.push( nodeCode );
  27807. nodeData.code = nodeCode;
  27808. }
  27809. return nodeCode;
  27810. }
  27811. /**
  27812. * Adds a code flow based on the code-block hierarchy.
  27813. * This is used so that code-blocks like If,Else create their variables locally if the Node
  27814. * is only used inside one of these conditionals in the current shader stage.
  27815. *
  27816. * @param {Node} node - The node to add.
  27817. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  27818. */
  27819. addFlowCodeHierarchy( node, nodeBlock ) {
  27820. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  27821. let needsFlowCode = true;
  27822. let nodeBlockHierarchy = nodeBlock;
  27823. while ( nodeBlockHierarchy ) {
  27824. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  27825. needsFlowCode = false;
  27826. break;
  27827. }
  27828. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  27829. }
  27830. if ( needsFlowCode ) {
  27831. for ( const flowCode of flowCodes ) {
  27832. this.addLineFlowCode( flowCode );
  27833. }
  27834. }
  27835. }
  27836. /**
  27837. * Add a inline-code to the current flow code-block.
  27838. *
  27839. * @param {Node} node - The node to add.
  27840. * @param {String} code - The code to add.
  27841. * @param {Node} nodeBlock - Current ConditionalNode
  27842. */
  27843. addLineFlowCodeBlock( node, code, nodeBlock ) {
  27844. const nodeData = this.getDataFromNode( node );
  27845. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  27846. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  27847. flowCodes.push( code );
  27848. codeBlock.set( nodeBlock, true );
  27849. }
  27850. /**
  27851. * Add a inline-code to the current flow.
  27852. *
  27853. * @param {String} code - The code to add.
  27854. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  27855. * @return {NodeBuilder} A reference to this node builder.
  27856. */
  27857. addLineFlowCode( code, node = null ) {
  27858. if ( code === '' ) return this;
  27859. if ( node !== null && this.context.nodeBlock ) {
  27860. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  27861. }
  27862. code = this.tab + code;
  27863. if ( ! /;\s*$/.test( code ) ) {
  27864. code = code + ';\n';
  27865. }
  27866. this.flow.code += code;
  27867. return this;
  27868. }
  27869. /**
  27870. * Adds a code to the current code flow.
  27871. *
  27872. * @param {String} code - Shader code.
  27873. * @return {NodeBuilder} A reference to this node builder.
  27874. */
  27875. addFlowCode( code ) {
  27876. this.flow.code += code;
  27877. return this;
  27878. }
  27879. /**
  27880. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  27881. * Typically used in codes with If,Else.
  27882. *
  27883. * @return {NodeBuilder} A reference to this node builder.
  27884. */
  27885. addFlowTab() {
  27886. this.tab += '\t';
  27887. return this;
  27888. }
  27889. /**
  27890. * Removes a tab.
  27891. *
  27892. * @return {NodeBuilder} A reference to this node builder.
  27893. */
  27894. removeFlowTab() {
  27895. this.tab = this.tab.slice( 0, - 1 );
  27896. return this;
  27897. }
  27898. /**
  27899. * Gets the current flow data based on a Node.
  27900. *
  27901. * @param {Node} node - Node that the flow was started.
  27902. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  27903. * @return {Object} The flow data.
  27904. */
  27905. getFlowData( node/*, shaderStage*/ ) {
  27906. return this.flowsData.get( node );
  27907. }
  27908. /**
  27909. * Executes the node flow based on a root node to generate the final shader code.
  27910. *
  27911. * @param {Node} node - The node to execute.
  27912. * @return {Object} The code flow.
  27913. */
  27914. flowNode( node ) {
  27915. const output = node.getNodeType( this );
  27916. const flowData = this.flowChildNode( node, output );
  27917. this.flowsData.set( node, flowData );
  27918. return flowData;
  27919. }
  27920. /**
  27921. * Returns the native shader operator name for a given generic name.
  27922. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  27923. *
  27924. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  27925. * @return {FunctionNode} The build function node.
  27926. */
  27927. buildFunctionNode( shaderNode ) {
  27928. const fn = new FunctionNode();
  27929. const previous = this.currentFunctionNode;
  27930. this.currentFunctionNode = fn;
  27931. fn.code = this.buildFunctionCode( shaderNode );
  27932. this.currentFunctionNode = previous;
  27933. return fn;
  27934. }
  27935. /**
  27936. * Generates a code flow based on a TSL function: Fn().
  27937. *
  27938. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  27939. * @return {Object}
  27940. */
  27941. flowShaderNode( shaderNode ) {
  27942. const layout = shaderNode.layout;
  27943. const inputs = {
  27944. [ Symbol.iterator ]() {
  27945. let index = 0;
  27946. const values = Object.values( this );
  27947. return {
  27948. next: () => ( {
  27949. value: values[ index ],
  27950. done: index ++ >= values.length
  27951. } )
  27952. };
  27953. }
  27954. };
  27955. for ( const input of layout.inputs ) {
  27956. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  27957. }
  27958. //
  27959. shaderNode.layout = null;
  27960. const callNode = shaderNode.call( inputs );
  27961. const flowData = this.flowStagesNode( callNode, layout.type );
  27962. shaderNode.layout = layout;
  27963. return flowData;
  27964. }
  27965. /**
  27966. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  27967. *
  27968. * @param {Node} node - The node to execute.
  27969. * @param {String?} output - Expected output type. For example 'vec3'.
  27970. * @return {Object}
  27971. */
  27972. flowStagesNode( node, output = null ) {
  27973. const previousFlow = this.flow;
  27974. const previousVars = this.vars;
  27975. const previousCache = this.cache;
  27976. const previousBuildStage = this.buildStage;
  27977. const previousStack = this.stack;
  27978. const flow = {
  27979. code: ''
  27980. };
  27981. this.flow = flow;
  27982. this.vars = {};
  27983. this.cache = new NodeCache();
  27984. this.stack = stack();
  27985. for ( const buildStage of defaultBuildStages ) {
  27986. this.setBuildStage( buildStage );
  27987. flow.result = node.build( this, output );
  27988. }
  27989. flow.vars = this.getVars( this.shaderStage );
  27990. this.flow = previousFlow;
  27991. this.vars = previousVars;
  27992. this.cache = previousCache;
  27993. this.stack = previousStack;
  27994. this.setBuildStage( previousBuildStage );
  27995. return flow;
  27996. }
  27997. /**
  27998. * Returns the native shader operator name for a given generic name.
  27999. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  28000. *
  28001. * @abstract
  28002. * @param {String} op - The operator name to resolve.
  28003. * @return {String} The resolved operator name.
  28004. */
  28005. getFunctionOperator( /* op */ ) {
  28006. return null;
  28007. }
  28008. /**
  28009. * Generates a code flow based on a child Node.
  28010. *
  28011. * @param {Node} node - The node to execute.
  28012. * @param {String?} output - Expected output type. For example 'vec3'.
  28013. * @return {Object} The code flow.
  28014. */
  28015. flowChildNode( node, output = null ) {
  28016. const previousFlow = this.flow;
  28017. const flow = {
  28018. code: ''
  28019. };
  28020. this.flow = flow;
  28021. flow.result = node.build( this, output );
  28022. this.flow = previousFlow;
  28023. return flow;
  28024. }
  28025. /**
  28026. * Executes a flow of code in a different stage.
  28027. *
  28028. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  28029. * return the value in fragment-stage even if it is being executed in an input fragment.
  28030. *
  28031. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28032. * @param {Node} node - The node to execute.
  28033. * @param {String?} output - Expected output type. For example 'vec3'.
  28034. * @param {String?} propertyName - The property name to assign the result.
  28035. * @return {Object}
  28036. */
  28037. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28038. const previousShaderStage = this.shaderStage;
  28039. this.setShaderStage( shaderStage );
  28040. const flowData = this.flowChildNode( node, output );
  28041. if ( propertyName !== null ) {
  28042. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28043. }
  28044. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28045. this.setShaderStage( previousShaderStage );
  28046. return flowData;
  28047. }
  28048. /**
  28049. * Returns an array holding all node attributes of this node builder.
  28050. *
  28051. * @return {Array<NodeAttribute>} The node attributes of this builder.
  28052. */
  28053. getAttributesArray() {
  28054. return this.attributes.concat( this.bufferAttributes );
  28055. }
  28056. /**
  28057. * Returns the attribute definitions as a shader string for the given shader stage.
  28058. *
  28059. * @abstract
  28060. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28061. * @return {String} The attribute code section.
  28062. */
  28063. getAttributes( /*shaderStage*/ ) {
  28064. console.warn( 'Abstract function.' );
  28065. }
  28066. /**
  28067. * Returns the varying definitions as a shader string for the given shader stage.
  28068. *
  28069. * @abstract
  28070. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28071. * @return {String} The varying code section.
  28072. */
  28073. getVaryings( /*shaderStage*/ ) {
  28074. console.warn( 'Abstract function.' );
  28075. }
  28076. /**
  28077. * Returns a single variable definition as a shader string for the given variable type and name.
  28078. *
  28079. * @param {String} type - The variable's type.
  28080. * @param {String} name - The variable's name.
  28081. * @return {String} The shader string.
  28082. */
  28083. getVar( type, name ) {
  28084. return `${ this.getType( type ) } ${ name }`;
  28085. }
  28086. /**
  28087. * Returns the variable definitions as a shader string for the given shader stage.
  28088. *
  28089. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28090. * @return {String} The variable code section.
  28091. */
  28092. getVars( shaderStage ) {
  28093. let snippet = '';
  28094. const vars = this.vars[ shaderStage ];
  28095. if ( vars !== undefined ) {
  28096. for ( const variable of vars ) {
  28097. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28098. }
  28099. }
  28100. return snippet;
  28101. }
  28102. /**
  28103. * Returns the uniform definitions as a shader string for the given shader stage.
  28104. *
  28105. * @abstract
  28106. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28107. * @return {String} The uniform code section.
  28108. */
  28109. getUniforms( /*shaderStage*/ ) {
  28110. console.warn( 'Abstract function.' );
  28111. }
  28112. /**
  28113. * Returns the native code definitions as a shader string for the given shader stage.
  28114. *
  28115. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  28116. * @return {String} The native code section.
  28117. */
  28118. getCodes( shaderStage ) {
  28119. const codes = this.codes[ shaderStage ];
  28120. let code = '';
  28121. if ( codes !== undefined ) {
  28122. for ( const nodeCode of codes ) {
  28123. code += nodeCode.code + '\n';
  28124. }
  28125. }
  28126. return code;
  28127. }
  28128. /**
  28129. * Returns the hash of this node builder.
  28130. *
  28131. * @return {String} The hash.
  28132. */
  28133. getHash() {
  28134. return this.vertexShader + this.fragmentShader + this.computeShader;
  28135. }
  28136. /**
  28137. * Sets the current shader stage.
  28138. *
  28139. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  28140. */
  28141. setShaderStage( shaderStage ) {
  28142. this.shaderStage = shaderStage;
  28143. }
  28144. /**
  28145. * Returns the current shader stage.
  28146. *
  28147. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  28148. */
  28149. getShaderStage() {
  28150. return this.shaderStage;
  28151. }
  28152. /**
  28153. * Sets the current build stage.
  28154. *
  28155. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  28156. */
  28157. setBuildStage( buildStage ) {
  28158. this.buildStage = buildStage;
  28159. }
  28160. /**
  28161. * Returns the current build stage.
  28162. *
  28163. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  28164. */
  28165. getBuildStage() {
  28166. return this.buildStage;
  28167. }
  28168. /**
  28169. * Controls the code build of the shader stages.
  28170. *
  28171. * @abstract
  28172. */
  28173. buildCode() {
  28174. console.warn( 'Abstract function.' );
  28175. }
  28176. /**
  28177. * Central build method which controls the build for the given object.
  28178. *
  28179. * @return {NodeBuilder} A reference to this node builder.
  28180. */
  28181. build() {
  28182. const { object, material, renderer } = this;
  28183. if ( material !== null ) {
  28184. let nodeMaterial = renderer.library.fromMaterial( material );
  28185. if ( nodeMaterial === null ) {
  28186. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  28187. nodeMaterial = new NodeMaterial();
  28188. }
  28189. nodeMaterial.build( this );
  28190. } else {
  28191. this.addFlow( 'compute', object );
  28192. }
  28193. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28194. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28195. // generate() -> stage 3: generate shader
  28196. for ( const buildStage of defaultBuildStages ) {
  28197. this.setBuildStage( buildStage );
  28198. if ( this.context.vertex && this.context.vertex.isNode ) {
  28199. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28200. }
  28201. for ( const shaderStage of shaderStages ) {
  28202. this.setShaderStage( shaderStage );
  28203. const flowNodes = this.flowNodes[ shaderStage ];
  28204. for ( const node of flowNodes ) {
  28205. if ( buildStage === 'generate' ) {
  28206. this.flowNode( node );
  28207. } else {
  28208. node.build( this );
  28209. }
  28210. }
  28211. }
  28212. }
  28213. this.setBuildStage( null );
  28214. this.setShaderStage( null );
  28215. // stage 4: build code for a specific output
  28216. this.buildCode();
  28217. this.buildUpdateNodes();
  28218. return this;
  28219. }
  28220. /**
  28221. * Returns a uniform representation which is later used for UBO generation and rendering.
  28222. *
  28223. * @param {NodeUniform} uniformNode - The uniform node.
  28224. * @param {String} type - The requested type.
  28225. * @return {Uniform} The uniform.
  28226. */
  28227. getNodeUniform( uniformNode, type ) {
  28228. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28229. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28230. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28231. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28232. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28233. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28234. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28235. throw new Error( `Uniform "${type}" not declared.` );
  28236. }
  28237. /**
  28238. * Formats the given shader snippet from a given type into another one. E.g.
  28239. * this method might be used to convert a simple float string `"1.0"` into a
  28240. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  28241. *
  28242. * @param {String} snippet - The shader snippet.
  28243. * @param {String} fromType - The source type.
  28244. * @param {String} toType - The target type.
  28245. * @return {String} The updated shader string.
  28246. */
  28247. format( snippet, fromType, toType ) {
  28248. fromType = this.getVectorType( fromType );
  28249. toType = this.getVectorType( toType );
  28250. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28251. return snippet;
  28252. }
  28253. const fromTypeLength = this.getTypeLength( fromType );
  28254. const toTypeLength = this.getTypeLength( toType );
  28255. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  28256. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  28257. }
  28258. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  28259. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  28260. }
  28261. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28262. // @TODO: ignore for now
  28263. return snippet;
  28264. }
  28265. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28266. // @TODO: ignore for now
  28267. return snippet;
  28268. }
  28269. if ( fromTypeLength === toTypeLength ) {
  28270. return `${ this.getType( toType ) }( ${ snippet } )`;
  28271. }
  28272. if ( fromTypeLength > toTypeLength ) {
  28273. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28274. }
  28275. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28276. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28277. }
  28278. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28279. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28280. }
  28281. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28282. // convert a number value to vector type, e.g:
  28283. // vec3( 1u ) -> vec3( float( 1u ) )
  28284. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28285. }
  28286. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28287. }
  28288. /**
  28289. * Returns a signature with the engine's current revision.
  28290. *
  28291. * @return {String} The signature.
  28292. */
  28293. getSignature() {
  28294. return `// Three.js r${ REVISION } - Node System\n`;
  28295. }
  28296. // deprecated
  28297. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  28298. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  28299. }
  28300. }
  28301. /**
  28302. * Management class for updating nodes. The module tracks metrics like
  28303. * the elapsed time, delta time, the render and frame ID to correctly
  28304. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  28305. * and {@link Node#updateAfter} depending on the node's configuration.
  28306. */
  28307. class NodeFrame {
  28308. /**
  28309. * Constructs a new node fame.
  28310. */
  28311. constructor() {
  28312. /**
  28313. * The elapsed time in seconds.
  28314. *
  28315. * @type {Number}
  28316. * @default 0
  28317. */
  28318. this.time = 0;
  28319. /**
  28320. * The delta time in seconds.
  28321. *
  28322. * @type {Number}
  28323. * @default 0
  28324. */
  28325. this.deltaTime = 0;
  28326. /**
  28327. * The frame ID.
  28328. *
  28329. * @type {Number}
  28330. * @default 0
  28331. */
  28332. this.frameId = 0;
  28333. /**
  28334. * The render ID.
  28335. *
  28336. * @type {Number}
  28337. * @default 0
  28338. */
  28339. this.renderId = 0;
  28340. /**
  28341. * Used to control the {@link Node#update} call.
  28342. *
  28343. * @type {WeakMap<Node, Object>}
  28344. */
  28345. this.updateMap = new WeakMap();
  28346. /**
  28347. * Used to control the {@link Node#updateBefore} call.
  28348. *
  28349. * @type {WeakMap<Node, Object>}
  28350. */
  28351. this.updateBeforeMap = new WeakMap();
  28352. /**
  28353. * Used to control the {@link Node#updateAfter} call.
  28354. *
  28355. * @type {WeakMap<Node, Object>}
  28356. */
  28357. this.updateAfterMap = new WeakMap();
  28358. /**
  28359. * A reference to the current renderer.
  28360. *
  28361. * @type {Renderer?}
  28362. * @default null
  28363. */
  28364. this.renderer = null;
  28365. /**
  28366. * A reference to the current material.
  28367. *
  28368. * @type {Material?}
  28369. * @default null
  28370. */
  28371. this.material = null;
  28372. /**
  28373. * A reference to the current camera.
  28374. *
  28375. * @type {Camera?}
  28376. * @default null
  28377. */
  28378. this.camera = null;
  28379. /**
  28380. * A reference to the current 3D object.
  28381. *
  28382. * @type {Object3D?}
  28383. * @default null
  28384. */
  28385. this.object = null;
  28386. /**
  28387. * A reference to the current scene.
  28388. *
  28389. * @type {Scene?}
  28390. * @default null
  28391. */
  28392. this.scene = null;
  28393. }
  28394. /**
  28395. * Returns a dictionary for a given node and update map which
  28396. * is used to correctly call node update methods per frame or render.
  28397. *
  28398. * @private
  28399. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  28400. * @param {Node} nodeRef - The reference to the current node.
  28401. * @return {Object<String,WeakMap>} The dictionary.
  28402. */
  28403. _getMaps( referenceMap, nodeRef ) {
  28404. let maps = referenceMap.get( nodeRef );
  28405. if ( maps === undefined ) {
  28406. maps = {
  28407. renderMap: new WeakMap(),
  28408. frameMap: new WeakMap()
  28409. };
  28410. referenceMap.set( nodeRef, maps );
  28411. }
  28412. return maps;
  28413. }
  28414. /**
  28415. * This method executes the {@link Node#updateBefore} for the given node.
  28416. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  28417. * is only executed once per frame, render or object depending on the update
  28418. * type.
  28419. *
  28420. * @param {Node} node - The node that should be updated.
  28421. */
  28422. updateBeforeNode( node ) {
  28423. const updateType = node.getUpdateBeforeType();
  28424. const reference = node.updateReference( this );
  28425. if ( updateType === NodeUpdateType.FRAME ) {
  28426. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28427. if ( frameMap.get( reference ) !== this.frameId ) {
  28428. if ( node.updateBefore( this ) !== false ) {
  28429. frameMap.set( reference, this.frameId );
  28430. }
  28431. }
  28432. } else if ( updateType === NodeUpdateType.RENDER ) {
  28433. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28434. if ( renderMap.get( reference ) !== this.renderId ) {
  28435. if ( node.updateBefore( this ) !== false ) {
  28436. renderMap.set( reference, this.renderId );
  28437. }
  28438. }
  28439. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28440. node.updateBefore( this );
  28441. }
  28442. }
  28443. /**
  28444. * This method executes the {@link Node#updateAfter} for the given node.
  28445. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  28446. * is only executed once per frame, render or object depending on the update
  28447. * type.
  28448. *
  28449. * @param {Node} node - The node that should be updated.
  28450. */
  28451. updateAfterNode( node ) {
  28452. const updateType = node.getUpdateAfterType();
  28453. const reference = node.updateReference( this );
  28454. if ( updateType === NodeUpdateType.FRAME ) {
  28455. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28456. if ( frameMap.get( reference ) !== this.frameId ) {
  28457. if ( node.updateAfter( this ) !== false ) {
  28458. frameMap.set( reference, this.frameId );
  28459. }
  28460. }
  28461. } else if ( updateType === NodeUpdateType.RENDER ) {
  28462. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28463. if ( renderMap.get( reference ) !== this.renderId ) {
  28464. if ( node.updateAfter( this ) !== false ) {
  28465. renderMap.set( reference, this.renderId );
  28466. }
  28467. }
  28468. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28469. node.updateAfter( this );
  28470. }
  28471. }
  28472. /**
  28473. * This method executes the {@link Node#update} for the given node.
  28474. * It makes sure {@link Node#updateType} is honored meaning the update
  28475. * is only executed once per frame, render or object depending on the update
  28476. * type.
  28477. *
  28478. * @param {Node} node - The node that should be updated.
  28479. */
  28480. updateNode( node ) {
  28481. const updateType = node.getUpdateType();
  28482. const reference = node.updateReference( this );
  28483. if ( updateType === NodeUpdateType.FRAME ) {
  28484. const { frameMap } = this._getMaps( this.updateMap, reference );
  28485. if ( frameMap.get( reference ) !== this.frameId ) {
  28486. if ( node.update( this ) !== false ) {
  28487. frameMap.set( reference, this.frameId );
  28488. }
  28489. }
  28490. } else if ( updateType === NodeUpdateType.RENDER ) {
  28491. const { renderMap } = this._getMaps( this.updateMap, reference );
  28492. if ( renderMap.get( reference ) !== this.renderId ) {
  28493. if ( node.update( this ) !== false ) {
  28494. renderMap.set( reference, this.renderId );
  28495. }
  28496. }
  28497. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28498. node.update( this );
  28499. }
  28500. }
  28501. /**
  28502. * Updates the internal state of the node frame. This method is
  28503. * called by the renderer in its internal animation loop.
  28504. */
  28505. update() {
  28506. this.frameId ++;
  28507. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28508. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28509. this.lastTime = performance.now();
  28510. this.time += this.deltaTime;
  28511. }
  28512. }
  28513. /**
  28514. * Describes the input of a {@link NodeFunction}.
  28515. */
  28516. class NodeFunctionInput {
  28517. /**
  28518. * Constructs a new node function input.
  28519. *
  28520. * @param {String} type - The input type.
  28521. * @param {String} name - The input name.
  28522. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  28523. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  28524. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  28525. */
  28526. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28527. /**
  28528. * The input type.
  28529. *
  28530. * @type {String}
  28531. */
  28532. this.type = type;
  28533. /**
  28534. * The input name.
  28535. *
  28536. * @type {String}
  28537. */
  28538. this.name = name;
  28539. /**
  28540. * If the input is an Array, count will be the length.
  28541. *
  28542. * @type {Number?}
  28543. * @default null
  28544. */
  28545. this.count = count;
  28546. /**
  28547. *The parameter qualifier (only relevant for GLSL).
  28548. *
  28549. * @type {('in'|'out'|'inout')}
  28550. * @default ''
  28551. */
  28552. this.qualifier = qualifier;
  28553. /**
  28554. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  28555. *
  28556. * @type {Boolean}
  28557. * @default false
  28558. */
  28559. this.isConst = isConst;
  28560. }
  28561. }
  28562. NodeFunctionInput.isNodeFunctionInput = true;
  28563. /**
  28564. * Module for representing directional lights as nodes.
  28565. *
  28566. * @augments AnalyticLightNode
  28567. */
  28568. class DirectionalLightNode extends AnalyticLightNode {
  28569. static get type() {
  28570. return 'DirectionalLightNode';
  28571. }
  28572. /**
  28573. * Constructs a new directional light node.
  28574. *
  28575. * @param {DirectionalLight?} [light=null] - The directional light source.
  28576. */
  28577. constructor( light = null ) {
  28578. super( light );
  28579. }
  28580. setup( builder ) {
  28581. super.setup( builder );
  28582. const lightingModel = builder.context.lightingModel;
  28583. const lightColor = this.colorNode;
  28584. const lightDirection = lightTargetDirection( this.light );
  28585. const reflectedLight = builder.context.reflectedLight;
  28586. lightingModel.direct( {
  28587. lightDirection,
  28588. lightColor,
  28589. reflectedLight
  28590. }, builder.stack, builder );
  28591. }
  28592. }
  28593. const _matrix41 = /*@__PURE__*/ new Matrix4();
  28594. const _matrix42 = /*@__PURE__*/ new Matrix4();
  28595. let _ltcLib = null;
  28596. /**
  28597. * Module for representing rect area lights as nodes.
  28598. *
  28599. * @augments AnalyticLightNode
  28600. */
  28601. class RectAreaLightNode extends AnalyticLightNode {
  28602. static get type() {
  28603. return 'RectAreaLightNode';
  28604. }
  28605. /**
  28606. * Constructs a new rect area light node.
  28607. *
  28608. * @param {RectAreaLight?} [light=null] - The rect area light source.
  28609. */
  28610. constructor( light = null ) {
  28611. super( light );
  28612. /**
  28613. * Uniform node representing the half height of the are light.
  28614. *
  28615. * @type {UniformNode<vec3>}
  28616. */
  28617. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  28618. /**
  28619. * Uniform node representing the half width of the are light.
  28620. *
  28621. * @type {UniformNode<vec3>}
  28622. */
  28623. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  28624. /**
  28625. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  28626. * relies on `viewMatrix` which might vary per render call.
  28627. *
  28628. * @type {String}
  28629. * @default 'render'
  28630. */
  28631. this.updateType = NodeUpdateType.RENDER;
  28632. }
  28633. /**
  28634. * Overwritten to updated rect area light specific uniforms.
  28635. *
  28636. * @param {NodeFrame} frame - A reference to the current node frame.
  28637. */
  28638. update( frame ) {
  28639. super.update( frame );
  28640. const { light } = this;
  28641. const viewMatrix = frame.camera.matrixWorldInverse;
  28642. _matrix42.identity();
  28643. _matrix41.copy( light.matrixWorld );
  28644. _matrix41.premultiply( viewMatrix );
  28645. _matrix42.extractRotation( _matrix41 );
  28646. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  28647. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  28648. this.halfWidth.value.applyMatrix4( _matrix42 );
  28649. this.halfHeight.value.applyMatrix4( _matrix42 );
  28650. }
  28651. setup( builder ) {
  28652. super.setup( builder );
  28653. let ltc_1, ltc_2;
  28654. if ( builder.isAvailable( 'float32Filterable' ) ) {
  28655. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  28656. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  28657. } else {
  28658. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  28659. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  28660. }
  28661. const { colorNode, light } = this;
  28662. const lightingModel = builder.context.lightingModel;
  28663. const lightPosition = lightViewPosition( light );
  28664. const reflectedLight = builder.context.reflectedLight;
  28665. lightingModel.directRectArea( {
  28666. lightColor: colorNode,
  28667. lightPosition,
  28668. halfWidth: this.halfWidth,
  28669. halfHeight: this.halfHeight,
  28670. reflectedLight,
  28671. ltc_1,
  28672. ltc_2
  28673. }, builder.stack, builder );
  28674. }
  28675. /**
  28676. * Used to configure the internal BRDF approximation texture data.
  28677. *
  28678. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  28679. */
  28680. static setLTC( ltc ) {
  28681. _ltcLib = ltc;
  28682. }
  28683. }
  28684. /**
  28685. * Module for representing spot lights as nodes.
  28686. *
  28687. * @augments AnalyticLightNode
  28688. */
  28689. class SpotLightNode extends AnalyticLightNode {
  28690. static get type() {
  28691. return 'SpotLightNode';
  28692. }
  28693. /**
  28694. * Constructs a new spot light node.
  28695. *
  28696. * @param {SpotLight?} [light=null] - The spot light source.
  28697. */
  28698. constructor( light = null ) {
  28699. super( light );
  28700. /**
  28701. * Uniform node representing the cone cosine.
  28702. *
  28703. * @type {UniformNode<float>}
  28704. */
  28705. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  28706. /**
  28707. * Uniform node representing the penumbra cosine.
  28708. *
  28709. * @type {UniformNode<float>}
  28710. */
  28711. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  28712. /**
  28713. * Uniform node representing the cutoff distance.
  28714. *
  28715. * @type {UniformNode<float>}
  28716. */
  28717. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28718. /**
  28719. * Uniform node representing the decay exponent.
  28720. *
  28721. * @type {UniformNode<float>}
  28722. */
  28723. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  28724. }
  28725. /**
  28726. * Overwritten to updated spot light specific uniforms.
  28727. *
  28728. * @param {NodeFrame} frame - A reference to the current node frame.
  28729. */
  28730. update( frame ) {
  28731. super.update( frame );
  28732. const { light } = this;
  28733. this.coneCosNode.value = Math.cos( light.angle );
  28734. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  28735. this.cutoffDistanceNode.value = light.distance;
  28736. this.decayExponentNode.value = light.decay;
  28737. }
  28738. /**
  28739. * Computes the spot attenuation for the given angle.
  28740. *
  28741. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  28742. * @return {Node<float>} The spot attenuation.
  28743. */
  28744. getSpotAttenuation( angleCosine ) {
  28745. const { coneCosNode, penumbraCosNode } = this;
  28746. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  28747. }
  28748. setup( builder ) {
  28749. super.setup( builder );
  28750. const lightingModel = builder.context.lightingModel;
  28751. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  28752. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  28753. const lightDirection = lVector.normalize();
  28754. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  28755. const spotAttenuation = this.getSpotAttenuation( angleCos );
  28756. const lightDistance = lVector.length();
  28757. const lightAttenuation = getDistanceAttenuation( {
  28758. lightDistance,
  28759. cutoffDistance: cutoffDistanceNode,
  28760. decayExponent: decayExponentNode
  28761. } );
  28762. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  28763. if ( light.map ) {
  28764. const spotLightCoord = lightProjectionUV( light );
  28765. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  28766. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  28767. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  28768. }
  28769. const reflectedLight = builder.context.reflectedLight;
  28770. lightingModel.direct( {
  28771. lightDirection,
  28772. lightColor,
  28773. reflectedLight
  28774. }, builder.stack, builder );
  28775. }
  28776. }
  28777. /**
  28778. * An IES version of the default spot light node.
  28779. *
  28780. * @augments SpotLightNode
  28781. */
  28782. class IESSpotLightNode extends SpotLightNode {
  28783. static get type() {
  28784. return 'IESSpotLightNode';
  28785. }
  28786. /**
  28787. * Overwrites the default implementation to compute an IES conform spot attenuation.
  28788. *
  28789. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  28790. * @return {Node<float>} The spot attenuation.
  28791. */
  28792. getSpotAttenuation( angleCosine ) {
  28793. const iesMap = this.light.iesMap;
  28794. let spotAttenuation = null;
  28795. if ( iesMap && iesMap.isTexture === true ) {
  28796. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  28797. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  28798. } else {
  28799. spotAttenuation = super.getSpotAttenuation( angleCosine );
  28800. }
  28801. return spotAttenuation;
  28802. }
  28803. }
  28804. /**
  28805. * Module for representing ambient lights as nodes.
  28806. *
  28807. * @augments AnalyticLightNode
  28808. */
  28809. class AmbientLightNode extends AnalyticLightNode {
  28810. static get type() {
  28811. return 'AmbientLightNode';
  28812. }
  28813. /**
  28814. * Constructs a new ambient light node.
  28815. *
  28816. * @param {AmbientLight?} [light=null] - The ambient light source.
  28817. */
  28818. constructor( light = null ) {
  28819. super( light );
  28820. }
  28821. setup( { context } ) {
  28822. context.irradiance.addAssign( this.colorNode );
  28823. }
  28824. }
  28825. /**
  28826. * Module for representing hemisphere lights as nodes.
  28827. *
  28828. * @augments AnalyticLightNode
  28829. */
  28830. class HemisphereLightNode extends AnalyticLightNode {
  28831. static get type() {
  28832. return 'HemisphereLightNode';
  28833. }
  28834. /**
  28835. * Constructs a new hemisphere light node.
  28836. *
  28837. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  28838. */
  28839. constructor( light = null ) {
  28840. super( light );
  28841. /**
  28842. * Uniform node representing the light's position.
  28843. *
  28844. * @type {UniformNode<vec3>}
  28845. */
  28846. this.lightPositionNode = lightPosition( light );
  28847. /**
  28848. * A node representing the light's direction.
  28849. *
  28850. * @type {Node<vec3>}
  28851. */
  28852. this.lightDirectionNode = this.lightPositionNode.normalize();
  28853. /**
  28854. * Uniform node representing the light's ground color.
  28855. *
  28856. * @type {UniformNode<vec3>}
  28857. */
  28858. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  28859. }
  28860. /**
  28861. * Overwritten to updated hemisphere light specific uniforms.
  28862. *
  28863. * @param {NodeFrame} frame - A reference to the current node frame.
  28864. */
  28865. update( frame ) {
  28866. const { light } = this;
  28867. super.update( frame );
  28868. this.lightPositionNode.object3d = light;
  28869. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  28870. }
  28871. setup( builder ) {
  28872. const { colorNode, groundColorNode, lightDirectionNode } = this;
  28873. const dotNL = normalView.dot( lightDirectionNode );
  28874. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  28875. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  28876. builder.context.irradiance.addAssign( irradiance );
  28877. }
  28878. }
  28879. /**
  28880. * Module for representing light probes as nodes.
  28881. *
  28882. * @augments AnalyticLightNode
  28883. */
  28884. class LightProbeNode extends AnalyticLightNode {
  28885. static get type() {
  28886. return 'LightProbeNode';
  28887. }
  28888. /**
  28889. * Constructs a new light probe node.
  28890. *
  28891. * @param {LightProbe?} [light=null] - The light probe.
  28892. */
  28893. constructor( light = null ) {
  28894. super( light );
  28895. const array = [];
  28896. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  28897. /**
  28898. * Light probe represented as a uniform of spherical harmonics.
  28899. *
  28900. * @type {UniformArrayNode}
  28901. */
  28902. this.lightProbe = uniformArray( array );
  28903. }
  28904. /**
  28905. * Overwritten to updated light probe specific uniforms.
  28906. *
  28907. * @param {NodeFrame} frame - A reference to the current node frame.
  28908. */
  28909. update( frame ) {
  28910. const { light } = this;
  28911. super.update( frame );
  28912. //
  28913. for ( let i = 0; i < 9; i ++ ) {
  28914. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  28915. }
  28916. }
  28917. setup( builder ) {
  28918. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  28919. builder.context.irradiance.addAssign( irradiance );
  28920. }
  28921. }
  28922. /**
  28923. * Base class for node parsers. A derived parser must be implemented
  28924. * for each supported native shader language.
  28925. */
  28926. class NodeParser {
  28927. /**
  28928. * The method parses the given native code an returns a node function.
  28929. *
  28930. * @abstract
  28931. * @param {String} source - The native shader code.
  28932. * @return {NodeFunction} A node function.
  28933. */
  28934. parseFunction( /*source*/ ) {
  28935. console.warn( 'Abstract function.' );
  28936. }
  28937. }
  28938. /**
  28939. * Base class for node functions. A derived module must be implemented
  28940. * for each supported native shader language. Similar to other `Node*` modules,
  28941. * this class is only relevant during the building process and not used
  28942. * in user-level code.
  28943. */
  28944. class NodeFunction {
  28945. /**
  28946. * Constructs a new node function.
  28947. *
  28948. * @param {String} type - The node type. This type is the return type of the node function.
  28949. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  28950. * @param {String} [name=''] - The function's name.
  28951. * @param {String} [precision=''] - The precision qualifier.
  28952. */
  28953. constructor( type, inputs, name = '', precision = '' ) {
  28954. /**
  28955. * The node type. This type is the return type of the node function.
  28956. *
  28957. * @type {String}
  28958. */
  28959. this.type = type;
  28960. /**
  28961. * The function's inputs.
  28962. *
  28963. * @type {Array<NodeFunctionInput>}
  28964. */
  28965. this.inputs = inputs;
  28966. /**
  28967. * The name of the uniform.
  28968. *
  28969. * @type {String}
  28970. * @default ''
  28971. */
  28972. this.name = name;
  28973. /**
  28974. * The precision qualifier.
  28975. *
  28976. * @type {String}
  28977. * @default ''
  28978. */
  28979. this.precision = precision;
  28980. }
  28981. /**
  28982. * This method returns the native code of the node function.
  28983. *
  28984. * @abstract
  28985. * @param {String} name - The function's name.
  28986. * @return {String} A shader code.
  28987. */
  28988. getCode( /*name = this.name*/ ) {
  28989. console.warn( 'Abstract function.' );
  28990. }
  28991. }
  28992. NodeFunction.isNodeFunction = true;
  28993. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  28994. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  28995. const pragmaMain = '#pragma main';
  28996. const parse$1 = ( source ) => {
  28997. source = source.trim();
  28998. const pragmaMainIndex = source.indexOf( pragmaMain );
  28999. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  29000. const declaration = mainCode.match( declarationRegexp$1 );
  29001. if ( declaration !== null && declaration.length === 5 ) {
  29002. // tokenizer
  29003. const inputsCode = declaration[ 4 ];
  29004. const propsMatches = [];
  29005. let nameMatch = null;
  29006. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  29007. propsMatches.push( nameMatch );
  29008. }
  29009. // parser
  29010. const inputs = [];
  29011. let i = 0;
  29012. while ( i < propsMatches.length ) {
  29013. const isConst = propsMatches[ i ][ 0 ] === 'const';
  29014. if ( isConst === true ) {
  29015. i ++;
  29016. }
  29017. let qualifier = propsMatches[ i ][ 0 ];
  29018. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  29019. i ++;
  29020. } else {
  29021. qualifier = '';
  29022. }
  29023. const type = propsMatches[ i ++ ][ 0 ];
  29024. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  29025. if ( Number.isNaN( count ) === false ) i ++;
  29026. else count = null;
  29027. const name = propsMatches[ i ++ ][ 0 ];
  29028. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  29029. }
  29030. //
  29031. const blockCode = mainCode.substring( declaration[ 0 ].length );
  29032. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  29033. const type = declaration[ 2 ];
  29034. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  29035. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  29036. return {
  29037. type,
  29038. inputs,
  29039. name,
  29040. precision,
  29041. inputsCode,
  29042. blockCode,
  29043. headerCode
  29044. };
  29045. } else {
  29046. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  29047. }
  29048. };
  29049. /**
  29050. * This class represents a GLSL node function.
  29051. *
  29052. * @augments NodeFunction
  29053. */
  29054. class GLSLNodeFunction extends NodeFunction {
  29055. /**
  29056. * Constructs a new GLSL node function.
  29057. *
  29058. * @param {String} source - The GLSL source.
  29059. */
  29060. constructor( source ) {
  29061. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  29062. super( type, inputs, name, precision );
  29063. this.inputsCode = inputsCode;
  29064. this.blockCode = blockCode;
  29065. this.headerCode = headerCode;
  29066. }
  29067. /**
  29068. * This method returns the GLSL code of the node function.
  29069. *
  29070. * @param {String} [name=this.name] - The function's name.
  29071. * @return {String} The shader code.
  29072. */
  29073. getCode( name = this.name ) {
  29074. let code;
  29075. const blockCode = this.blockCode;
  29076. if ( blockCode !== '' ) {
  29077. const { type, inputsCode, headerCode, precision } = this;
  29078. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  29079. if ( precision !== '' ) {
  29080. declarationCode = `${ precision } ${ declarationCode }`;
  29081. }
  29082. code = headerCode + declarationCode + blockCode;
  29083. } else {
  29084. // interface function
  29085. code = '';
  29086. }
  29087. return code;
  29088. }
  29089. }
  29090. /**
  29091. * A GLSL node parser.
  29092. *
  29093. * @augments NodeParser
  29094. */
  29095. class GLSLNodeParser extends NodeParser {
  29096. /**
  29097. * The method parses the given GLSL code an returns a node function.
  29098. *
  29099. * @param {String} source - The GLSL code.
  29100. * @return {GLSLNodeFunction} A node function.
  29101. */
  29102. parseFunction( source ) {
  29103. return new GLSLNodeFunction( source );
  29104. }
  29105. }
  29106. const outputNodeMap = new WeakMap();
  29107. class Nodes extends DataMap {
  29108. constructor( renderer, backend ) {
  29109. super();
  29110. this.renderer = renderer;
  29111. this.backend = backend;
  29112. this.nodeFrame = new NodeFrame();
  29113. this.nodeBuilderCache = new Map();
  29114. this.callHashCache = new ChainMap();
  29115. this.groupsData = new ChainMap();
  29116. }
  29117. updateGroup( nodeUniformsGroup ) {
  29118. const groupNode = nodeUniformsGroup.groupNode;
  29119. const name = groupNode.name;
  29120. // objectGroup is every updated
  29121. if ( name === objectGroup.name ) return true;
  29122. // renderGroup is updated once per render/compute call
  29123. if ( name === renderGroup.name ) {
  29124. const uniformsGroupData = this.get( nodeUniformsGroup );
  29125. const renderId = this.nodeFrame.renderId;
  29126. if ( uniformsGroupData.renderId !== renderId ) {
  29127. uniformsGroupData.renderId = renderId;
  29128. return true;
  29129. }
  29130. return false;
  29131. }
  29132. // frameGroup is updated once per frame
  29133. if ( name === frameGroup.name ) {
  29134. const uniformsGroupData = this.get( nodeUniformsGroup );
  29135. const frameId = this.nodeFrame.frameId;
  29136. if ( uniformsGroupData.frameId !== frameId ) {
  29137. uniformsGroupData.frameId = frameId;
  29138. return true;
  29139. }
  29140. return false;
  29141. }
  29142. // other groups are updated just when groupNode.needsUpdate is true
  29143. const groupChain = [ groupNode, nodeUniformsGroup ];
  29144. let groupData = this.groupsData.get( groupChain );
  29145. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  29146. if ( groupData.version !== groupNode.version ) {
  29147. groupData.version = groupNode.version;
  29148. return true;
  29149. }
  29150. return false;
  29151. }
  29152. getForRenderCacheKey( renderObject ) {
  29153. return renderObject.initialCacheKey;
  29154. }
  29155. getForRender( renderObject ) {
  29156. const renderObjectData = this.get( renderObject );
  29157. let nodeBuilderState = renderObjectData.nodeBuilderState;
  29158. if ( nodeBuilderState === undefined ) {
  29159. const { nodeBuilderCache } = this;
  29160. const cacheKey = this.getForRenderCacheKey( renderObject );
  29161. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  29162. if ( nodeBuilderState === undefined ) {
  29163. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  29164. nodeBuilder.scene = renderObject.scene;
  29165. nodeBuilder.material = renderObject.material;
  29166. nodeBuilder.camera = renderObject.camera;
  29167. nodeBuilder.context.material = renderObject.material;
  29168. nodeBuilder.lightsNode = renderObject.lightsNode;
  29169. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  29170. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  29171. nodeBuilder.clippingContext = renderObject.clippingContext;
  29172. nodeBuilder.build();
  29173. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  29174. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  29175. }
  29176. nodeBuilderState.usedTimes ++;
  29177. renderObjectData.nodeBuilderState = nodeBuilderState;
  29178. }
  29179. return nodeBuilderState;
  29180. }
  29181. delete( object ) {
  29182. if ( object.isRenderObject ) {
  29183. const nodeBuilderState = this.get( object ).nodeBuilderState;
  29184. nodeBuilderState.usedTimes --;
  29185. if ( nodeBuilderState.usedTimes === 0 ) {
  29186. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  29187. }
  29188. }
  29189. return super.delete( object );
  29190. }
  29191. getForCompute( computeNode ) {
  29192. const computeData = this.get( computeNode );
  29193. let nodeBuilderState = computeData.nodeBuilderState;
  29194. if ( nodeBuilderState === undefined ) {
  29195. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  29196. nodeBuilder.build();
  29197. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  29198. computeData.nodeBuilderState = nodeBuilderState;
  29199. }
  29200. return nodeBuilderState;
  29201. }
  29202. _createNodeBuilderState( nodeBuilder ) {
  29203. return new NodeBuilderState(
  29204. nodeBuilder.vertexShader,
  29205. nodeBuilder.fragmentShader,
  29206. nodeBuilder.computeShader,
  29207. nodeBuilder.getAttributesArray(),
  29208. nodeBuilder.getBindings(),
  29209. nodeBuilder.updateNodes,
  29210. nodeBuilder.updateBeforeNodes,
  29211. nodeBuilder.updateAfterNodes,
  29212. nodeBuilder.monitor,
  29213. nodeBuilder.transforms
  29214. );
  29215. }
  29216. getEnvironmentNode( scene ) {
  29217. let environmentNode = null;
  29218. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  29219. environmentNode = scene.environmentNode;
  29220. } else {
  29221. const sceneData = this.get( scene );
  29222. if ( sceneData.environmentNode ) {
  29223. environmentNode = sceneData.environmentNode;
  29224. }
  29225. }
  29226. return environmentNode;
  29227. }
  29228. getBackgroundNode( scene ) {
  29229. let backgroundNode = null;
  29230. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  29231. backgroundNode = scene.backgroundNode;
  29232. } else {
  29233. const sceneData = this.get( scene );
  29234. if ( sceneData.backgroundNode ) {
  29235. backgroundNode = sceneData.backgroundNode;
  29236. }
  29237. }
  29238. return backgroundNode;
  29239. }
  29240. getFogNode( scene ) {
  29241. return scene.fogNode || this.get( scene ).fogNode || null;
  29242. }
  29243. getCacheKey( scene, lightsNode ) {
  29244. const chain = [ scene, lightsNode ];
  29245. const callId = this.renderer.info.calls;
  29246. let cacheKeyData = this.callHashCache.get( chain );
  29247. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  29248. const environmentNode = this.getEnvironmentNode( scene );
  29249. const fogNode = this.getFogNode( scene );
  29250. const values = [];
  29251. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  29252. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  29253. if ( fogNode ) values.push( fogNode.getCacheKey() );
  29254. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  29255. cacheKeyData = {
  29256. callId,
  29257. cacheKey: hashArray( values )
  29258. };
  29259. this.callHashCache.set( chain, cacheKeyData );
  29260. }
  29261. return cacheKeyData.cacheKey;
  29262. }
  29263. updateScene( scene ) {
  29264. this.updateEnvironment( scene );
  29265. this.updateFog( scene );
  29266. this.updateBackground( scene );
  29267. }
  29268. get isToneMappingState() {
  29269. return this.renderer.getRenderTarget() ? false : true;
  29270. }
  29271. updateBackground( scene ) {
  29272. const sceneData = this.get( scene );
  29273. const background = scene.background;
  29274. if ( background ) {
  29275. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  29276. if ( sceneData.background !== background || forceUpdate ) {
  29277. let backgroundNode = null;
  29278. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  29279. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  29280. backgroundNode = pmremTexture( background );
  29281. } else {
  29282. let envMap;
  29283. if ( background.isCubeTexture === true ) {
  29284. envMap = cubeTexture( background );
  29285. } else {
  29286. envMap = texture( background );
  29287. }
  29288. backgroundNode = cubeMapNode( envMap );
  29289. }
  29290. } else if ( background.isTexture === true ) {
  29291. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  29292. } else if ( background.isColor !== true ) {
  29293. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  29294. }
  29295. sceneData.backgroundNode = backgroundNode;
  29296. sceneData.background = background;
  29297. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  29298. }
  29299. } else if ( sceneData.backgroundNode ) {
  29300. delete sceneData.backgroundNode;
  29301. delete sceneData.background;
  29302. }
  29303. }
  29304. updateFog( scene ) {
  29305. const sceneData = this.get( scene );
  29306. const sceneFog = scene.fog;
  29307. if ( sceneFog ) {
  29308. if ( sceneData.fog !== sceneFog ) {
  29309. let fogNode = null;
  29310. if ( sceneFog.isFogExp2 ) {
  29311. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  29312. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  29313. fogNode = fog( color, densityFogFactor( density ) );
  29314. } else if ( sceneFog.isFog ) {
  29315. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  29316. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  29317. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  29318. fogNode = fog( color, rangeFogFactor( near, far ) );
  29319. } else {
  29320. console.error( 'WebGPUNodes: Unsupported fog configuration.', sceneFog );
  29321. }
  29322. sceneData.fogNode = fogNode;
  29323. sceneData.fog = sceneFog;
  29324. }
  29325. } else {
  29326. delete sceneData.fogNode;
  29327. delete sceneData.fog;
  29328. }
  29329. }
  29330. updateEnvironment( scene ) {
  29331. const sceneData = this.get( scene );
  29332. const environment = scene.environment;
  29333. if ( environment ) {
  29334. if ( sceneData.environment !== environment ) {
  29335. let environmentNode = null;
  29336. if ( environment.isCubeTexture === true ) {
  29337. environmentNode = cubeTexture( environment );
  29338. } else if ( environment.isTexture === true ) {
  29339. environmentNode = texture( environment );
  29340. } else {
  29341. console.error( 'Nodes: Unsupported environment configuration.', environment );
  29342. }
  29343. sceneData.environmentNode = environmentNode;
  29344. sceneData.environment = environment;
  29345. }
  29346. } else if ( sceneData.environmentNode ) {
  29347. delete sceneData.environmentNode;
  29348. delete sceneData.environment;
  29349. }
  29350. }
  29351. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  29352. const nodeFrame = this.nodeFrame;
  29353. nodeFrame.renderer = renderer;
  29354. nodeFrame.scene = scene;
  29355. nodeFrame.object = object;
  29356. nodeFrame.camera = camera;
  29357. nodeFrame.material = material;
  29358. return nodeFrame;
  29359. }
  29360. getNodeFrameForRender( renderObject ) {
  29361. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  29362. }
  29363. getOutputCacheKey() {
  29364. const renderer = this.renderer;
  29365. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  29366. }
  29367. hasOutputChange( outputTarget ) {
  29368. const cacheKey = outputNodeMap.get( outputTarget );
  29369. return cacheKey !== this.getOutputCacheKey();
  29370. }
  29371. getOutputNode( outputTexture ) {
  29372. const renderer = this.renderer;
  29373. const cacheKey = this.getOutputCacheKey();
  29374. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  29375. outputNodeMap.set( outputTexture, cacheKey );
  29376. return output;
  29377. }
  29378. updateBefore( renderObject ) {
  29379. const nodeBuilder = renderObject.getNodeBuilderState();
  29380. for ( const node of nodeBuilder.updateBeforeNodes ) {
  29381. // update frame state for each node
  29382. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  29383. }
  29384. }
  29385. updateAfter( renderObject ) {
  29386. const nodeBuilder = renderObject.getNodeBuilderState();
  29387. for ( const node of nodeBuilder.updateAfterNodes ) {
  29388. // update frame state for each node
  29389. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  29390. }
  29391. }
  29392. updateForCompute( computeNode ) {
  29393. const nodeFrame = this.getNodeFrame();
  29394. const nodeBuilder = this.getForCompute( computeNode );
  29395. for ( const node of nodeBuilder.updateNodes ) {
  29396. nodeFrame.updateNode( node );
  29397. }
  29398. }
  29399. updateForRender( renderObject ) {
  29400. const nodeFrame = this.getNodeFrameForRender( renderObject );
  29401. const nodeBuilder = renderObject.getNodeBuilderState();
  29402. for ( const node of nodeBuilder.updateNodes ) {
  29403. nodeFrame.updateNode( node );
  29404. }
  29405. }
  29406. needsRefresh( renderObject ) {
  29407. const nodeFrame = this.getNodeFrameForRender( renderObject );
  29408. const monitor = renderObject.getMonitor();
  29409. return monitor.needsRefresh( renderObject, nodeFrame );
  29410. }
  29411. dispose() {
  29412. super.dispose();
  29413. this.nodeFrame = new NodeFrame();
  29414. this.nodeBuilderCache = new Map();
  29415. }
  29416. }
  29417. const _plane = /*@__PURE__*/ new Plane();
  29418. class ClippingContext {
  29419. constructor( parentContext = null ) {
  29420. this.version = 0;
  29421. this.clipIntersection = null;
  29422. this.cacheKey = '';
  29423. if ( parentContext === null ) {
  29424. this.intersectionPlanes = [];
  29425. this.unionPlanes = [];
  29426. this.viewNormalMatrix = new Matrix3();
  29427. this.clippingGroupContexts = new WeakMap();
  29428. this.shadowPass = false;
  29429. } else {
  29430. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  29431. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  29432. this.shadowPass = parentContext.shadowPass;
  29433. this.viewMatrix = parentContext.viewMatrix;
  29434. }
  29435. this.parentVersion = null;
  29436. }
  29437. projectPlanes( source, destination, offset ) {
  29438. const l = source.length;
  29439. for ( let i = 0; i < l; i ++ ) {
  29440. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29441. const v = destination[ offset + i ];
  29442. const normal = _plane.normal;
  29443. v.x = - normal.x;
  29444. v.y = - normal.y;
  29445. v.z = - normal.z;
  29446. v.w = _plane.constant;
  29447. }
  29448. }
  29449. updateGlobal( scene, camera ) {
  29450. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  29451. this.viewMatrix = camera.matrixWorldInverse;
  29452. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29453. }
  29454. update( parentContext, clippingGroup ) {
  29455. let update = false;
  29456. if ( parentContext.version !== this.parentVersion ) {
  29457. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  29458. this.unionPlanes = Array.from( parentContext.unionPlanes );
  29459. this.parentVersion = parentContext.version;
  29460. }
  29461. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  29462. this.clipIntersection = clippingGroup.clipIntersection;
  29463. if ( this.clipIntersection ) {
  29464. this.unionPlanes.length = parentContext.unionPlanes.length;
  29465. } else {
  29466. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  29467. }
  29468. }
  29469. const srcClippingPlanes = clippingGroup.clippingPlanes;
  29470. const l = srcClippingPlanes.length;
  29471. let dstClippingPlanes;
  29472. let offset;
  29473. if ( this.clipIntersection ) {
  29474. dstClippingPlanes = this.intersectionPlanes;
  29475. offset = parentContext.intersectionPlanes.length;
  29476. } else {
  29477. dstClippingPlanes = this.unionPlanes;
  29478. offset = parentContext.unionPlanes.length;
  29479. }
  29480. if ( dstClippingPlanes.length !== offset + l ) {
  29481. dstClippingPlanes.length = offset + l;
  29482. for ( let i = 0; i < l; i ++ ) {
  29483. dstClippingPlanes[ offset + i ] = new Vector4();
  29484. }
  29485. update = true;
  29486. }
  29487. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  29488. if ( update ) {
  29489. this.version ++;
  29490. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  29491. }
  29492. }
  29493. getGroupContext( clippingGroup ) {
  29494. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  29495. let context = this.clippingGroupContexts.get( clippingGroup );
  29496. if ( context === undefined ) {
  29497. context = new ClippingContext( this );
  29498. this.clippingGroupContexts.set( clippingGroup, context );
  29499. }
  29500. context.update( this, clippingGroup );
  29501. return context;
  29502. }
  29503. get unionClippingCount() {
  29504. return this.unionPlanes.length;
  29505. }
  29506. }
  29507. class RenderBundle {
  29508. constructor( scene, camera ) {
  29509. this.scene = scene;
  29510. this.camera = camera;
  29511. }
  29512. clone() {
  29513. return Object.assign( new this.constructor(), this );
  29514. }
  29515. }
  29516. class RenderBundles {
  29517. constructor() {
  29518. this.lists = new ChainMap();
  29519. }
  29520. get( scene, camera ) {
  29521. const lists = this.lists;
  29522. const keys = [ scene, camera ];
  29523. let list = lists.get( keys );
  29524. if ( list === undefined ) {
  29525. list = new RenderBundle( scene, camera );
  29526. lists.set( keys, list );
  29527. }
  29528. return list;
  29529. }
  29530. dispose() {
  29531. this.lists = new ChainMap();
  29532. }
  29533. }
  29534. class NodeLibrary {
  29535. constructor() {
  29536. this.lightNodes = new WeakMap();
  29537. this.materialNodes = new Map();
  29538. this.toneMappingNodes = new Map();
  29539. }
  29540. fromMaterial( material ) {
  29541. if ( material.isNodeMaterial ) return material;
  29542. let nodeMaterial = null;
  29543. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  29544. if ( nodeMaterialClass !== null ) {
  29545. nodeMaterial = new nodeMaterialClass();
  29546. for ( const key in material ) {
  29547. nodeMaterial[ key ] = material[ key ];
  29548. }
  29549. }
  29550. return nodeMaterial;
  29551. }
  29552. addToneMapping( toneMappingNode, toneMapping ) {
  29553. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  29554. }
  29555. getToneMappingFunction( toneMapping ) {
  29556. return this.toneMappingNodes.get( toneMapping ) || null;
  29557. }
  29558. getMaterialNodeClass( materialType ) {
  29559. return this.materialNodes.get( materialType ) || null;
  29560. }
  29561. addMaterial( materialNodeClass, materialClassType ) {
  29562. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  29563. }
  29564. getLightNodeClass( light ) {
  29565. return this.lightNodes.get( light ) || null;
  29566. }
  29567. addLight( lightNodeClass, lightClass ) {
  29568. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  29569. }
  29570. addType( nodeClass, type, library ) {
  29571. if ( library.has( type ) ) {
  29572. console.warn( `Redefinition of node ${ type }` );
  29573. return;
  29574. }
  29575. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  29576. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  29577. library.set( type, nodeClass );
  29578. }
  29579. addClass( nodeClass, baseClass, library ) {
  29580. if ( library.has( baseClass ) ) {
  29581. console.warn( `Redefinition of node ${ baseClass.name }` );
  29582. return;
  29583. }
  29584. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  29585. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  29586. library.set( baseClass, nodeClass );
  29587. }
  29588. }
  29589. const _defaultLights = /*@__PURE__*/ new LightsNode();
  29590. class Lighting extends ChainMap {
  29591. constructor() {
  29592. super();
  29593. }
  29594. createNode( lights = [] ) {
  29595. return new LightsNode().setLights( lights );
  29596. }
  29597. getNode( scene, camera ) {
  29598. // ignore post-processing
  29599. if ( scene.isQuadMesh ) return _defaultLights;
  29600. // tiled lighting
  29601. const keys = [ scene, camera ];
  29602. let node = this.get( keys );
  29603. if ( node === undefined ) {
  29604. node = this.createNode();
  29605. this.set( keys, node );
  29606. }
  29607. return node;
  29608. }
  29609. }
  29610. const _scene = /*@__PURE__*/ new Scene();
  29611. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  29612. const _screen = /*@__PURE__*/ new Vector4();
  29613. const _frustum = /*@__PURE__*/ new Frustum();
  29614. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  29615. const _vector4 = /*@__PURE__*/ new Vector4();
  29616. class Renderer {
  29617. constructor( backend, parameters = {} ) {
  29618. this.isRenderer = true;
  29619. //
  29620. const {
  29621. logarithmicDepthBuffer = false,
  29622. alpha = true,
  29623. depth = true,
  29624. stencil = false,
  29625. antialias = false,
  29626. samples = 0,
  29627. getFallback = null
  29628. } = parameters;
  29629. // public
  29630. this.domElement = backend.getDomElement();
  29631. this.backend = backend;
  29632. this.samples = samples || ( antialias === true ) ? 4 : 0;
  29633. this.autoClear = true;
  29634. this.autoClearColor = true;
  29635. this.autoClearDepth = true;
  29636. this.autoClearStencil = true;
  29637. this.alpha = alpha;
  29638. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  29639. this.outputColorSpace = SRGBColorSpace;
  29640. this.toneMapping = NoToneMapping;
  29641. this.toneMappingExposure = 1.0;
  29642. this.sortObjects = true;
  29643. this.depth = depth;
  29644. this.stencil = stencil;
  29645. this.info = new Info();
  29646. this.nodes = {
  29647. modelViewMatrix: null,
  29648. modelNormalViewMatrix: null
  29649. };
  29650. this.library = new NodeLibrary();
  29651. this.lighting = new Lighting();
  29652. // internals
  29653. this._getFallback = getFallback;
  29654. this._pixelRatio = 1;
  29655. this._width = this.domElement.width;
  29656. this._height = this.domElement.height;
  29657. this._viewport = new Vector4( 0, 0, this._width, this._height );
  29658. this._scissor = new Vector4( 0, 0, this._width, this._height );
  29659. this._scissorTest = false;
  29660. this._attributes = null;
  29661. this._geometries = null;
  29662. this._nodes = null;
  29663. this._animation = null;
  29664. this._bindings = null;
  29665. this._objects = null;
  29666. this._pipelines = null;
  29667. this._bundles = null;
  29668. this._renderLists = null;
  29669. this._renderContexts = null;
  29670. this._textures = null;
  29671. this._background = null;
  29672. this._quad = new QuadMesh( new NodeMaterial() );
  29673. this._quad.material.type = 'Renderer_output';
  29674. this._currentRenderContext = null;
  29675. this._opaqueSort = null;
  29676. this._transparentSort = null;
  29677. this._frameBufferTarget = null;
  29678. const alphaClear = this.alpha === true ? 0 : 1;
  29679. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  29680. this._clearDepth = 1;
  29681. this._clearStencil = 0;
  29682. this._renderTarget = null;
  29683. this._activeCubeFace = 0;
  29684. this._activeMipmapLevel = 0;
  29685. this._mrt = null;
  29686. this._renderObjectFunction = null;
  29687. this._currentRenderObjectFunction = null;
  29688. this._currentRenderBundle = null;
  29689. this._handleObjectFunction = this._renderObjectDirect;
  29690. this._isDeviceLost = false;
  29691. this.onDeviceLost = this._onDeviceLost;
  29692. this._initialized = false;
  29693. this._initPromise = null;
  29694. this._compilationPromises = null;
  29695. this.transparent = true;
  29696. this.opaque = true;
  29697. this.shadowMap = {
  29698. enabled: false,
  29699. type: PCFShadowMap
  29700. };
  29701. this.xr = {
  29702. enabled: false
  29703. };
  29704. this.debug = {
  29705. checkShaderErrors: true,
  29706. onShaderError: null,
  29707. getShaderAsync: async ( scene, camera, object ) => {
  29708. await this.compileAsync( scene, camera );
  29709. const renderList = this._renderLists.get( scene, camera );
  29710. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  29711. const material = scene.overrideMaterial || object.material;
  29712. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  29713. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  29714. return { fragmentShader, vertexShader };
  29715. }
  29716. };
  29717. }
  29718. async init() {
  29719. if ( this._initialized ) {
  29720. throw new Error( 'Renderer: Backend has already been initialized.' );
  29721. }
  29722. if ( this._initPromise !== null ) {
  29723. return this._initPromise;
  29724. }
  29725. this._initPromise = new Promise( async ( resolve, reject ) => {
  29726. let backend = this.backend;
  29727. try {
  29728. await backend.init( this );
  29729. } catch ( error ) {
  29730. if ( this._getFallback !== null ) {
  29731. // try the fallback
  29732. try {
  29733. this.backend = backend = this._getFallback( error );
  29734. await backend.init( this );
  29735. } catch ( error ) {
  29736. reject( error );
  29737. return;
  29738. }
  29739. } else {
  29740. reject( error );
  29741. return;
  29742. }
  29743. }
  29744. this._nodes = new Nodes( this, backend );
  29745. this._animation = new Animation( this._nodes, this.info );
  29746. this._attributes = new Attributes( backend );
  29747. this._background = new Background( this, this._nodes );
  29748. this._geometries = new Geometries( this._attributes, this.info );
  29749. this._textures = new Textures( this, backend, this.info );
  29750. this._pipelines = new Pipelines( backend, this._nodes );
  29751. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  29752. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  29753. this._renderLists = new RenderLists( this.lighting );
  29754. this._bundles = new RenderBundles();
  29755. this._renderContexts = new RenderContexts();
  29756. //
  29757. this._animation.start();
  29758. this._initialized = true;
  29759. resolve();
  29760. } );
  29761. return this._initPromise;
  29762. }
  29763. get coordinateSystem() {
  29764. return this.backend.coordinateSystem;
  29765. }
  29766. async compileAsync( scene, camera, targetScene = null ) {
  29767. if ( this._isDeviceLost === true ) return;
  29768. if ( this._initialized === false ) await this.init();
  29769. // preserve render tree
  29770. const nodeFrame = this._nodes.nodeFrame;
  29771. const previousRenderId = nodeFrame.renderId;
  29772. const previousRenderContext = this._currentRenderContext;
  29773. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  29774. const previousCompilationPromises = this._compilationPromises;
  29775. //
  29776. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  29777. if ( targetScene === null ) targetScene = scene;
  29778. const renderTarget = this._renderTarget;
  29779. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  29780. const activeMipmapLevel = this._activeMipmapLevel;
  29781. const compilationPromises = [];
  29782. this._currentRenderContext = renderContext;
  29783. this._currentRenderObjectFunction = this.renderObject;
  29784. this._handleObjectFunction = this._createObjectPipeline;
  29785. this._compilationPromises = compilationPromises;
  29786. nodeFrame.renderId ++;
  29787. //
  29788. nodeFrame.update();
  29789. //
  29790. renderContext.depth = this.depth;
  29791. renderContext.stencil = this.stencil;
  29792. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  29793. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  29794. //
  29795. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  29796. //
  29797. const renderList = this._renderLists.get( scene, camera );
  29798. renderList.begin();
  29799. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  29800. // include lights from target scene
  29801. if ( targetScene !== scene ) {
  29802. targetScene.traverseVisible( function ( object ) {
  29803. if ( object.isLight && object.layers.test( camera.layers ) ) {
  29804. renderList.pushLight( object );
  29805. }
  29806. } );
  29807. }
  29808. renderList.finish();
  29809. //
  29810. if ( renderTarget !== null ) {
  29811. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  29812. const renderTargetData = this._textures.get( renderTarget );
  29813. renderContext.textures = renderTargetData.textures;
  29814. renderContext.depthTexture = renderTargetData.depthTexture;
  29815. } else {
  29816. renderContext.textures = null;
  29817. renderContext.depthTexture = null;
  29818. }
  29819. //
  29820. this._nodes.updateScene( sceneRef );
  29821. //
  29822. this._background.update( sceneRef, renderList, renderContext );
  29823. // process render lists
  29824. const opaqueObjects = renderList.opaque;
  29825. const transparentObjects = renderList.transparent;
  29826. const transparentDoublePassObjects = renderList.transparentDoublePass;
  29827. const lightsNode = renderList.lightsNode;
  29828. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  29829. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  29830. // restore render tree
  29831. nodeFrame.renderId = previousRenderId;
  29832. this._currentRenderContext = previousRenderContext;
  29833. this._currentRenderObjectFunction = previousRenderObjectFunction;
  29834. this._compilationPromises = previousCompilationPromises;
  29835. this._handleObjectFunction = this._renderObjectDirect;
  29836. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  29837. await Promise.all( compilationPromises );
  29838. }
  29839. async renderAsync( scene, camera ) {
  29840. if ( this._initialized === false ) await this.init();
  29841. const renderContext = this._renderScene( scene, camera );
  29842. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  29843. }
  29844. async waitForGPU() {
  29845. await this.backend.waitForGPU();
  29846. }
  29847. setMRT( mrt ) {
  29848. this._mrt = mrt;
  29849. return this;
  29850. }
  29851. getMRT() {
  29852. return this._mrt;
  29853. }
  29854. _onDeviceLost( info ) {
  29855. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  29856. if ( info.reason ) {
  29857. errorMessage += `\nReason: ${info.reason}`;
  29858. }
  29859. console.error( errorMessage );
  29860. this._isDeviceLost = true;
  29861. }
  29862. _renderBundle( bundle, sceneRef, lightsNode ) {
  29863. const { bundleGroup, camera, renderList } = bundle;
  29864. const renderContext = this._currentRenderContext;
  29865. //
  29866. const renderBundle = this._bundles.get( bundleGroup, camera );
  29867. const renderBundleData = this.backend.get( renderBundle );
  29868. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  29869. //
  29870. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  29871. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  29872. renderBundleData.renderContexts.add( renderContext );
  29873. if ( renderBundleNeedsUpdate ) {
  29874. this.backend.beginBundle( renderContext );
  29875. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  29876. renderBundleData.renderObjects = [];
  29877. }
  29878. this._currentRenderBundle = renderBundle;
  29879. const opaqueObjects = renderList.opaque;
  29880. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  29881. this._currentRenderBundle = null;
  29882. //
  29883. this.backend.finishBundle( renderContext, renderBundle );
  29884. renderBundleData.version = bundleGroup.version;
  29885. } else {
  29886. const { renderObjects } = renderBundleData;
  29887. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  29888. const renderObject = renderObjects[ i ];
  29889. if ( this._nodes.needsRefresh( renderObject ) ) {
  29890. this._nodes.updateBefore( renderObject );
  29891. this._nodes.updateForRender( renderObject );
  29892. this._bindings.updateForRender( renderObject );
  29893. this._nodes.updateAfter( renderObject );
  29894. }
  29895. }
  29896. }
  29897. this.backend.addBundle( renderContext, renderBundle );
  29898. }
  29899. render( scene, camera ) {
  29900. if ( this._initialized === false ) {
  29901. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  29902. return this.renderAsync( scene, camera );
  29903. }
  29904. this._renderScene( scene, camera );
  29905. }
  29906. _getFrameBufferTarget() {
  29907. const { currentToneMapping, currentColorSpace } = this;
  29908. const useToneMapping = currentToneMapping !== NoToneMapping;
  29909. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  29910. if ( useToneMapping === false && useColorSpace === false ) return null;
  29911. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  29912. const { depth, stencil } = this;
  29913. let frameBufferTarget = this._frameBufferTarget;
  29914. if ( frameBufferTarget === null ) {
  29915. frameBufferTarget = new RenderTarget( width, height, {
  29916. depthBuffer: depth,
  29917. stencilBuffer: stencil,
  29918. type: HalfFloatType, // FloatType
  29919. format: RGBAFormat,
  29920. colorSpace: LinearSRGBColorSpace,
  29921. generateMipmaps: false,
  29922. minFilter: LinearFilter,
  29923. magFilter: LinearFilter,
  29924. samples: this.samples
  29925. } );
  29926. frameBufferTarget.isPostProcessingRenderTarget = true;
  29927. this._frameBufferTarget = frameBufferTarget;
  29928. }
  29929. frameBufferTarget.depthBuffer = depth;
  29930. frameBufferTarget.stencilBuffer = stencil;
  29931. frameBufferTarget.setSize( width, height );
  29932. frameBufferTarget.viewport.copy( this._viewport );
  29933. frameBufferTarget.scissor.copy( this._scissor );
  29934. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  29935. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  29936. frameBufferTarget.scissorTest = this._scissorTest;
  29937. return frameBufferTarget;
  29938. }
  29939. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  29940. if ( this._isDeviceLost === true ) return;
  29941. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  29942. // preserve render tree
  29943. const nodeFrame = this._nodes.nodeFrame;
  29944. const previousRenderId = nodeFrame.renderId;
  29945. const previousRenderContext = this._currentRenderContext;
  29946. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  29947. //
  29948. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  29949. const outputRenderTarget = this._renderTarget;
  29950. const activeCubeFace = this._activeCubeFace;
  29951. const activeMipmapLevel = this._activeMipmapLevel;
  29952. //
  29953. let renderTarget;
  29954. if ( frameBufferTarget !== null ) {
  29955. renderTarget = frameBufferTarget;
  29956. this.setRenderTarget( renderTarget );
  29957. } else {
  29958. renderTarget = outputRenderTarget;
  29959. }
  29960. //
  29961. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  29962. this._currentRenderContext = renderContext;
  29963. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  29964. //
  29965. this.info.calls ++;
  29966. this.info.render.calls ++;
  29967. this.info.render.frameCalls ++;
  29968. nodeFrame.renderId = this.info.calls;
  29969. //
  29970. const coordinateSystem = this.coordinateSystem;
  29971. if ( camera.coordinateSystem !== coordinateSystem ) {
  29972. camera.coordinateSystem = coordinateSystem;
  29973. camera.updateProjectionMatrix();
  29974. }
  29975. //
  29976. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  29977. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  29978. //
  29979. let viewport = this._viewport;
  29980. let scissor = this._scissor;
  29981. let pixelRatio = this._pixelRatio;
  29982. if ( renderTarget !== null ) {
  29983. viewport = renderTarget.viewport;
  29984. scissor = renderTarget.scissor;
  29985. pixelRatio = 1;
  29986. }
  29987. this.getDrawingBufferSize( _drawingBufferSize );
  29988. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  29989. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  29990. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  29991. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  29992. renderContext.viewportValue.width >>= activeMipmapLevel;
  29993. renderContext.viewportValue.height >>= activeMipmapLevel;
  29994. renderContext.viewportValue.minDepth = minDepth;
  29995. renderContext.viewportValue.maxDepth = maxDepth;
  29996. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  29997. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  29998. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  29999. renderContext.scissorValue.width >>= activeMipmapLevel;
  30000. renderContext.scissorValue.height >>= activeMipmapLevel;
  30001. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  30002. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  30003. //
  30004. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  30005. //
  30006. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  30007. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  30008. const renderList = this._renderLists.get( scene, camera );
  30009. renderList.begin();
  30010. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  30011. renderList.finish();
  30012. if ( this.sortObjects === true ) {
  30013. renderList.sort( this._opaqueSort, this._transparentSort );
  30014. }
  30015. //
  30016. if ( renderTarget !== null ) {
  30017. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  30018. const renderTargetData = this._textures.get( renderTarget );
  30019. renderContext.textures = renderTargetData.textures;
  30020. renderContext.depthTexture = renderTargetData.depthTexture;
  30021. renderContext.width = renderTargetData.width;
  30022. renderContext.height = renderTargetData.height;
  30023. renderContext.renderTarget = renderTarget;
  30024. renderContext.depth = renderTarget.depthBuffer;
  30025. renderContext.stencil = renderTarget.stencilBuffer;
  30026. } else {
  30027. renderContext.textures = null;
  30028. renderContext.depthTexture = null;
  30029. renderContext.width = this.domElement.width;
  30030. renderContext.height = this.domElement.height;
  30031. renderContext.depth = this.depth;
  30032. renderContext.stencil = this.stencil;
  30033. }
  30034. renderContext.width >>= activeMipmapLevel;
  30035. renderContext.height >>= activeMipmapLevel;
  30036. renderContext.activeCubeFace = activeCubeFace;
  30037. renderContext.activeMipmapLevel = activeMipmapLevel;
  30038. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  30039. //
  30040. this._nodes.updateScene( sceneRef );
  30041. //
  30042. this._background.update( sceneRef, renderList, renderContext );
  30043. //
  30044. this.backend.beginRender( renderContext );
  30045. // process render lists
  30046. const {
  30047. bundles,
  30048. lightsNode,
  30049. transparentDoublePass: transparentDoublePassObjects,
  30050. transparent: transparentObjects,
  30051. opaque: opaqueObjects
  30052. } = renderList;
  30053. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  30054. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  30055. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  30056. // finish render pass
  30057. this.backend.finishRender( renderContext );
  30058. // restore render tree
  30059. nodeFrame.renderId = previousRenderId;
  30060. this._currentRenderContext = previousRenderContext;
  30061. this._currentRenderObjectFunction = previousRenderObjectFunction;
  30062. //
  30063. if ( frameBufferTarget !== null ) {
  30064. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  30065. const quad = this._quad;
  30066. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  30067. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  30068. quad.material.needsUpdate = true;
  30069. }
  30070. this._renderScene( quad, quad.camera, false );
  30071. }
  30072. //
  30073. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  30074. //
  30075. return renderContext;
  30076. }
  30077. getMaxAnisotropy() {
  30078. return this.backend.getMaxAnisotropy();
  30079. }
  30080. getActiveCubeFace() {
  30081. return this._activeCubeFace;
  30082. }
  30083. getActiveMipmapLevel() {
  30084. return this._activeMipmapLevel;
  30085. }
  30086. async setAnimationLoop( callback ) {
  30087. if ( this._initialized === false ) await this.init();
  30088. this._animation.setAnimationLoop( callback );
  30089. }
  30090. async getArrayBufferAsync( attribute ) {
  30091. return await this.backend.getArrayBufferAsync( attribute );
  30092. }
  30093. getContext() {
  30094. return this.backend.getContext();
  30095. }
  30096. getPixelRatio() {
  30097. return this._pixelRatio;
  30098. }
  30099. getDrawingBufferSize( target ) {
  30100. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  30101. }
  30102. getSize( target ) {
  30103. return target.set( this._width, this._height );
  30104. }
  30105. setPixelRatio( value = 1 ) {
  30106. if ( this._pixelRatio === value ) return;
  30107. this._pixelRatio = value;
  30108. this.setSize( this._width, this._height, false );
  30109. }
  30110. setDrawingBufferSize( width, height, pixelRatio ) {
  30111. this._width = width;
  30112. this._height = height;
  30113. this._pixelRatio = pixelRatio;
  30114. this.domElement.width = Math.floor( width * pixelRatio );
  30115. this.domElement.height = Math.floor( height * pixelRatio );
  30116. this.setViewport( 0, 0, width, height );
  30117. if ( this._initialized ) this.backend.updateSize();
  30118. }
  30119. setSize( width, height, updateStyle = true ) {
  30120. this._width = width;
  30121. this._height = height;
  30122. this.domElement.width = Math.floor( width * this._pixelRatio );
  30123. this.domElement.height = Math.floor( height * this._pixelRatio );
  30124. if ( updateStyle === true ) {
  30125. this.domElement.style.width = width + 'px';
  30126. this.domElement.style.height = height + 'px';
  30127. }
  30128. this.setViewport( 0, 0, width, height );
  30129. if ( this._initialized ) this.backend.updateSize();
  30130. }
  30131. setOpaqueSort( method ) {
  30132. this._opaqueSort = method;
  30133. }
  30134. setTransparentSort( method ) {
  30135. this._transparentSort = method;
  30136. }
  30137. getScissor( target ) {
  30138. const scissor = this._scissor;
  30139. target.x = scissor.x;
  30140. target.y = scissor.y;
  30141. target.width = scissor.width;
  30142. target.height = scissor.height;
  30143. return target;
  30144. }
  30145. setScissor( x, y, width, height ) {
  30146. const scissor = this._scissor;
  30147. if ( x.isVector4 ) {
  30148. scissor.copy( x );
  30149. } else {
  30150. scissor.set( x, y, width, height );
  30151. }
  30152. }
  30153. getScissorTest() {
  30154. return this._scissorTest;
  30155. }
  30156. setScissorTest( boolean ) {
  30157. this._scissorTest = boolean;
  30158. this.backend.setScissorTest( boolean );
  30159. }
  30160. getViewport( target ) {
  30161. return target.copy( this._viewport );
  30162. }
  30163. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  30164. const viewport = this._viewport;
  30165. if ( x.isVector4 ) {
  30166. viewport.copy( x );
  30167. } else {
  30168. viewport.set( x, y, width, height );
  30169. }
  30170. viewport.minDepth = minDepth;
  30171. viewport.maxDepth = maxDepth;
  30172. }
  30173. getClearColor( target ) {
  30174. return target.copy( this._clearColor );
  30175. }
  30176. setClearColor( color, alpha = 1 ) {
  30177. this._clearColor.set( color );
  30178. this._clearColor.a = alpha;
  30179. }
  30180. getClearAlpha() {
  30181. return this._clearColor.a;
  30182. }
  30183. setClearAlpha( alpha ) {
  30184. this._clearColor.a = alpha;
  30185. }
  30186. getClearDepth() {
  30187. return this._clearDepth;
  30188. }
  30189. setClearDepth( depth ) {
  30190. this._clearDepth = depth;
  30191. }
  30192. getClearStencil() {
  30193. return this._clearStencil;
  30194. }
  30195. setClearStencil( stencil ) {
  30196. this._clearStencil = stencil;
  30197. }
  30198. isOccluded( object ) {
  30199. const renderContext = this._currentRenderContext;
  30200. return renderContext && this.backend.isOccluded( renderContext, object );
  30201. }
  30202. clear( color = true, depth = true, stencil = true ) {
  30203. if ( this._initialized === false ) {
  30204. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  30205. return this.clearAsync( color, depth, stencil );
  30206. }
  30207. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  30208. let renderTargetData = null;
  30209. if ( renderTarget !== null ) {
  30210. this._textures.updateRenderTarget( renderTarget );
  30211. renderTargetData = this._textures.get( renderTarget );
  30212. }
  30213. this.backend.clear( color, depth, stencil, renderTargetData );
  30214. if ( renderTarget !== null && this._renderTarget === null ) {
  30215. // If a color space transform or tone mapping is required,
  30216. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  30217. const quad = this._quad;
  30218. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  30219. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  30220. quad.material.needsUpdate = true;
  30221. }
  30222. this._renderScene( quad, quad.camera, false );
  30223. }
  30224. }
  30225. clearColor() {
  30226. return this.clear( true, false, false );
  30227. }
  30228. clearDepth() {
  30229. return this.clear( false, true, false );
  30230. }
  30231. clearStencil() {
  30232. return this.clear( false, false, true );
  30233. }
  30234. async clearAsync( color = true, depth = true, stencil = true ) {
  30235. if ( this._initialized === false ) await this.init();
  30236. this.clear( color, depth, stencil );
  30237. }
  30238. clearColorAsync() {
  30239. return this.clearAsync( true, false, false );
  30240. }
  30241. clearDepthAsync() {
  30242. return this.clearAsync( false, true, false );
  30243. }
  30244. clearStencilAsync() {
  30245. return this.clearAsync( false, false, true );
  30246. }
  30247. get currentToneMapping() {
  30248. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  30249. }
  30250. get currentColorSpace() {
  30251. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  30252. }
  30253. dispose() {
  30254. this.info.dispose();
  30255. this.backend.dispose();
  30256. this._animation.dispose();
  30257. this._objects.dispose();
  30258. this._pipelines.dispose();
  30259. this._nodes.dispose();
  30260. this._bindings.dispose();
  30261. this._renderLists.dispose();
  30262. this._renderContexts.dispose();
  30263. this._textures.dispose();
  30264. this.setRenderTarget( null );
  30265. this.setAnimationLoop( null );
  30266. }
  30267. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  30268. this._renderTarget = renderTarget;
  30269. this._activeCubeFace = activeCubeFace;
  30270. this._activeMipmapLevel = activeMipmapLevel;
  30271. }
  30272. getRenderTarget() {
  30273. return this._renderTarget;
  30274. }
  30275. setRenderObjectFunction( renderObjectFunction ) {
  30276. this._renderObjectFunction = renderObjectFunction;
  30277. }
  30278. getRenderObjectFunction() {
  30279. return this._renderObjectFunction;
  30280. }
  30281. compute( computeNodes ) {
  30282. if ( this.isDeviceLost === true ) return;
  30283. if ( this._initialized === false ) {
  30284. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  30285. return this.computeAsync( computeNodes );
  30286. }
  30287. //
  30288. const nodeFrame = this._nodes.nodeFrame;
  30289. const previousRenderId = nodeFrame.renderId;
  30290. //
  30291. this.info.calls ++;
  30292. this.info.compute.calls ++;
  30293. this.info.compute.frameCalls ++;
  30294. nodeFrame.renderId = this.info.calls;
  30295. //
  30296. const backend = this.backend;
  30297. const pipelines = this._pipelines;
  30298. const bindings = this._bindings;
  30299. const nodes = this._nodes;
  30300. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  30301. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  30302. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  30303. }
  30304. backend.beginCompute( computeNodes );
  30305. for ( const computeNode of computeList ) {
  30306. // onInit
  30307. if ( pipelines.has( computeNode ) === false ) {
  30308. const dispose = () => {
  30309. computeNode.removeEventListener( 'dispose', dispose );
  30310. pipelines.delete( computeNode );
  30311. bindings.delete( computeNode );
  30312. nodes.delete( computeNode );
  30313. };
  30314. computeNode.addEventListener( 'dispose', dispose );
  30315. //
  30316. const onInitFn = computeNode.onInitFunction;
  30317. if ( onInitFn !== null ) {
  30318. onInitFn.call( computeNode, { renderer: this } );
  30319. }
  30320. }
  30321. nodes.updateForCompute( computeNode );
  30322. bindings.updateForCompute( computeNode );
  30323. const computeBindings = bindings.getForCompute( computeNode );
  30324. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  30325. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  30326. }
  30327. backend.finishCompute( computeNodes );
  30328. //
  30329. nodeFrame.renderId = previousRenderId;
  30330. }
  30331. async computeAsync( computeNodes ) {
  30332. if ( this._initialized === false ) await this.init();
  30333. this.compute( computeNodes );
  30334. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  30335. }
  30336. async hasFeatureAsync( name ) {
  30337. if ( this._initialized === false ) await this.init();
  30338. return this.backend.hasFeature( name );
  30339. }
  30340. hasFeature( name ) {
  30341. if ( this._initialized === false ) {
  30342. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  30343. return false;
  30344. }
  30345. return this.backend.hasFeature( name );
  30346. }
  30347. hasInitialized() {
  30348. return this._initialized;
  30349. }
  30350. async initTextureAsync( texture ) {
  30351. if ( this._initialized === false ) await this.init();
  30352. this._textures.updateTexture( texture );
  30353. }
  30354. initTexture( texture ) {
  30355. if ( this._initialized === false ) {
  30356. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  30357. return false;
  30358. }
  30359. this._textures.updateTexture( texture );
  30360. }
  30361. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  30362. if ( rectangle !== null ) {
  30363. if ( rectangle.isVector2 ) {
  30364. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  30365. } else if ( rectangle.isVector4 ) {
  30366. rectangle = _vector4.copy( rectangle ).floor();
  30367. } else {
  30368. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  30369. return;
  30370. }
  30371. } else {
  30372. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  30373. }
  30374. //
  30375. let renderContext = this._currentRenderContext;
  30376. let renderTarget;
  30377. if ( renderContext !== null ) {
  30378. renderTarget = renderContext.renderTarget;
  30379. } else {
  30380. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  30381. if ( renderTarget !== null ) {
  30382. this._textures.updateRenderTarget( renderTarget );
  30383. renderContext = this._textures.get( renderTarget );
  30384. }
  30385. }
  30386. //
  30387. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  30388. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  30389. }
  30390. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  30391. this._textures.updateTexture( srcTexture );
  30392. this._textures.updateTexture( dstTexture );
  30393. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  30394. }
  30395. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  30396. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  30397. }
  30398. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  30399. if ( object.visible === false ) return;
  30400. const visible = object.layers.test( camera.layers );
  30401. if ( visible ) {
  30402. if ( object.isGroup ) {
  30403. groupOrder = object.renderOrder;
  30404. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  30405. } else if ( object.isLOD ) {
  30406. if ( object.autoUpdate === true ) object.update( camera );
  30407. } else if ( object.isLight ) {
  30408. renderList.pushLight( object );
  30409. } else if ( object.isSprite ) {
  30410. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  30411. if ( this.sortObjects === true ) {
  30412. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  30413. }
  30414. const { geometry, material } = object;
  30415. if ( material.visible ) {
  30416. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  30417. }
  30418. }
  30419. } else if ( object.isLineLoop ) {
  30420. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  30421. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  30422. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  30423. const { geometry, material } = object;
  30424. if ( this.sortObjects === true ) {
  30425. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  30426. _vector4
  30427. .copy( geometry.boundingSphere.center )
  30428. .applyMatrix4( object.matrixWorld )
  30429. .applyMatrix4( _projScreenMatrix );
  30430. }
  30431. if ( Array.isArray( material ) ) {
  30432. const groups = geometry.groups;
  30433. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  30434. const group = groups[ i ];
  30435. const groupMaterial = material[ group.materialIndex ];
  30436. if ( groupMaterial && groupMaterial.visible ) {
  30437. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  30438. }
  30439. }
  30440. } else if ( material.visible ) {
  30441. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  30442. }
  30443. }
  30444. }
  30445. }
  30446. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  30447. const baseRenderList = renderList;
  30448. // replace render list
  30449. renderList = this._renderLists.get( object, camera );
  30450. renderList.begin();
  30451. baseRenderList.pushBundle( {
  30452. bundleGroup: object,
  30453. camera,
  30454. renderList,
  30455. } );
  30456. renderList.finish();
  30457. }
  30458. const children = object.children;
  30459. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30460. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  30461. }
  30462. }
  30463. _renderBundles( bundles, sceneRef, lightsNode ) {
  30464. for ( const bundle of bundles ) {
  30465. this._renderBundle( bundle, sceneRef, lightsNode );
  30466. }
  30467. }
  30468. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  30469. if ( doublePassList.length > 0 ) {
  30470. // render back side
  30471. for ( const { material } of doublePassList ) {
  30472. material.side = BackSide;
  30473. }
  30474. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  30475. // render front side
  30476. for ( const { material } of doublePassList ) {
  30477. material.side = FrontSide;
  30478. }
  30479. this._renderObjects( renderList, camera, scene, lightsNode );
  30480. // restore
  30481. for ( const { material } of doublePassList ) {
  30482. material.side = DoubleSide;
  30483. }
  30484. } else {
  30485. this._renderObjects( renderList, camera, scene, lightsNode );
  30486. }
  30487. }
  30488. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  30489. // process renderable objects
  30490. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  30491. const renderItem = renderList[ i ];
  30492. // @TODO: Add support for multiple materials per object. This will require to extract
  30493. // the material from the renderItem object and pass it with its group data to renderObject().
  30494. const { object, geometry, material, group, clippingContext } = renderItem;
  30495. if ( camera.isArrayCamera ) {
  30496. const cameras = camera.cameras;
  30497. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  30498. const camera2 = cameras[ j ];
  30499. if ( object.layers.test( camera2.layers ) ) {
  30500. const vp = camera2.viewport;
  30501. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  30502. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  30503. const viewportValue = this._currentRenderContext.viewportValue;
  30504. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  30505. viewportValue.minDepth = minDepth;
  30506. viewportValue.maxDepth = maxDepth;
  30507. this.backend.updateViewport( this._currentRenderContext );
  30508. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  30509. }
  30510. }
  30511. } else {
  30512. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  30513. }
  30514. }
  30515. }
  30516. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  30517. let overridePositionNode;
  30518. let overrideColorNode;
  30519. let overrideDepthNode;
  30520. //
  30521. object.onBeforeRender( this, scene, camera, geometry, material, group );
  30522. //
  30523. if ( scene.overrideMaterial !== null ) {
  30524. const overrideMaterial = scene.overrideMaterial;
  30525. if ( material.positionNode && material.positionNode.isNode ) {
  30526. overridePositionNode = overrideMaterial.positionNode;
  30527. overrideMaterial.positionNode = material.positionNode;
  30528. }
  30529. overrideMaterial.alphaTest = material.alphaTest;
  30530. overrideMaterial.alphaMap = material.alphaMap;
  30531. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  30532. if ( overrideMaterial.isShadowNodeMaterial ) {
  30533. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  30534. if ( material.depthNode && material.depthNode.isNode ) {
  30535. overrideDepthNode = overrideMaterial.depthNode;
  30536. overrideMaterial.depthNode = material.depthNode;
  30537. }
  30538. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  30539. overrideColorNode = overrideMaterial.colorNode;
  30540. overrideMaterial.colorNode = material.castShadowNode;
  30541. }
  30542. }
  30543. material = overrideMaterial;
  30544. }
  30545. //
  30546. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  30547. material.side = BackSide;
  30548. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  30549. material.side = FrontSide;
  30550. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  30551. material.side = DoubleSide;
  30552. } else {
  30553. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  30554. }
  30555. //
  30556. if ( overridePositionNode !== undefined ) {
  30557. scene.overrideMaterial.positionNode = overridePositionNode;
  30558. }
  30559. if ( overrideDepthNode !== undefined ) {
  30560. scene.overrideMaterial.depthNode = overrideDepthNode;
  30561. }
  30562. if ( overrideColorNode !== undefined ) {
  30563. scene.overrideMaterial.colorNode = overrideColorNode;
  30564. }
  30565. //
  30566. object.onAfterRender( this, scene, camera, geometry, material, group );
  30567. }
  30568. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  30569. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  30570. renderObject.drawRange = object.geometry.drawRange;
  30571. renderObject.group = group;
  30572. //
  30573. const needsRefresh = this._nodes.needsRefresh( renderObject );
  30574. if ( needsRefresh ) {
  30575. this._nodes.updateBefore( renderObject );
  30576. this._geometries.updateForRender( renderObject );
  30577. this._nodes.updateForRender( renderObject );
  30578. this._bindings.updateForRender( renderObject );
  30579. }
  30580. this._pipelines.updateForRender( renderObject );
  30581. //
  30582. if ( this._currentRenderBundle !== null ) {
  30583. const renderBundleData = this.backend.get( this._currentRenderBundle );
  30584. renderBundleData.renderObjects.push( renderObject );
  30585. renderObject.bundle = this._currentRenderBundle.scene;
  30586. }
  30587. this.backend.draw( renderObject, this.info );
  30588. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  30589. }
  30590. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  30591. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  30592. renderObject.drawRange = object.geometry.drawRange;
  30593. renderObject.group = group;
  30594. //
  30595. this._nodes.updateBefore( renderObject );
  30596. this._geometries.updateForRender( renderObject );
  30597. this._nodes.updateForRender( renderObject );
  30598. this._bindings.updateForRender( renderObject );
  30599. this._pipelines.getForRender( renderObject, this._compilationPromises );
  30600. this._nodes.updateAfter( renderObject );
  30601. }
  30602. get compile() {
  30603. return this.compileAsync;
  30604. }
  30605. }
  30606. class Binding {
  30607. constructor( name = '' ) {
  30608. this.name = name;
  30609. this.visibility = 0;
  30610. }
  30611. setVisibility( visibility ) {
  30612. this.visibility |= visibility;
  30613. }
  30614. clone() {
  30615. return Object.assign( new this.constructor(), this );
  30616. }
  30617. }
  30618. function getFloatLength( floatLength ) {
  30619. // ensure chunk size alignment (STD140 layout)
  30620. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  30621. }
  30622. class Buffer extends Binding {
  30623. constructor( name, buffer = null ) {
  30624. super( name );
  30625. this.isBuffer = true;
  30626. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  30627. this._buffer = buffer;
  30628. }
  30629. get byteLength() {
  30630. return getFloatLength( this._buffer.byteLength );
  30631. }
  30632. get buffer() {
  30633. return this._buffer;
  30634. }
  30635. update() {
  30636. return true;
  30637. }
  30638. }
  30639. class UniformBuffer extends Buffer {
  30640. constructor( name, buffer = null ) {
  30641. super( name, buffer );
  30642. this.isUniformBuffer = true;
  30643. }
  30644. }
  30645. let _id$4 = 0;
  30646. class NodeUniformBuffer extends UniformBuffer {
  30647. constructor( nodeUniform, groupNode ) {
  30648. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  30649. this.nodeUniform = nodeUniform;
  30650. this.groupNode = groupNode;
  30651. }
  30652. get buffer() {
  30653. return this.nodeUniform.value;
  30654. }
  30655. }
  30656. class UniformsGroup extends UniformBuffer {
  30657. constructor( name ) {
  30658. super( name );
  30659. this.isUniformsGroup = true;
  30660. this._values = null;
  30661. // the order of uniforms in this array must match the order of uniforms in the shader
  30662. this.uniforms = [];
  30663. }
  30664. addUniform( uniform ) {
  30665. this.uniforms.push( uniform );
  30666. return this;
  30667. }
  30668. removeUniform( uniform ) {
  30669. const index = this.uniforms.indexOf( uniform );
  30670. if ( index !== - 1 ) {
  30671. this.uniforms.splice( index, 1 );
  30672. }
  30673. return this;
  30674. }
  30675. get values() {
  30676. if ( this._values === null ) {
  30677. this._values = Array.from( this.buffer );
  30678. }
  30679. return this._values;
  30680. }
  30681. get buffer() {
  30682. let buffer = this._buffer;
  30683. if ( buffer === null ) {
  30684. const byteLength = this.byteLength;
  30685. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  30686. this._buffer = buffer;
  30687. }
  30688. return buffer;
  30689. }
  30690. get byteLength() {
  30691. let offset = 0; // global buffer offset in bytes
  30692. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  30693. const uniform = this.uniforms[ i ];
  30694. const { boundary, itemSize } = uniform;
  30695. // offset within a single chunk in bytes
  30696. const chunkOffset = offset % GPU_CHUNK_BYTES;
  30697. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  30698. // conformance tests
  30699. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  30700. // check for chunk overflow
  30701. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  30702. } else if ( chunkOffset % boundary !== 0 ) {
  30703. // check for correct alignment
  30704. offset += ( chunkOffset % boundary );
  30705. }
  30706. uniform.offset = ( offset / this.bytesPerElement );
  30707. offset += ( itemSize * this.bytesPerElement );
  30708. }
  30709. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  30710. }
  30711. update() {
  30712. let updated = false;
  30713. for ( const uniform of this.uniforms ) {
  30714. if ( this.updateByType( uniform ) === true ) {
  30715. updated = true;
  30716. }
  30717. }
  30718. return updated;
  30719. }
  30720. updateByType( uniform ) {
  30721. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  30722. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  30723. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  30724. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  30725. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  30726. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  30727. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  30728. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  30729. }
  30730. updateNumber( uniform ) {
  30731. let updated = false;
  30732. const a = this.values;
  30733. const v = uniform.getValue();
  30734. const offset = uniform.offset;
  30735. const type = uniform.getType();
  30736. if ( a[ offset ] !== v ) {
  30737. const b = this._getBufferForType( type );
  30738. b[ offset ] = a[ offset ] = v;
  30739. updated = true;
  30740. }
  30741. return updated;
  30742. }
  30743. updateVector2( uniform ) {
  30744. let updated = false;
  30745. const a = this.values;
  30746. const v = uniform.getValue();
  30747. const offset = uniform.offset;
  30748. const type = uniform.getType();
  30749. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  30750. const b = this._getBufferForType( type );
  30751. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  30752. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  30753. updated = true;
  30754. }
  30755. return updated;
  30756. }
  30757. updateVector3( uniform ) {
  30758. let updated = false;
  30759. const a = this.values;
  30760. const v = uniform.getValue();
  30761. const offset = uniform.offset;
  30762. const type = uniform.getType();
  30763. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  30764. const b = this._getBufferForType( type );
  30765. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  30766. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  30767. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  30768. updated = true;
  30769. }
  30770. return updated;
  30771. }
  30772. updateVector4( uniform ) {
  30773. let updated = false;
  30774. const a = this.values;
  30775. const v = uniform.getValue();
  30776. const offset = uniform.offset;
  30777. const type = uniform.getType();
  30778. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  30779. const b = this._getBufferForType( type );
  30780. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  30781. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  30782. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  30783. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  30784. updated = true;
  30785. }
  30786. return updated;
  30787. }
  30788. updateColor( uniform ) {
  30789. let updated = false;
  30790. const a = this.values;
  30791. const c = uniform.getValue();
  30792. const offset = uniform.offset;
  30793. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  30794. const b = this.buffer;
  30795. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  30796. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  30797. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  30798. updated = true;
  30799. }
  30800. return updated;
  30801. }
  30802. updateMatrix3( uniform ) {
  30803. let updated = false;
  30804. const a = this.values;
  30805. const e = uniform.getValue().elements;
  30806. const offset = uniform.offset;
  30807. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  30808. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  30809. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  30810. const b = this.buffer;
  30811. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  30812. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  30813. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  30814. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  30815. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  30816. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  30817. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  30818. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  30819. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  30820. updated = true;
  30821. }
  30822. return updated;
  30823. }
  30824. updateMatrix4( uniform ) {
  30825. let updated = false;
  30826. const a = this.values;
  30827. const e = uniform.getValue().elements;
  30828. const offset = uniform.offset;
  30829. if ( arraysEqual( a, e, offset ) === false ) {
  30830. const b = this.buffer;
  30831. b.set( e, offset );
  30832. setArray( a, e, offset );
  30833. updated = true;
  30834. }
  30835. return updated;
  30836. }
  30837. _getBufferForType( type ) {
  30838. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  30839. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  30840. return this.buffer;
  30841. }
  30842. }
  30843. function setArray( a, b, offset ) {
  30844. for ( let i = 0, l = b.length; i < l; i ++ ) {
  30845. a[ offset + i ] = b[ i ];
  30846. }
  30847. }
  30848. function arraysEqual( a, b, offset ) {
  30849. for ( let i = 0, l = b.length; i < l; i ++ ) {
  30850. if ( a[ offset + i ] !== b[ i ] ) return false;
  30851. }
  30852. return true;
  30853. }
  30854. let _id$3 = 0;
  30855. class NodeUniformsGroup extends UniformsGroup {
  30856. constructor( name, groupNode ) {
  30857. super( name );
  30858. this.id = _id$3 ++;
  30859. this.groupNode = groupNode;
  30860. this.isNodeUniformsGroup = true;
  30861. }
  30862. getNodes() {
  30863. const nodes = [];
  30864. for ( const uniform of this.uniforms ) {
  30865. const node = uniform.nodeUniform.node;
  30866. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  30867. nodes.push( node );
  30868. }
  30869. return nodes;
  30870. }
  30871. }
  30872. let _id$2 = 0;
  30873. class SampledTexture extends Binding {
  30874. constructor( name, texture ) {
  30875. super( name );
  30876. this.id = _id$2 ++;
  30877. this.texture = texture;
  30878. this.version = texture ? texture.version : 0;
  30879. this.store = false;
  30880. this.generation = null;
  30881. this.isSampledTexture = true;
  30882. }
  30883. needsBindingsUpdate( generation ) {
  30884. const { texture } = this;
  30885. if ( generation !== this.generation ) {
  30886. this.generation = generation;
  30887. return true;
  30888. }
  30889. return texture.isVideoTexture;
  30890. }
  30891. update() {
  30892. const { texture, version } = this;
  30893. if ( version !== texture.version ) {
  30894. this.version = texture.version;
  30895. return true;
  30896. }
  30897. return false;
  30898. }
  30899. }
  30900. class NodeSampledTexture extends SampledTexture {
  30901. constructor( name, textureNode, groupNode, access = null ) {
  30902. super( name, textureNode ? textureNode.value : null );
  30903. this.textureNode = textureNode;
  30904. this.groupNode = groupNode;
  30905. this.access = access;
  30906. }
  30907. needsBindingsUpdate( generation ) {
  30908. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  30909. }
  30910. update() {
  30911. const { textureNode } = this;
  30912. if ( this.texture !== textureNode.value ) {
  30913. this.texture = textureNode.value;
  30914. return true;
  30915. }
  30916. return super.update();
  30917. }
  30918. }
  30919. class NodeSampledCubeTexture extends NodeSampledTexture {
  30920. constructor( name, textureNode, groupNode, access ) {
  30921. super( name, textureNode, groupNode, access );
  30922. this.isSampledCubeTexture = true;
  30923. }
  30924. }
  30925. class NodeSampledTexture3D extends NodeSampledTexture {
  30926. constructor( name, textureNode, groupNode, access ) {
  30927. super( name, textureNode, groupNode, access );
  30928. this.isSampledTexture3D = true;
  30929. }
  30930. }
  30931. const glslMethods = {
  30932. textureDimensions: 'textureSize',
  30933. equals: 'equal'
  30934. };
  30935. const precisionLib = {
  30936. low: 'lowp',
  30937. medium: 'mediump',
  30938. high: 'highp'
  30939. };
  30940. const supports$1 = {
  30941. swizzleAssign: true,
  30942. storageBuffer: false
  30943. };
  30944. const defaultPrecisions = `
  30945. precision highp float;
  30946. precision highp int;
  30947. precision highp sampler2D;
  30948. precision highp sampler3D;
  30949. precision highp samplerCube;
  30950. precision highp sampler2DArray;
  30951. precision highp usampler2D;
  30952. precision highp usampler3D;
  30953. precision highp usamplerCube;
  30954. precision highp usampler2DArray;
  30955. precision highp isampler2D;
  30956. precision highp isampler3D;
  30957. precision highp isamplerCube;
  30958. precision highp isampler2DArray;
  30959. precision lowp sampler2DShadow;
  30960. `;
  30961. class GLSLNodeBuilder extends NodeBuilder {
  30962. constructor( object, renderer ) {
  30963. super( object, renderer, new GLSLNodeParser() );
  30964. this.uniformGroups = {};
  30965. this.transforms = [];
  30966. this.extensions = {};
  30967. this.builtins = { vertex: [], fragment: [], compute: [] };
  30968. this.useComparisonMethod = true;
  30969. }
  30970. needsToWorkingColorSpace( texture ) {
  30971. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  30972. }
  30973. getMethod( method ) {
  30974. return glslMethods[ method ] || method;
  30975. }
  30976. getOutputStructName() {
  30977. return '';
  30978. }
  30979. buildFunctionCode( shaderNode ) {
  30980. const layout = shaderNode.layout;
  30981. const flowData = this.flowShaderNode( shaderNode );
  30982. const parameters = [];
  30983. for ( const input of layout.inputs ) {
  30984. parameters.push( this.getType( input.type ) + ' ' + input.name );
  30985. }
  30986. //
  30987. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  30988. ${ flowData.vars }
  30989. ${ flowData.code }
  30990. return ${ flowData.result };
  30991. }`;
  30992. //
  30993. return code;
  30994. }
  30995. setupPBO( storageBufferNode ) {
  30996. const attribute = storageBufferNode.value;
  30997. if ( attribute.pbo === undefined ) {
  30998. const originalArray = attribute.array;
  30999. const numElements = attribute.count * attribute.itemSize;
  31000. const { itemSize } = attribute;
  31001. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  31002. let format = isInteger ? RedIntegerFormat : RedFormat;
  31003. if ( itemSize === 2 ) {
  31004. format = isInteger ? RGIntegerFormat : RGFormat;
  31005. } else if ( itemSize === 3 ) {
  31006. format = isInteger ? RGBIntegerFormat : RGBFormat;
  31007. } else if ( itemSize === 4 ) {
  31008. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  31009. }
  31010. const typeMap = {
  31011. Float32Array: FloatType,
  31012. Uint8Array: UnsignedByteType,
  31013. Uint16Array: UnsignedShortType,
  31014. Uint32Array: UnsignedIntType,
  31015. Int8Array: ByteType,
  31016. Int16Array: ShortType,
  31017. Int32Array: IntType,
  31018. Uint8ClampedArray: UnsignedByteType,
  31019. };
  31020. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  31021. let height = Math.ceil( ( numElements / itemSize ) / width );
  31022. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  31023. const newSize = width * height * itemSize;
  31024. const newArray = new originalArray.constructor( newSize );
  31025. newArray.set( originalArray, 0 );
  31026. attribute.array = newArray;
  31027. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  31028. pboTexture.needsUpdate = true;
  31029. pboTexture.isPBOTexture = true;
  31030. const pbo = new TextureNode( pboTexture, null, null );
  31031. pbo.setPrecision( 'high' );
  31032. attribute.pboNode = pbo;
  31033. attribute.pbo = pbo.value;
  31034. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  31035. }
  31036. }
  31037. getPropertyName( node, shaderStage = this.shaderStage ) {
  31038. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  31039. return shaderStage.charAt( 0 ) + '_' + node.name;
  31040. }
  31041. return super.getPropertyName( node, shaderStage );
  31042. }
  31043. generatePBO( storageArrayElementNode ) {
  31044. const { node, indexNode } = storageArrayElementNode;
  31045. const attribute = node.value;
  31046. if ( this.renderer.backend.has( attribute ) ) {
  31047. const attributeData = this.renderer.backend.get( attribute );
  31048. attributeData.pbo = attribute.pbo;
  31049. }
  31050. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  31051. const textureName = this.getPropertyName( nodeUniform );
  31052. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  31053. const indexSnippet = indexNode.build( this, 'uint' );
  31054. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  31055. let propertyName = elementNodeData.propertyName;
  31056. if ( propertyName === undefined ) {
  31057. // property element
  31058. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  31059. propertyName = this.getPropertyName( nodeVar );
  31060. // property size
  31061. const bufferNodeData = this.getDataFromNode( node );
  31062. let propertySizeName = bufferNodeData.propertySizeName;
  31063. if ( propertySizeName === undefined ) {
  31064. propertySizeName = propertyName + 'Size';
  31065. this.getVarFromNode( node, propertySizeName, 'uint' );
  31066. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  31067. bufferNodeData.propertySizeName = propertySizeName;
  31068. }
  31069. //
  31070. const { itemSize } = attribute;
  31071. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  31072. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  31073. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  31074. //
  31075. let prefix = 'vec4';
  31076. if ( attribute.pbo.type === UnsignedIntType ) {
  31077. prefix = 'uvec4';
  31078. } else if ( attribute.pbo.type === IntType ) {
  31079. prefix = 'ivec4';
  31080. }
  31081. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  31082. elementNodeData.propertyName = propertyName;
  31083. }
  31084. return propertyName;
  31085. }
  31086. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  31087. if ( depthSnippet ) {
  31088. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  31089. } else {
  31090. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  31091. }
  31092. }
  31093. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  31094. if ( texture.isDepthTexture ) {
  31095. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  31096. } else {
  31097. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  31098. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  31099. }
  31100. }
  31101. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  31102. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  31103. }
  31104. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  31105. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  31106. }
  31107. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  31108. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  31109. }
  31110. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  31111. if ( shaderStage === 'fragment' ) {
  31112. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  31113. } else {
  31114. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  31115. }
  31116. }
  31117. getVars( shaderStage ) {
  31118. const snippets = [];
  31119. const vars = this.vars[ shaderStage ];
  31120. if ( vars !== undefined ) {
  31121. for ( const variable of vars ) {
  31122. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  31123. }
  31124. }
  31125. return snippets.join( '\n\t' );
  31126. }
  31127. getUniforms( shaderStage ) {
  31128. const uniforms = this.uniforms[ shaderStage ];
  31129. const bindingSnippets = [];
  31130. const uniformGroups = {};
  31131. for ( const uniform of uniforms ) {
  31132. let snippet = null;
  31133. let group = false;
  31134. if ( uniform.type === 'texture' ) {
  31135. const texture = uniform.node.value;
  31136. let typePrefix = '';
  31137. if ( texture.isDataTexture === true ) {
  31138. if ( texture.type === UnsignedIntType ) {
  31139. typePrefix = 'u';
  31140. } else if ( texture.type === IntType ) {
  31141. typePrefix = 'i';
  31142. }
  31143. }
  31144. if ( texture.compareFunction ) {
  31145. snippet = `sampler2DShadow ${ uniform.name };`;
  31146. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  31147. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  31148. } else {
  31149. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  31150. }
  31151. } else if ( uniform.type === 'cubeTexture' ) {
  31152. snippet = `samplerCube ${ uniform.name };`;
  31153. } else if ( uniform.type === 'texture3D' ) {
  31154. snippet = `sampler3D ${ uniform.name };`;
  31155. } else if ( uniform.type === 'buffer' ) {
  31156. const bufferNode = uniform.node;
  31157. const bufferType = this.getType( bufferNode.bufferType );
  31158. const bufferCount = bufferNode.bufferCount;
  31159. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  31160. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  31161. } else {
  31162. const vectorType = this.getVectorType( uniform.type );
  31163. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  31164. group = true;
  31165. }
  31166. const precision = uniform.node.precision;
  31167. if ( precision !== null ) {
  31168. snippet = precisionLib[ precision ] + ' ' + snippet;
  31169. }
  31170. if ( group ) {
  31171. snippet = '\t' + snippet;
  31172. const groupName = uniform.groupNode.name;
  31173. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  31174. groupSnippets.push( snippet );
  31175. } else {
  31176. snippet = 'uniform ' + snippet;
  31177. bindingSnippets.push( snippet );
  31178. }
  31179. }
  31180. let output = '';
  31181. for ( const name in uniformGroups ) {
  31182. const groupSnippets = uniformGroups[ name ];
  31183. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  31184. }
  31185. output += bindingSnippets.join( '\n' );
  31186. return output;
  31187. }
  31188. getTypeFromAttribute( attribute ) {
  31189. let nodeType = super.getTypeFromAttribute( attribute );
  31190. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  31191. let dataAttribute = attribute;
  31192. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31193. const array = dataAttribute.array;
  31194. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  31195. nodeType = nodeType.slice( 1 );
  31196. }
  31197. }
  31198. return nodeType;
  31199. }
  31200. getAttributes( shaderStage ) {
  31201. let snippet = '';
  31202. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  31203. const attributes = this.getAttributesArray();
  31204. let location = 0;
  31205. for ( const attribute of attributes ) {
  31206. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  31207. }
  31208. }
  31209. return snippet;
  31210. }
  31211. getStructMembers( struct ) {
  31212. const snippets = [];
  31213. const members = struct.getMemberTypes();
  31214. for ( let i = 0; i < members.length; i ++ ) {
  31215. const member = members[ i ];
  31216. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  31217. }
  31218. return snippets.join( '\n' );
  31219. }
  31220. getStructs( shaderStage ) {
  31221. const snippets = [];
  31222. const structs = this.structs[ shaderStage ];
  31223. if ( structs.length === 0 ) {
  31224. return 'layout( location = 0 ) out vec4 fragColor;\n';
  31225. }
  31226. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  31227. const struct = structs[ index ];
  31228. let snippet = '\n';
  31229. snippet += this.getStructMembers( struct );
  31230. snippet += '\n';
  31231. snippets.push( snippet );
  31232. }
  31233. return snippets.join( '\n\n' );
  31234. }
  31235. getVaryings( shaderStage ) {
  31236. let snippet = '';
  31237. const varyings = this.varyings;
  31238. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  31239. for ( const varying of varyings ) {
  31240. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  31241. const type = this.getType( varying.type );
  31242. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  31243. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  31244. }
  31245. } else if ( shaderStage === 'fragment' ) {
  31246. for ( const varying of varyings ) {
  31247. if ( varying.needsInterpolation ) {
  31248. const type = this.getType( varying.type );
  31249. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  31250. snippet += `${flat}in ${type} ${varying.name};\n`;
  31251. }
  31252. }
  31253. }
  31254. for ( const builtin of this.builtins[ shaderStage ] ) {
  31255. snippet += `${builtin};\n`;
  31256. }
  31257. return snippet;
  31258. }
  31259. getVertexIndex() {
  31260. return 'uint( gl_VertexID )';
  31261. }
  31262. getInstanceIndex() {
  31263. return 'uint( gl_InstanceID )';
  31264. }
  31265. getInvocationLocalIndex() {
  31266. const workgroupSize = this.object.workgroupSize;
  31267. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  31268. return `uint( gl_InstanceID ) % ${size}u`;
  31269. }
  31270. getDrawIndex() {
  31271. const extensions = this.renderer.backend.extensions;
  31272. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  31273. return 'uint( gl_DrawID )';
  31274. }
  31275. return null;
  31276. }
  31277. getFrontFacing() {
  31278. return 'gl_FrontFacing';
  31279. }
  31280. getFragCoord() {
  31281. return 'gl_FragCoord.xy';
  31282. }
  31283. getFragDepth() {
  31284. return 'gl_FragDepth';
  31285. }
  31286. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  31287. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  31288. if ( map.has( name ) === false ) {
  31289. map.set( name, {
  31290. name,
  31291. behavior
  31292. } );
  31293. }
  31294. }
  31295. getExtensions( shaderStage ) {
  31296. const snippets = [];
  31297. if ( shaderStage === 'vertex' ) {
  31298. const ext = this.renderer.backend.extensions;
  31299. const isBatchedMesh = this.object.isBatchedMesh;
  31300. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  31301. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  31302. }
  31303. }
  31304. const extensions = this.extensions[ shaderStage ];
  31305. if ( extensions !== undefined ) {
  31306. for ( const { name, behavior } of extensions.values() ) {
  31307. snippets.push( `#extension ${name} : ${behavior}` );
  31308. }
  31309. }
  31310. return snippets.join( '\n' );
  31311. }
  31312. getClipDistance() {
  31313. return 'gl_ClipDistance';
  31314. }
  31315. isAvailable( name ) {
  31316. let result = supports$1[ name ];
  31317. if ( result === undefined ) {
  31318. let extensionName;
  31319. result = false;
  31320. switch ( name ) {
  31321. case 'float32Filterable':
  31322. extensionName = 'OES_texture_float_linear';
  31323. break;
  31324. case 'clipDistance':
  31325. extensionName = 'WEBGL_clip_cull_distance';
  31326. break;
  31327. }
  31328. if ( extensionName !== undefined ) {
  31329. const extensions = this.renderer.backend.extensions;
  31330. if ( extensions.has( extensionName ) ) {
  31331. extensions.get( extensionName );
  31332. result = true;
  31333. }
  31334. }
  31335. supports$1[ name ] = result;
  31336. }
  31337. return result;
  31338. }
  31339. isFlipY() {
  31340. return true;
  31341. }
  31342. enableHardwareClipping( planeCount ) {
  31343. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  31344. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  31345. }
  31346. registerTransform( varyingName, attributeNode ) {
  31347. this.transforms.push( { varyingName, attributeNode } );
  31348. }
  31349. getTransforms( /* shaderStage */ ) {
  31350. const transforms = this.transforms;
  31351. let snippet = '';
  31352. for ( let i = 0; i < transforms.length; i ++ ) {
  31353. const transform = transforms[ i ];
  31354. const attributeName = this.getPropertyName( transform.attributeNode );
  31355. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  31356. }
  31357. return snippet;
  31358. }
  31359. _getGLSLUniformStruct( name, vars ) {
  31360. return `
  31361. layout( std140 ) uniform ${name} {
  31362. ${vars}
  31363. };`;
  31364. }
  31365. _getGLSLVertexCode( shaderData ) {
  31366. return `#version 300 es
  31367. ${ this.getSignature() }
  31368. // extensions
  31369. ${shaderData.extensions}
  31370. // precision
  31371. ${ defaultPrecisions }
  31372. // uniforms
  31373. ${shaderData.uniforms}
  31374. // varyings
  31375. ${shaderData.varyings}
  31376. // attributes
  31377. ${shaderData.attributes}
  31378. // codes
  31379. ${shaderData.codes}
  31380. void main() {
  31381. // vars
  31382. ${shaderData.vars}
  31383. // transforms
  31384. ${shaderData.transforms}
  31385. // flow
  31386. ${shaderData.flow}
  31387. gl_PointSize = 1.0;
  31388. }
  31389. `;
  31390. }
  31391. _getGLSLFragmentCode( shaderData ) {
  31392. return `#version 300 es
  31393. ${ this.getSignature() }
  31394. // precision
  31395. ${ defaultPrecisions }
  31396. // uniforms
  31397. ${shaderData.uniforms}
  31398. // varyings
  31399. ${shaderData.varyings}
  31400. // codes
  31401. ${shaderData.codes}
  31402. ${shaderData.structs}
  31403. void main() {
  31404. // vars
  31405. ${shaderData.vars}
  31406. // flow
  31407. ${shaderData.flow}
  31408. }
  31409. `;
  31410. }
  31411. buildCode() {
  31412. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  31413. this.sortBindingGroups();
  31414. for ( const shaderStage in shadersData ) {
  31415. let flow = '// code\n\n';
  31416. flow += this.flowCode[ shaderStage ];
  31417. const flowNodes = this.flowNodes[ shaderStage ];
  31418. const mainNode = flowNodes[ flowNodes.length - 1 ];
  31419. for ( const node of flowNodes ) {
  31420. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  31421. const slotName = node.name;
  31422. if ( slotName ) {
  31423. if ( flow.length > 0 ) flow += '\n';
  31424. flow += `\t// flow -> ${ slotName }\n\t`;
  31425. }
  31426. flow += `${ flowSlotData.code }\n\t`;
  31427. if ( node === mainNode && shaderStage !== 'compute' ) {
  31428. flow += '// result\n\t';
  31429. if ( shaderStage === 'vertex' ) {
  31430. flow += 'gl_Position = ';
  31431. flow += `${ flowSlotData.result };`;
  31432. } else if ( shaderStage === 'fragment' ) {
  31433. if ( ! node.outputNode.isOutputStructNode ) {
  31434. flow += 'fragColor = ';
  31435. flow += `${ flowSlotData.result };`;
  31436. }
  31437. }
  31438. }
  31439. }
  31440. const stageData = shadersData[ shaderStage ];
  31441. stageData.extensions = this.getExtensions( shaderStage );
  31442. stageData.uniforms = this.getUniforms( shaderStage );
  31443. stageData.attributes = this.getAttributes( shaderStage );
  31444. stageData.varyings = this.getVaryings( shaderStage );
  31445. stageData.vars = this.getVars( shaderStage );
  31446. stageData.structs = this.getStructs( shaderStage );
  31447. stageData.codes = this.getCodes( shaderStage );
  31448. stageData.transforms = this.getTransforms( shaderStage );
  31449. stageData.flow = flow;
  31450. }
  31451. if ( this.material !== null ) {
  31452. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  31453. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  31454. } else {
  31455. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  31456. }
  31457. }
  31458. getUniformFromNode( node, type, shaderStage, name = null ) {
  31459. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  31460. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31461. let uniformGPU = nodeData.uniformGPU;
  31462. if ( uniformGPU === undefined ) {
  31463. const group = node.groupNode;
  31464. const groupName = group.name;
  31465. const bindings = this.getBindGroupArray( groupName, shaderStage );
  31466. if ( type === 'texture' ) {
  31467. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  31468. bindings.push( uniformGPU );
  31469. } else if ( type === 'cubeTexture' ) {
  31470. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  31471. bindings.push( uniformGPU );
  31472. } else if ( type === 'texture3D' ) {
  31473. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  31474. bindings.push( uniformGPU );
  31475. } else if ( type === 'buffer' ) {
  31476. node.name = `NodeBuffer_${ node.id }`;
  31477. uniformNode.name = `buffer${ node.id }`;
  31478. const buffer = new NodeUniformBuffer( node, group );
  31479. buffer.name = node.name;
  31480. bindings.push( buffer );
  31481. uniformGPU = buffer;
  31482. } else {
  31483. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  31484. let uniformsGroup = uniformsStage[ groupName ];
  31485. if ( uniformsGroup === undefined ) {
  31486. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  31487. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  31488. uniformsStage[ groupName ] = uniformsGroup;
  31489. bindings.push( uniformsGroup );
  31490. }
  31491. uniformGPU = this.getNodeUniform( uniformNode, type );
  31492. uniformsGroup.addUniform( uniformGPU );
  31493. }
  31494. nodeData.uniformGPU = uniformGPU;
  31495. }
  31496. return uniformNode;
  31497. }
  31498. }
  31499. let vector2 = null;
  31500. let vector4 = null;
  31501. let color4 = null;
  31502. class Backend {
  31503. constructor( parameters = {} ) {
  31504. this.parameters = Object.assign( {}, parameters );
  31505. this.data = new WeakMap();
  31506. this.renderer = null;
  31507. this.domElement = null;
  31508. }
  31509. async init( renderer ) {
  31510. this.renderer = renderer;
  31511. }
  31512. // render context
  31513. begin( /*renderContext*/ ) { }
  31514. finish( /*renderContext*/ ) { }
  31515. // render object
  31516. draw( /*renderObject, info*/ ) { }
  31517. // program
  31518. createProgram( /*program*/ ) { }
  31519. destroyProgram( /*program*/ ) { }
  31520. // bindings
  31521. createBindings( /*bingGroup, bindings*/ ) { }
  31522. updateBindings( /*bingGroup, bindings*/ ) { }
  31523. // pipeline
  31524. createRenderPipeline( /*renderObject*/ ) { }
  31525. createComputePipeline( /*computeNode, pipeline*/ ) { }
  31526. destroyPipeline( /*pipeline*/ ) { }
  31527. // cache key
  31528. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  31529. getRenderCacheKey( /*renderObject*/ ) { } // return String
  31530. // node builder
  31531. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  31532. // textures
  31533. createSampler( /*texture*/ ) { }
  31534. createDefaultTexture( /*texture*/ ) { }
  31535. createTexture( /*texture*/ ) { }
  31536. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  31537. // attributes
  31538. createAttribute( /*attribute*/ ) { }
  31539. createIndexAttribute( /*attribute*/ ) { }
  31540. updateAttribute( /*attribute*/ ) { }
  31541. destroyAttribute( /*attribute*/ ) { }
  31542. // canvas
  31543. getContext() { }
  31544. updateSize() { }
  31545. // utils
  31546. resolveTimestampAsync( /*renderContext, type*/ ) { }
  31547. hasFeatureAsync( /*name*/ ) { } // return Boolean
  31548. hasFeature( /*name*/ ) { } // return Boolean
  31549. getInstanceCount( renderObject ) {
  31550. const { object, geometry } = renderObject;
  31551. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  31552. }
  31553. getDrawingBufferSize() {
  31554. vector2 = vector2 || new Vector2();
  31555. return this.renderer.getDrawingBufferSize( vector2 );
  31556. }
  31557. getScissor() {
  31558. vector4 = vector4 || new Vector4();
  31559. return this.renderer.getScissor( vector4 );
  31560. }
  31561. setScissorTest( /*boolean*/ ) { }
  31562. getClearColor() {
  31563. const renderer = this.renderer;
  31564. color4 = color4 || new Color4();
  31565. renderer.getClearColor( color4 );
  31566. color4.getRGB( color4, this.renderer.currentColorSpace );
  31567. return color4;
  31568. }
  31569. getDomElement() {
  31570. let domElement = this.domElement;
  31571. if ( domElement === null ) {
  31572. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  31573. // OffscreenCanvas does not have setAttribute, see #22811
  31574. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  31575. this.domElement = domElement;
  31576. }
  31577. return domElement;
  31578. }
  31579. // resource properties
  31580. set( object, value ) {
  31581. this.data.set( object, value );
  31582. }
  31583. get( object ) {
  31584. let map = this.data.get( object );
  31585. if ( map === undefined ) {
  31586. map = {};
  31587. this.data.set( object, map );
  31588. }
  31589. return map;
  31590. }
  31591. has( object ) {
  31592. return this.data.has( object );
  31593. }
  31594. delete( object ) {
  31595. this.data.delete( object );
  31596. }
  31597. dispose() { }
  31598. }
  31599. let _id$1 = 0;
  31600. class DualAttributeData {
  31601. constructor( attributeData, dualBuffer ) {
  31602. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  31603. this.type = attributeData.type;
  31604. this.bufferType = attributeData.bufferType;
  31605. this.pbo = attributeData.pbo;
  31606. this.byteLength = attributeData.byteLength;
  31607. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  31608. this.version = attributeData.version;
  31609. this.isInteger = attributeData.isInteger;
  31610. this.activeBufferIndex = 0;
  31611. this.baseId = attributeData.id;
  31612. }
  31613. get id() {
  31614. return `${ this.baseId }|${ this.activeBufferIndex }`;
  31615. }
  31616. get bufferGPU() {
  31617. return this.buffers[ this.activeBufferIndex ];
  31618. }
  31619. get transformBuffer() {
  31620. return this.buffers[ this.activeBufferIndex ^ 1 ];
  31621. }
  31622. switchBuffers() {
  31623. this.activeBufferIndex ^= 1;
  31624. }
  31625. }
  31626. class WebGLAttributeUtils {
  31627. constructor( backend ) {
  31628. this.backend = backend;
  31629. }
  31630. createAttribute( attribute, bufferType ) {
  31631. const backend = this.backend;
  31632. const { gl } = backend;
  31633. const array = attribute.array;
  31634. const usage = attribute.usage || gl.STATIC_DRAW;
  31635. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  31636. const bufferData = backend.get( bufferAttribute );
  31637. let bufferGPU = bufferData.bufferGPU;
  31638. if ( bufferGPU === undefined ) {
  31639. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  31640. bufferData.bufferGPU = bufferGPU;
  31641. bufferData.bufferType = bufferType;
  31642. bufferData.version = bufferAttribute.version;
  31643. }
  31644. //attribute.onUploadCallback();
  31645. let type;
  31646. if ( array instanceof Float32Array ) {
  31647. type = gl.FLOAT;
  31648. } else if ( array instanceof Uint16Array ) {
  31649. if ( attribute.isFloat16BufferAttribute ) {
  31650. type = gl.HALF_FLOAT;
  31651. } else {
  31652. type = gl.UNSIGNED_SHORT;
  31653. }
  31654. } else if ( array instanceof Int16Array ) {
  31655. type = gl.SHORT;
  31656. } else if ( array instanceof Uint32Array ) {
  31657. type = gl.UNSIGNED_INT;
  31658. } else if ( array instanceof Int32Array ) {
  31659. type = gl.INT;
  31660. } else if ( array instanceof Int8Array ) {
  31661. type = gl.BYTE;
  31662. } else if ( array instanceof Uint8Array ) {
  31663. type = gl.UNSIGNED_BYTE;
  31664. } else if ( array instanceof Uint8ClampedArray ) {
  31665. type = gl.UNSIGNED_BYTE;
  31666. } else {
  31667. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  31668. }
  31669. let attributeData = {
  31670. bufferGPU,
  31671. bufferType,
  31672. type,
  31673. byteLength: array.byteLength,
  31674. bytesPerElement: array.BYTES_PER_ELEMENT,
  31675. version: attribute.version,
  31676. pbo: attribute.pbo,
  31677. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  31678. id: _id$1 ++
  31679. };
  31680. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  31681. // create buffer for transform feedback use
  31682. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  31683. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  31684. }
  31685. backend.set( attribute, attributeData );
  31686. }
  31687. updateAttribute( attribute ) {
  31688. const backend = this.backend;
  31689. const { gl } = backend;
  31690. const array = attribute.array;
  31691. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  31692. const bufferData = backend.get( bufferAttribute );
  31693. const bufferType = bufferData.bufferType;
  31694. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  31695. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  31696. if ( updateRanges.length === 0 ) {
  31697. // Not using update ranges
  31698. gl.bufferSubData( bufferType, 0, array );
  31699. } else {
  31700. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  31701. const range = updateRanges[ i ];
  31702. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  31703. array, range.start, range.count );
  31704. }
  31705. bufferAttribute.clearUpdateRanges();
  31706. }
  31707. gl.bindBuffer( bufferType, null );
  31708. bufferData.version = bufferAttribute.version;
  31709. }
  31710. destroyAttribute( attribute ) {
  31711. const backend = this.backend;
  31712. const { gl } = backend;
  31713. if ( attribute.isInterleavedBufferAttribute ) {
  31714. backend.delete( attribute.data );
  31715. }
  31716. const attributeData = backend.get( attribute );
  31717. gl.deleteBuffer( attributeData.bufferGPU );
  31718. backend.delete( attribute );
  31719. }
  31720. async getArrayBufferAsync( attribute ) {
  31721. const backend = this.backend;
  31722. const { gl } = backend;
  31723. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  31724. const { bufferGPU } = backend.get( bufferAttribute );
  31725. const array = attribute.array;
  31726. const byteLength = array.byteLength;
  31727. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  31728. const writeBuffer = gl.createBuffer();
  31729. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  31730. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  31731. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  31732. await backend.utils._clientWaitAsync();
  31733. const dstBuffer = new attribute.array.constructor( array.length );
  31734. // Ensure the buffer is bound before reading
  31735. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  31736. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  31737. gl.deleteBuffer( writeBuffer );
  31738. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  31739. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  31740. return dstBuffer.buffer;
  31741. }
  31742. _createBuffer( gl, bufferType, array, usage ) {
  31743. const bufferGPU = gl.createBuffer();
  31744. gl.bindBuffer( bufferType, bufferGPU );
  31745. gl.bufferData( bufferType, array, usage );
  31746. gl.bindBuffer( bufferType, null );
  31747. return bufferGPU;
  31748. }
  31749. }
  31750. let initialized$1 = false, equationToGL, factorToGL;
  31751. class WebGLState {
  31752. constructor( backend ) {
  31753. this.backend = backend;
  31754. this.gl = this.backend.gl;
  31755. this.enabled = {};
  31756. this.currentFlipSided = null;
  31757. this.currentCullFace = null;
  31758. this.currentProgram = null;
  31759. this.currentBlendingEnabled = false;
  31760. this.currentBlending = null;
  31761. this.currentBlendSrc = null;
  31762. this.currentBlendDst = null;
  31763. this.currentBlendSrcAlpha = null;
  31764. this.currentBlendDstAlpha = null;
  31765. this.currentPremultipledAlpha = null;
  31766. this.currentPolygonOffsetFactor = null;
  31767. this.currentPolygonOffsetUnits = null;
  31768. this.currentColorMask = null;
  31769. this.currentDepthFunc = null;
  31770. this.currentDepthMask = null;
  31771. this.currentStencilFunc = null;
  31772. this.currentStencilRef = null;
  31773. this.currentStencilFuncMask = null;
  31774. this.currentStencilFail = null;
  31775. this.currentStencilZFail = null;
  31776. this.currentStencilZPass = null;
  31777. this.currentStencilMask = null;
  31778. this.currentLineWidth = null;
  31779. this.currentClippingPlanes = 0;
  31780. this.currentBoundFramebuffers = {};
  31781. this.currentDrawbuffers = new WeakMap();
  31782. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  31783. this.currentTextureSlot = null;
  31784. this.currentBoundTextures = {};
  31785. this.currentBoundBufferBases = {};
  31786. if ( initialized$1 === false ) {
  31787. this._init( this.gl );
  31788. initialized$1 = true;
  31789. }
  31790. }
  31791. _init( gl ) {
  31792. // Store only WebGL constants here.
  31793. equationToGL = {
  31794. [ AddEquation ]: gl.FUNC_ADD,
  31795. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  31796. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  31797. };
  31798. factorToGL = {
  31799. [ ZeroFactor ]: gl.ZERO,
  31800. [ OneFactor ]: gl.ONE,
  31801. [ SrcColorFactor ]: gl.SRC_COLOR,
  31802. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  31803. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  31804. [ DstColorFactor ]: gl.DST_COLOR,
  31805. [ DstAlphaFactor ]: gl.DST_ALPHA,
  31806. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  31807. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  31808. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  31809. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  31810. };
  31811. }
  31812. enable( id ) {
  31813. const { enabled } = this;
  31814. if ( enabled[ id ] !== true ) {
  31815. this.gl.enable( id );
  31816. enabled[ id ] = true;
  31817. }
  31818. }
  31819. disable( id ) {
  31820. const { enabled } = this;
  31821. if ( enabled[ id ] !== false ) {
  31822. this.gl.disable( id );
  31823. enabled[ id ] = false;
  31824. }
  31825. }
  31826. setFlipSided( flipSided ) {
  31827. if ( this.currentFlipSided !== flipSided ) {
  31828. const { gl } = this;
  31829. if ( flipSided ) {
  31830. gl.frontFace( gl.CW );
  31831. } else {
  31832. gl.frontFace( gl.CCW );
  31833. }
  31834. this.currentFlipSided = flipSided;
  31835. }
  31836. }
  31837. setCullFace( cullFace ) {
  31838. const { gl } = this;
  31839. if ( cullFace !== CullFaceNone ) {
  31840. this.enable( gl.CULL_FACE );
  31841. if ( cullFace !== this.currentCullFace ) {
  31842. if ( cullFace === CullFaceBack ) {
  31843. gl.cullFace( gl.BACK );
  31844. } else if ( cullFace === CullFaceFront ) {
  31845. gl.cullFace( gl.FRONT );
  31846. } else {
  31847. gl.cullFace( gl.FRONT_AND_BACK );
  31848. }
  31849. }
  31850. } else {
  31851. this.disable( gl.CULL_FACE );
  31852. }
  31853. this.currentCullFace = cullFace;
  31854. }
  31855. setLineWidth( width ) {
  31856. const { currentLineWidth, gl } = this;
  31857. if ( width !== currentLineWidth ) {
  31858. gl.lineWidth( width );
  31859. this.currentLineWidth = width;
  31860. }
  31861. }
  31862. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  31863. const { gl } = this;
  31864. if ( blending === NoBlending ) {
  31865. if ( this.currentBlendingEnabled === true ) {
  31866. this.disable( gl.BLEND );
  31867. this.currentBlendingEnabled = false;
  31868. }
  31869. return;
  31870. }
  31871. if ( this.currentBlendingEnabled === false ) {
  31872. this.enable( gl.BLEND );
  31873. this.currentBlendingEnabled = true;
  31874. }
  31875. if ( blending !== CustomBlending ) {
  31876. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  31877. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  31878. gl.blendEquation( gl.FUNC_ADD );
  31879. this.currentBlendEquation = AddEquation;
  31880. this.currentBlendEquationAlpha = AddEquation;
  31881. }
  31882. if ( premultipliedAlpha ) {
  31883. switch ( blending ) {
  31884. case NormalBlending:
  31885. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  31886. break;
  31887. case AdditiveBlending:
  31888. gl.blendFunc( gl.ONE, gl.ONE );
  31889. break;
  31890. case SubtractiveBlending:
  31891. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  31892. break;
  31893. case MultiplyBlending:
  31894. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  31895. break;
  31896. default:
  31897. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  31898. break;
  31899. }
  31900. } else {
  31901. switch ( blending ) {
  31902. case NormalBlending:
  31903. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  31904. break;
  31905. case AdditiveBlending:
  31906. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  31907. break;
  31908. case SubtractiveBlending:
  31909. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  31910. break;
  31911. case MultiplyBlending:
  31912. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  31913. break;
  31914. default:
  31915. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  31916. break;
  31917. }
  31918. }
  31919. this.currentBlendSrc = null;
  31920. this.currentBlendDst = null;
  31921. this.currentBlendSrcAlpha = null;
  31922. this.currentBlendDstAlpha = null;
  31923. this.currentBlending = blending;
  31924. this.currentPremultipledAlpha = premultipliedAlpha;
  31925. }
  31926. return;
  31927. }
  31928. // custom blending
  31929. blendEquationAlpha = blendEquationAlpha || blendEquation;
  31930. blendSrcAlpha = blendSrcAlpha || blendSrc;
  31931. blendDstAlpha = blendDstAlpha || blendDst;
  31932. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  31933. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  31934. this.currentBlendEquation = blendEquation;
  31935. this.currentBlendEquationAlpha = blendEquationAlpha;
  31936. }
  31937. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  31938. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  31939. this.currentBlendSrc = blendSrc;
  31940. this.currentBlendDst = blendDst;
  31941. this.currentBlendSrcAlpha = blendSrcAlpha;
  31942. this.currentBlendDstAlpha = blendDstAlpha;
  31943. }
  31944. this.currentBlending = blending;
  31945. this.currentPremultipledAlpha = false;
  31946. }
  31947. setColorMask( colorMask ) {
  31948. if ( this.currentColorMask !== colorMask ) {
  31949. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  31950. this.currentColorMask = colorMask;
  31951. }
  31952. }
  31953. setDepthTest( depthTest ) {
  31954. const { gl } = this;
  31955. if ( depthTest ) {
  31956. this.enable( gl.DEPTH_TEST );
  31957. } else {
  31958. this.disable( gl.DEPTH_TEST );
  31959. }
  31960. }
  31961. setDepthMask( depthMask ) {
  31962. if ( this.currentDepthMask !== depthMask ) {
  31963. this.gl.depthMask( depthMask );
  31964. this.currentDepthMask = depthMask;
  31965. }
  31966. }
  31967. setDepthFunc( depthFunc ) {
  31968. if ( this.currentDepthFunc !== depthFunc ) {
  31969. const { gl } = this;
  31970. switch ( depthFunc ) {
  31971. case NeverDepth:
  31972. gl.depthFunc( gl.NEVER );
  31973. break;
  31974. case AlwaysDepth:
  31975. gl.depthFunc( gl.ALWAYS );
  31976. break;
  31977. case LessDepth:
  31978. gl.depthFunc( gl.LESS );
  31979. break;
  31980. case LessEqualDepth:
  31981. gl.depthFunc( gl.LEQUAL );
  31982. break;
  31983. case EqualDepth:
  31984. gl.depthFunc( gl.EQUAL );
  31985. break;
  31986. case GreaterEqualDepth:
  31987. gl.depthFunc( gl.GEQUAL );
  31988. break;
  31989. case GreaterDepth:
  31990. gl.depthFunc( gl.GREATER );
  31991. break;
  31992. case NotEqualDepth:
  31993. gl.depthFunc( gl.NOTEQUAL );
  31994. break;
  31995. default:
  31996. gl.depthFunc( gl.LEQUAL );
  31997. }
  31998. this.currentDepthFunc = depthFunc;
  31999. }
  32000. }
  32001. setStencilTest( stencilTest ) {
  32002. const { gl } = this;
  32003. if ( stencilTest ) {
  32004. this.enable( gl.STENCIL_TEST );
  32005. } else {
  32006. this.disable( gl.STENCIL_TEST );
  32007. }
  32008. }
  32009. setStencilMask( stencilMask ) {
  32010. if ( this.currentStencilMask !== stencilMask ) {
  32011. this.gl.stencilMask( stencilMask );
  32012. this.currentStencilMask = stencilMask;
  32013. }
  32014. }
  32015. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  32016. if ( this.currentStencilFunc !== stencilFunc ||
  32017. this.currentStencilRef !== stencilRef ||
  32018. this.currentStencilFuncMask !== stencilMask ) {
  32019. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  32020. this.currentStencilFunc = stencilFunc;
  32021. this.currentStencilRef = stencilRef;
  32022. this.currentStencilFuncMask = stencilMask;
  32023. }
  32024. }
  32025. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  32026. if ( this.currentStencilFail !== stencilFail ||
  32027. this.currentStencilZFail !== stencilZFail ||
  32028. this.currentStencilZPass !== stencilZPass ) {
  32029. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  32030. this.currentStencilFail = stencilFail;
  32031. this.currentStencilZFail = stencilZFail;
  32032. this.currentStencilZPass = stencilZPass;
  32033. }
  32034. }
  32035. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  32036. const { gl } = this;
  32037. material.side === DoubleSide
  32038. ? this.disable( gl.CULL_FACE )
  32039. : this.enable( gl.CULL_FACE );
  32040. let flipSided = ( material.side === BackSide );
  32041. if ( frontFaceCW ) flipSided = ! flipSided;
  32042. this.setFlipSided( flipSided );
  32043. ( material.blending === NormalBlending && material.transparent === false )
  32044. ? this.setBlending( NoBlending )
  32045. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  32046. this.setDepthFunc( material.depthFunc );
  32047. this.setDepthTest( material.depthTest );
  32048. this.setDepthMask( material.depthWrite );
  32049. this.setColorMask( material.colorWrite );
  32050. const stencilWrite = material.stencilWrite;
  32051. this.setStencilTest( stencilWrite );
  32052. if ( stencilWrite ) {
  32053. this.setStencilMask( material.stencilWriteMask );
  32054. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  32055. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  32056. }
  32057. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  32058. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  32059. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  32060. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  32061. if ( hardwareClippingPlanes > 0 ) {
  32062. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  32063. const CLIP_DISTANCE0_WEBGL = 0x3000;
  32064. for ( let i = 0; i < 8; i ++ ) {
  32065. if ( i < hardwareClippingPlanes ) {
  32066. this.enable( CLIP_DISTANCE0_WEBGL + i );
  32067. } else {
  32068. this.disable( CLIP_DISTANCE0_WEBGL + i );
  32069. }
  32070. }
  32071. }
  32072. }
  32073. }
  32074. setPolygonOffset( polygonOffset, factor, units ) {
  32075. const { gl } = this;
  32076. if ( polygonOffset ) {
  32077. this.enable( gl.POLYGON_OFFSET_FILL );
  32078. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  32079. gl.polygonOffset( factor, units );
  32080. this.currentPolygonOffsetFactor = factor;
  32081. this.currentPolygonOffsetUnits = units;
  32082. }
  32083. } else {
  32084. this.disable( gl.POLYGON_OFFSET_FILL );
  32085. }
  32086. }
  32087. useProgram( program ) {
  32088. if ( this.currentProgram !== program ) {
  32089. this.gl.useProgram( program );
  32090. this.currentProgram = program;
  32091. return true;
  32092. }
  32093. return false;
  32094. }
  32095. // framebuffer
  32096. bindFramebuffer( target, framebuffer ) {
  32097. const { gl, currentBoundFramebuffers } = this;
  32098. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  32099. gl.bindFramebuffer( target, framebuffer );
  32100. currentBoundFramebuffers[ target ] = framebuffer;
  32101. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  32102. if ( target === gl.DRAW_FRAMEBUFFER ) {
  32103. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  32104. }
  32105. if ( target === gl.FRAMEBUFFER ) {
  32106. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  32107. }
  32108. return true;
  32109. }
  32110. return false;
  32111. }
  32112. drawBuffers( renderContext, framebuffer ) {
  32113. const { gl } = this;
  32114. let drawBuffers = [];
  32115. let needsUpdate = false;
  32116. if ( renderContext.textures !== null ) {
  32117. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  32118. if ( drawBuffers === undefined ) {
  32119. drawBuffers = [];
  32120. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  32121. }
  32122. const textures = renderContext.textures;
  32123. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  32124. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  32125. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  32126. }
  32127. drawBuffers.length = textures.length;
  32128. needsUpdate = true;
  32129. }
  32130. } else {
  32131. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  32132. drawBuffers[ 0 ] = gl.BACK;
  32133. needsUpdate = true;
  32134. }
  32135. }
  32136. if ( needsUpdate ) {
  32137. gl.drawBuffers( drawBuffers );
  32138. }
  32139. }
  32140. // texture
  32141. activeTexture( webglSlot ) {
  32142. const { gl, currentTextureSlot, maxTextures } = this;
  32143. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  32144. if ( currentTextureSlot !== webglSlot ) {
  32145. gl.activeTexture( webglSlot );
  32146. this.currentTextureSlot = webglSlot;
  32147. }
  32148. }
  32149. bindTexture( webglType, webglTexture, webglSlot ) {
  32150. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  32151. if ( webglSlot === undefined ) {
  32152. if ( currentTextureSlot === null ) {
  32153. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  32154. } else {
  32155. webglSlot = currentTextureSlot;
  32156. }
  32157. }
  32158. let boundTexture = currentBoundTextures[ webglSlot ];
  32159. if ( boundTexture === undefined ) {
  32160. boundTexture = { type: undefined, texture: undefined };
  32161. currentBoundTextures[ webglSlot ] = boundTexture;
  32162. }
  32163. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  32164. if ( currentTextureSlot !== webglSlot ) {
  32165. gl.activeTexture( webglSlot );
  32166. this.currentTextureSlot = webglSlot;
  32167. }
  32168. gl.bindTexture( webglType, webglTexture );
  32169. boundTexture.type = webglType;
  32170. boundTexture.texture = webglTexture;
  32171. }
  32172. }
  32173. bindBufferBase( target, index, buffer ) {
  32174. const { gl } = this;
  32175. const key = `${target}-${index}`;
  32176. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  32177. gl.bindBufferBase( target, index, buffer );
  32178. this.currentBoundBufferBases[ key ] = buffer;
  32179. return true;
  32180. }
  32181. return false;
  32182. }
  32183. unbindTexture() {
  32184. const { gl, currentTextureSlot, currentBoundTextures } = this;
  32185. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  32186. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  32187. gl.bindTexture( boundTexture.type, null );
  32188. boundTexture.type = undefined;
  32189. boundTexture.texture = undefined;
  32190. }
  32191. }
  32192. }
  32193. class WebGLUtils {
  32194. constructor( backend ) {
  32195. this.backend = backend;
  32196. this.gl = this.backend.gl;
  32197. this.extensions = backend.extensions;
  32198. }
  32199. convert( p, colorSpace = NoColorSpace ) {
  32200. const { gl, extensions } = this;
  32201. let extension;
  32202. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  32203. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  32204. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  32205. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  32206. if ( p === ByteType ) return gl.BYTE;
  32207. if ( p === ShortType ) return gl.SHORT;
  32208. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  32209. if ( p === IntType ) return gl.INT;
  32210. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  32211. if ( p === FloatType ) return gl.FLOAT;
  32212. if ( p === HalfFloatType ) {
  32213. return gl.HALF_FLOAT;
  32214. }
  32215. if ( p === AlphaFormat ) return gl.ALPHA;
  32216. if ( p === RGBFormat ) return gl.RGB;
  32217. if ( p === RGBAFormat ) return gl.RGBA;
  32218. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  32219. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  32220. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  32221. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  32222. // WebGL2 formats.
  32223. if ( p === RedFormat ) return gl.RED;
  32224. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  32225. if ( p === RGFormat ) return gl.RG;
  32226. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  32227. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  32228. // S3TC
  32229. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  32230. if ( colorSpace === SRGBColorSpace ) {
  32231. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  32232. if ( extension !== null ) {
  32233. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  32234. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  32235. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  32236. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  32237. } else {
  32238. return null;
  32239. }
  32240. } else {
  32241. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  32242. if ( extension !== null ) {
  32243. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  32244. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32245. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32246. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32247. } else {
  32248. return null;
  32249. }
  32250. }
  32251. }
  32252. // PVRTC
  32253. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  32254. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  32255. if ( extension !== null ) {
  32256. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  32257. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  32258. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  32259. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  32260. } else {
  32261. return null;
  32262. }
  32263. }
  32264. // ETC
  32265. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  32266. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  32267. if ( extension !== null ) {
  32268. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  32269. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  32270. } else {
  32271. return null;
  32272. }
  32273. }
  32274. // ASTC
  32275. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  32276. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  32277. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  32278. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  32279. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  32280. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  32281. if ( extension !== null ) {
  32282. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  32283. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  32284. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  32285. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  32286. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  32287. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  32288. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  32289. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  32290. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  32291. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  32292. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  32293. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  32294. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  32295. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  32296. } else {
  32297. return null;
  32298. }
  32299. }
  32300. // BPTC
  32301. if ( p === RGBA_BPTC_Format ) {
  32302. extension = extensions.get( 'EXT_texture_compression_bptc' );
  32303. if ( extension !== null ) {
  32304. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  32305. } else {
  32306. return null;
  32307. }
  32308. }
  32309. // RGTC
  32310. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  32311. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  32312. if ( extension !== null ) {
  32313. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  32314. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  32315. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  32316. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  32317. } else {
  32318. return null;
  32319. }
  32320. }
  32321. //
  32322. if ( p === UnsignedInt248Type ) {
  32323. return gl.UNSIGNED_INT_24_8;
  32324. }
  32325. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  32326. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  32327. }
  32328. _clientWaitAsync() {
  32329. const { gl } = this;
  32330. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  32331. gl.flush();
  32332. return new Promise( ( resolve, reject ) => {
  32333. function test() {
  32334. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  32335. if ( res === gl.WAIT_FAILED ) {
  32336. gl.deleteSync( sync );
  32337. reject();
  32338. return;
  32339. }
  32340. if ( res === gl.TIMEOUT_EXPIRED ) {
  32341. requestAnimationFrame( test );
  32342. return;
  32343. }
  32344. gl.deleteSync( sync );
  32345. resolve();
  32346. }
  32347. test();
  32348. } );
  32349. }
  32350. }
  32351. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  32352. class WebGLTextureUtils {
  32353. constructor( backend ) {
  32354. this.backend = backend;
  32355. this.gl = backend.gl;
  32356. this.extensions = backend.extensions;
  32357. this.defaultTextures = {};
  32358. if ( initialized === false ) {
  32359. this._init( this.gl );
  32360. initialized = true;
  32361. }
  32362. }
  32363. _init( gl ) {
  32364. // Store only WebGL constants here.
  32365. wrappingToGL = {
  32366. [ RepeatWrapping ]: gl.REPEAT,
  32367. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  32368. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  32369. };
  32370. filterToGL = {
  32371. [ NearestFilter ]: gl.NEAREST,
  32372. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  32373. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  32374. [ LinearFilter ]: gl.LINEAR,
  32375. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  32376. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  32377. };
  32378. compareToGL = {
  32379. [ NeverCompare ]: gl.NEVER,
  32380. [ AlwaysCompare ]: gl.ALWAYS,
  32381. [ LessCompare ]: gl.LESS,
  32382. [ LessEqualCompare ]: gl.LEQUAL,
  32383. [ EqualCompare ]: gl.EQUAL,
  32384. [ GreaterEqualCompare ]: gl.GEQUAL,
  32385. [ GreaterCompare ]: gl.GREATER,
  32386. [ NotEqualCompare ]: gl.NOTEQUAL
  32387. };
  32388. }
  32389. filterFallback( f ) {
  32390. const { gl } = this;
  32391. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  32392. return gl.NEAREST;
  32393. }
  32394. return gl.LINEAR;
  32395. }
  32396. getGLTextureType( texture ) {
  32397. const { gl } = this;
  32398. let glTextureType;
  32399. if ( texture.isCubeTexture === true ) {
  32400. glTextureType = gl.TEXTURE_CUBE_MAP;
  32401. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  32402. glTextureType = gl.TEXTURE_2D_ARRAY;
  32403. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  32404. glTextureType = gl.TEXTURE_3D;
  32405. } else {
  32406. glTextureType = gl.TEXTURE_2D;
  32407. }
  32408. return glTextureType;
  32409. }
  32410. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  32411. const { gl, extensions } = this;
  32412. if ( internalFormatName !== null ) {
  32413. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  32414. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  32415. }
  32416. let internalFormat = glFormat;
  32417. if ( glFormat === gl.RED ) {
  32418. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  32419. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  32420. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  32421. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  32422. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  32423. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  32424. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  32425. if ( glType === gl.INT ) internalFormat = gl.R32I;
  32426. }
  32427. if ( glFormat === gl.RED_INTEGER ) {
  32428. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  32429. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  32430. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  32431. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  32432. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  32433. if ( glType === gl.INT ) internalFormat = gl.R32I;
  32434. }
  32435. if ( glFormat === gl.RG ) {
  32436. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  32437. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  32438. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  32439. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  32440. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  32441. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  32442. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  32443. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  32444. }
  32445. if ( glFormat === gl.RG_INTEGER ) {
  32446. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  32447. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  32448. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  32449. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  32450. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  32451. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  32452. }
  32453. if ( glFormat === gl.RGB ) {
  32454. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  32455. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  32456. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  32457. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  32458. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  32459. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  32460. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  32461. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  32462. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  32463. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  32464. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  32465. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  32466. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  32467. }
  32468. if ( glFormat === gl.RGB_INTEGER ) {
  32469. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  32470. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  32471. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  32472. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  32473. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  32474. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  32475. }
  32476. if ( glFormat === gl.RGBA ) {
  32477. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  32478. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  32479. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  32480. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  32481. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  32482. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  32483. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  32484. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  32485. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  32486. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  32487. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  32488. }
  32489. if ( glFormat === gl.RGBA_INTEGER ) {
  32490. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  32491. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  32492. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  32493. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  32494. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  32495. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  32496. }
  32497. if ( glFormat === gl.DEPTH_COMPONENT ) {
  32498. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  32499. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  32500. }
  32501. if ( glFormat === gl.DEPTH_STENCIL ) {
  32502. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  32503. }
  32504. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  32505. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  32506. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  32507. extensions.get( 'EXT_color_buffer_float' );
  32508. }
  32509. return internalFormat;
  32510. }
  32511. setTextureParameters( textureType, texture ) {
  32512. const { gl, extensions, backend } = this;
  32513. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  32514. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  32515. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  32516. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  32517. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  32518. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  32519. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  32520. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  32521. }
  32522. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  32523. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  32524. // follow WebGPU backend mapping for texture filtering
  32525. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  32526. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  32527. if ( texture.compareFunction ) {
  32528. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  32529. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  32530. }
  32531. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  32532. if ( texture.magFilter === NearestFilter ) return;
  32533. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  32534. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  32535. if ( texture.anisotropy > 1 ) {
  32536. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  32537. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  32538. }
  32539. }
  32540. }
  32541. createDefaultTexture( texture ) {
  32542. const { gl, backend, defaultTextures } = this;
  32543. const glTextureType = this.getGLTextureType( texture );
  32544. let textureGPU = defaultTextures[ glTextureType ];
  32545. if ( textureGPU === undefined ) {
  32546. textureGPU = gl.createTexture();
  32547. backend.state.bindTexture( glTextureType, textureGPU );
  32548. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  32549. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  32550. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  32551. defaultTextures[ glTextureType ] = textureGPU;
  32552. }
  32553. backend.set( texture, {
  32554. textureGPU,
  32555. glTextureType,
  32556. isDefault: true
  32557. } );
  32558. }
  32559. createTexture( texture, options ) {
  32560. const { gl, backend } = this;
  32561. const { levels, width, height, depth } = options;
  32562. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  32563. const glType = backend.utils.convert( texture.type );
  32564. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  32565. const textureGPU = gl.createTexture();
  32566. const glTextureType = this.getGLTextureType( texture );
  32567. backend.state.bindTexture( glTextureType, textureGPU );
  32568. this.setTextureParameters( glTextureType, texture );
  32569. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  32570. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  32571. } else if ( texture.isData3DTexture ) {
  32572. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  32573. } else if ( ! texture.isVideoTexture ) {
  32574. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  32575. }
  32576. backend.set( texture, {
  32577. textureGPU,
  32578. glTextureType,
  32579. glFormat,
  32580. glType,
  32581. glInternalFormat
  32582. } );
  32583. }
  32584. copyBufferToTexture( buffer, texture ) {
  32585. const { gl, backend } = this;
  32586. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  32587. const { width, height } = texture.source.data;
  32588. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  32589. backend.state.bindTexture( glTextureType, textureGPU );
  32590. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  32591. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  32592. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  32593. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  32594. backend.state.unbindTexture();
  32595. // debug
  32596. // const framebuffer = gl.createFramebuffer();
  32597. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  32598. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  32599. // const readout = new Float32Array( width * height * 4 );
  32600. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  32601. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  32602. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  32603. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  32604. // console.log( readout );
  32605. }
  32606. updateTexture( texture, options ) {
  32607. const { gl } = this;
  32608. const { width, height } = options;
  32609. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  32610. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  32611. return;
  32612. const getImage = ( source ) => {
  32613. if ( source.isDataTexture ) {
  32614. return source.image.data;
  32615. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  32616. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  32617. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  32618. source instanceof OffscreenCanvas ) {
  32619. return source;
  32620. }
  32621. return source.data;
  32622. };
  32623. this.backend.state.bindTexture( glTextureType, textureGPU );
  32624. this.setTextureParameters( glTextureType, texture );
  32625. if ( texture.isCompressedTexture ) {
  32626. const mipmaps = texture.mipmaps;
  32627. const image = options.image;
  32628. for ( let i = 0; i < mipmaps.length; i ++ ) {
  32629. const mipmap = mipmaps[ i ];
  32630. if ( texture.isCompressedArrayTexture ) {
  32631. if ( texture.format !== gl.RGBA ) {
  32632. if ( glFormat !== null ) {
  32633. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  32634. } else {
  32635. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  32636. }
  32637. } else {
  32638. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  32639. }
  32640. } else {
  32641. if ( glFormat !== null ) {
  32642. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  32643. } else {
  32644. console.warn( 'Unsupported compressed texture format' );
  32645. }
  32646. }
  32647. }
  32648. } else if ( texture.isCubeTexture ) {
  32649. const images = options.images;
  32650. for ( let i = 0; i < 6; i ++ ) {
  32651. const image = getImage( images[ i ] );
  32652. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  32653. }
  32654. } else if ( texture.isDataArrayTexture ) {
  32655. const image = options.image;
  32656. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  32657. } else if ( texture.isData3DTexture ) {
  32658. const image = options.image;
  32659. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  32660. } else if ( texture.isVideoTexture ) {
  32661. texture.update();
  32662. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  32663. } else {
  32664. const image = getImage( options.image );
  32665. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  32666. }
  32667. }
  32668. generateMipmaps( texture ) {
  32669. const { gl, backend } = this;
  32670. const { textureGPU, glTextureType } = backend.get( texture );
  32671. backend.state.bindTexture( glTextureType, textureGPU );
  32672. gl.generateMipmap( glTextureType );
  32673. }
  32674. deallocateRenderBuffers( renderTarget ) {
  32675. const { gl, backend } = this;
  32676. // remove framebuffer reference
  32677. if ( renderTarget ) {
  32678. const renderContextData = backend.get( renderTarget );
  32679. renderContextData.renderBufferStorageSetup = undefined;
  32680. if ( renderContextData.framebuffers ) {
  32681. for ( const cacheKey in renderContextData.framebuffers ) {
  32682. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  32683. }
  32684. delete renderContextData.framebuffers;
  32685. }
  32686. if ( renderContextData.depthRenderbuffer ) {
  32687. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  32688. delete renderContextData.depthRenderbuffer;
  32689. }
  32690. if ( renderContextData.stencilRenderbuffer ) {
  32691. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  32692. delete renderContextData.stencilRenderbuffer;
  32693. }
  32694. if ( renderContextData.msaaFrameBuffer ) {
  32695. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  32696. delete renderContextData.msaaFrameBuffer;
  32697. }
  32698. if ( renderContextData.msaaRenderbuffers ) {
  32699. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  32700. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  32701. }
  32702. delete renderContextData.msaaRenderbuffers;
  32703. }
  32704. }
  32705. }
  32706. destroyTexture( texture ) {
  32707. const { gl, backend } = this;
  32708. const { textureGPU, renderTarget } = backend.get( texture );
  32709. this.deallocateRenderBuffers( renderTarget );
  32710. gl.deleteTexture( textureGPU );
  32711. backend.delete( texture );
  32712. }
  32713. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  32714. const { gl, backend } = this;
  32715. const { state } = this.backend;
  32716. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  32717. let width, height, minX, minY;
  32718. let dstX, dstY;
  32719. if ( srcRegion !== null ) {
  32720. width = srcRegion.max.x - srcRegion.min.x;
  32721. height = srcRegion.max.y - srcRegion.min.y;
  32722. minX = srcRegion.min.x;
  32723. minY = srcRegion.min.y;
  32724. } else {
  32725. width = srcTexture.image.width;
  32726. height = srcTexture.image.height;
  32727. minX = 0;
  32728. minY = 0;
  32729. }
  32730. if ( dstPosition !== null ) {
  32731. dstX = dstPosition.x;
  32732. dstY = dstPosition.y;
  32733. } else {
  32734. dstX = 0;
  32735. dstY = 0;
  32736. }
  32737. state.bindTexture( glTextureType, dstTextureGPU );
  32738. // As another texture upload may have changed pixelStorei
  32739. // parameters, make sure they are correct for the dstTexture
  32740. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  32741. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  32742. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  32743. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  32744. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  32745. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  32746. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  32747. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  32748. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  32749. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  32750. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  32751. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  32752. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  32753. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  32754. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  32755. const srcTextureData = backend.get( srcTexture );
  32756. const dstTextureData = backend.get( dstTexture );
  32757. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  32758. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  32759. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  32760. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  32761. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  32762. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  32763. let mask = gl.COLOR_BUFFER_BIT;
  32764. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  32765. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  32766. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  32767. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  32768. } else {
  32769. if ( srcTexture.isDataTexture ) {
  32770. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  32771. } else {
  32772. if ( srcTexture.isCompressedTexture ) {
  32773. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  32774. } else {
  32775. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  32776. }
  32777. }
  32778. }
  32779. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  32780. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  32781. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  32782. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  32783. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  32784. // Generate mipmaps only when copying level 0
  32785. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  32786. state.unbindTexture();
  32787. }
  32788. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  32789. const { gl } = this;
  32790. const { state } = this.backend;
  32791. const { textureGPU } = this.backend.get( texture );
  32792. const { x, y, z: width, w: height } = rectangle;
  32793. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  32794. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  32795. if ( requireDrawFrameBuffer ) {
  32796. const partial = ( x !== 0 || y !== 0 );
  32797. let mask;
  32798. let attachment;
  32799. if ( texture.isDepthTexture === true ) {
  32800. mask = gl.DEPTH_BUFFER_BIT;
  32801. attachment = gl.DEPTH_ATTACHMENT;
  32802. if ( renderContext.stencil ) {
  32803. mask |= gl.STENCIL_BUFFER_BIT;
  32804. }
  32805. } else {
  32806. mask = gl.COLOR_BUFFER_BIT;
  32807. attachment = gl.COLOR_ATTACHMENT0;
  32808. }
  32809. if ( partial ) {
  32810. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  32811. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  32812. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  32813. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  32814. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  32815. const flippedY = srcHeight - y - height;
  32816. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  32817. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  32818. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  32819. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  32820. state.unbindTexture();
  32821. } else {
  32822. const fb = gl.createFramebuffer();
  32823. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  32824. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  32825. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  32826. gl.deleteFramebuffer( fb );
  32827. }
  32828. } else {
  32829. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  32830. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  32831. state.unbindTexture();
  32832. }
  32833. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  32834. this.backend._setFramebuffer( renderContext );
  32835. }
  32836. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  32837. setupRenderBufferStorage( renderbuffer, renderContext ) {
  32838. const { gl } = this;
  32839. const renderTarget = renderContext.renderTarget;
  32840. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  32841. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  32842. if ( depthBuffer && ! stencilBuffer ) {
  32843. let glInternalFormat = gl.DEPTH_COMPONENT24;
  32844. if ( samples > 0 ) {
  32845. if ( depthTexture && depthTexture.isDepthTexture ) {
  32846. if ( depthTexture.type === gl.FLOAT ) {
  32847. glInternalFormat = gl.DEPTH_COMPONENT32F;
  32848. }
  32849. }
  32850. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  32851. } else {
  32852. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  32853. }
  32854. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  32855. } else if ( depthBuffer && stencilBuffer ) {
  32856. if ( samples > 0 ) {
  32857. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  32858. } else {
  32859. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  32860. }
  32861. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  32862. }
  32863. }
  32864. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  32865. const { backend, gl } = this;
  32866. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  32867. const fb = gl.createFramebuffer();
  32868. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  32869. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  32870. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  32871. const typedArrayType = this._getTypedArrayType( glType );
  32872. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  32873. const elementCount = width * height;
  32874. const byteLength = elementCount * bytesPerTexel;
  32875. const buffer = gl.createBuffer();
  32876. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  32877. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  32878. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  32879. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  32880. await backend.utils._clientWaitAsync();
  32881. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  32882. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  32883. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  32884. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  32885. gl.deleteFramebuffer( fb );
  32886. return dstBuffer;
  32887. }
  32888. _getTypedArrayType( glType ) {
  32889. const { gl } = this;
  32890. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  32891. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  32892. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  32893. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  32894. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  32895. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  32896. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  32897. if ( glType === gl.FLOAT ) return Float32Array;
  32898. throw new Error( `Unsupported WebGL type: ${glType}` );
  32899. }
  32900. _getBytesPerTexel( glType, glFormat ) {
  32901. const { gl } = this;
  32902. let bytesPerComponent = 0;
  32903. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  32904. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  32905. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  32906. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  32907. glType === gl.UNSIGNED_SHORT ||
  32908. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  32909. if ( glType === gl.UNSIGNED_INT ||
  32910. glType === gl.FLOAT ) bytesPerComponent = 4;
  32911. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  32912. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  32913. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  32914. }
  32915. }
  32916. class WebGLExtensions {
  32917. constructor( backend ) {
  32918. this.backend = backend;
  32919. this.gl = this.backend.gl;
  32920. this.availableExtensions = this.gl.getSupportedExtensions();
  32921. this.extensions = {};
  32922. }
  32923. get( name ) {
  32924. let extension = this.extensions[ name ];
  32925. if ( extension === undefined ) {
  32926. extension = this.gl.getExtension( name );
  32927. this.extensions[ name ] = extension;
  32928. }
  32929. return extension;
  32930. }
  32931. has( name ) {
  32932. return this.availableExtensions.includes( name );
  32933. }
  32934. }
  32935. class WebGLCapabilities {
  32936. constructor( backend ) {
  32937. this.backend = backend;
  32938. this.maxAnisotropy = null;
  32939. }
  32940. getMaxAnisotropy() {
  32941. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  32942. const gl = this.backend.gl;
  32943. const extensions = this.backend.extensions;
  32944. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  32945. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  32946. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  32947. } else {
  32948. this.maxAnisotropy = 0;
  32949. }
  32950. return this.maxAnisotropy;
  32951. }
  32952. }
  32953. const GLFeatureName = {
  32954. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  32955. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  32956. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  32957. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  32958. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  32959. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  32960. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  32961. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  32962. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  32963. };
  32964. class WebGLBufferRenderer {
  32965. constructor( backend ) {
  32966. this.gl = backend.gl;
  32967. this.extensions = backend.extensions;
  32968. this.info = backend.renderer.info;
  32969. this.mode = null;
  32970. this.index = 0;
  32971. this.type = null;
  32972. this.object = null;
  32973. }
  32974. render( start, count ) {
  32975. const { gl, mode, object, type, info, index } = this;
  32976. if ( index !== 0 ) {
  32977. gl.drawElements( mode, count, type, start );
  32978. } else {
  32979. gl.drawArrays( mode, start, count );
  32980. }
  32981. info.update( object, count, mode, 1 );
  32982. }
  32983. renderInstances( start, count, primcount ) {
  32984. const { gl, mode, type, index, object, info } = this;
  32985. if ( primcount === 0 ) return;
  32986. if ( index !== 0 ) {
  32987. gl.drawElementsInstanced( mode, count, type, start, primcount );
  32988. } else {
  32989. gl.drawArraysInstanced( mode, start, count, primcount );
  32990. }
  32991. info.update( object, count, mode, primcount );
  32992. }
  32993. renderMultiDraw( starts, counts, drawCount ) {
  32994. const { extensions, mode, object, info } = this;
  32995. if ( drawCount === 0 ) return;
  32996. const extension = extensions.get( 'WEBGL_multi_draw' );
  32997. if ( extension === null ) {
  32998. for ( let i = 0; i < drawCount; i ++ ) {
  32999. this.render( starts[ i ], counts[ i ] );
  33000. }
  33001. } else {
  33002. if ( this.index !== 0 ) {
  33003. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  33004. } else {
  33005. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  33006. }
  33007. let elementCount = 0;
  33008. for ( let i = 0; i < drawCount; i ++ ) {
  33009. elementCount += counts[ i ];
  33010. }
  33011. info.update( object, elementCount, mode, 1 );
  33012. }
  33013. }
  33014. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  33015. const { extensions, mode, object, info } = this;
  33016. if ( drawCount === 0 ) return;
  33017. const extension = extensions.get( 'WEBGL_multi_draw' );
  33018. if ( extension === null ) {
  33019. for ( let i = 0; i < drawCount; i ++ ) {
  33020. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  33021. }
  33022. } else {
  33023. if ( this.index !== 0 ) {
  33024. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  33025. } else {
  33026. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  33027. }
  33028. let elementCount = 0;
  33029. for ( let i = 0; i < drawCount; i ++ ) {
  33030. elementCount += counts[ i ] * primcount[ i ];
  33031. }
  33032. info.update( object, elementCount, mode, 1 );
  33033. }
  33034. }
  33035. //
  33036. }
  33037. //
  33038. class WebGLBackend extends Backend {
  33039. constructor( parameters = {} ) {
  33040. super( parameters );
  33041. this.isWebGLBackend = true;
  33042. }
  33043. init( renderer ) {
  33044. super.init( renderer );
  33045. //
  33046. const parameters = this.parameters;
  33047. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  33048. function onContextLost( event ) {
  33049. event.preventDefault();
  33050. const contextLossInfo = {
  33051. api: 'WebGL',
  33052. message: event.statusMessage || 'Unknown reason',
  33053. reason: null,
  33054. originalEvent: event
  33055. };
  33056. renderer.onDeviceLost( contextLossInfo );
  33057. }
  33058. this._onContextLost = onContextLost;
  33059. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  33060. this.gl = glContext;
  33061. this.extensions = new WebGLExtensions( this );
  33062. this.capabilities = new WebGLCapabilities( this );
  33063. this.attributeUtils = new WebGLAttributeUtils( this );
  33064. this.textureUtils = new WebGLTextureUtils( this );
  33065. this.bufferRenderer = new WebGLBufferRenderer( this );
  33066. this.state = new WebGLState( this );
  33067. this.utils = new WebGLUtils( this );
  33068. this.vaoCache = {};
  33069. this.transformFeedbackCache = {};
  33070. this.discard = false;
  33071. this.trackTimestamp = ( parameters.trackTimestamp === true );
  33072. this.extensions.get( 'EXT_color_buffer_float' );
  33073. this.extensions.get( 'WEBGL_clip_cull_distance' );
  33074. this.extensions.get( 'OES_texture_float_linear' );
  33075. this.extensions.get( 'EXT_color_buffer_half_float' );
  33076. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  33077. this.extensions.get( 'WEBGL_render_shared_exponent' );
  33078. this.extensions.get( 'WEBGL_multi_draw' );
  33079. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  33080. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  33081. this._knownBindings = new WeakSet();
  33082. this._currentContext = null;
  33083. }
  33084. get coordinateSystem() {
  33085. return WebGLCoordinateSystem;
  33086. }
  33087. async getArrayBufferAsync( attribute ) {
  33088. return await this.attributeUtils.getArrayBufferAsync( attribute );
  33089. }
  33090. async waitForGPU() {
  33091. await this.utils._clientWaitAsync();
  33092. }
  33093. initTimestampQuery( renderContext ) {
  33094. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  33095. const renderContextData = this.get( renderContext );
  33096. if ( this.queryRunning ) {
  33097. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  33098. renderContextData.queryQueue.push( renderContext );
  33099. return;
  33100. }
  33101. if ( renderContextData.activeQuery ) {
  33102. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  33103. renderContextData.activeQuery = null;
  33104. }
  33105. renderContextData.activeQuery = this.gl.createQuery();
  33106. if ( renderContextData.activeQuery !== null ) {
  33107. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  33108. this.queryRunning = true;
  33109. }
  33110. }
  33111. // timestamp utils
  33112. prepareTimestampBuffer( renderContext ) {
  33113. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  33114. const renderContextData = this.get( renderContext );
  33115. if ( renderContextData.activeQuery ) {
  33116. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  33117. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  33118. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  33119. renderContextData.activeQuery = null;
  33120. this.queryRunning = false;
  33121. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  33122. const nextRenderContext = renderContextData.queryQueue.shift();
  33123. this.initTimestampQuery( nextRenderContext );
  33124. }
  33125. }
  33126. }
  33127. async resolveTimestampAsync( renderContext, type = 'render' ) {
  33128. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  33129. const renderContextData = this.get( renderContext );
  33130. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  33131. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  33132. const queryInfo = renderContextData.gpuQueries[ i ];
  33133. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  33134. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  33135. if ( available && ! disjoint ) {
  33136. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  33137. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  33138. this.gl.deleteQuery( queryInfo.query );
  33139. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  33140. i --;
  33141. this.renderer.info.updateTimestamp( type, duration );
  33142. }
  33143. }
  33144. }
  33145. getContext() {
  33146. return this.gl;
  33147. }
  33148. beginRender( renderContext ) {
  33149. const { gl } = this;
  33150. const renderContextData = this.get( renderContext );
  33151. //
  33152. //
  33153. this.initTimestampQuery( renderContext );
  33154. renderContextData.previousContext = this._currentContext;
  33155. this._currentContext = renderContext;
  33156. this._setFramebuffer( renderContext );
  33157. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  33158. //
  33159. if ( renderContext.viewport ) {
  33160. this.updateViewport( renderContext );
  33161. } else {
  33162. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  33163. }
  33164. if ( renderContext.scissor ) {
  33165. const { x, y, width, height } = renderContext.scissorValue;
  33166. gl.scissor( x, renderContext.height - height - y, width, height );
  33167. }
  33168. const occlusionQueryCount = renderContext.occlusionQueryCount;
  33169. if ( occlusionQueryCount > 0 ) {
  33170. // Get a reference to the array of objects with queries. The renderContextData property
  33171. // can be changed by another render pass before the async reading of all previous queries complete
  33172. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  33173. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  33174. renderContextData.lastOcclusionObject = null;
  33175. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  33176. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  33177. renderContextData.occlusionQueryIndex = 0;
  33178. }
  33179. }
  33180. finishRender( renderContext ) {
  33181. const { gl, state } = this;
  33182. const renderContextData = this.get( renderContext );
  33183. const previousContext = renderContextData.previousContext;
  33184. const occlusionQueryCount = renderContext.occlusionQueryCount;
  33185. if ( occlusionQueryCount > 0 ) {
  33186. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  33187. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  33188. }
  33189. this.resolveOccludedAsync( renderContext );
  33190. }
  33191. const textures = renderContext.textures;
  33192. if ( textures !== null ) {
  33193. for ( let i = 0; i < textures.length; i ++ ) {
  33194. const texture = textures[ i ];
  33195. if ( texture.generateMipmaps ) {
  33196. this.generateMipmaps( texture );
  33197. }
  33198. }
  33199. }
  33200. this._currentContext = previousContext;
  33201. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  33202. const renderTargetContextData = this.get( renderContext.renderTarget );
  33203. const { samples } = renderContext.renderTarget;
  33204. if ( samples > 0 ) {
  33205. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  33206. const mask = gl.COLOR_BUFFER_BIT;
  33207. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  33208. const textures = renderContext.textures;
  33209. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  33210. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  33211. for ( let i = 0; i < textures.length; i ++ ) {
  33212. // TODO Add support for MRT
  33213. if ( renderContext.scissor ) {
  33214. const { x, y, width, height } = renderContext.scissorValue;
  33215. const viewY = renderContext.height - height - y;
  33216. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  33217. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  33218. } else {
  33219. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  33220. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  33221. }
  33222. }
  33223. }
  33224. }
  33225. if ( previousContext !== null ) {
  33226. this._setFramebuffer( previousContext );
  33227. if ( previousContext.viewport ) {
  33228. this.updateViewport( previousContext );
  33229. } else {
  33230. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  33231. }
  33232. }
  33233. this.prepareTimestampBuffer( renderContext );
  33234. }
  33235. resolveOccludedAsync( renderContext ) {
  33236. const renderContextData = this.get( renderContext );
  33237. // handle occlusion query results
  33238. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  33239. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  33240. const occluded = new WeakSet();
  33241. const { gl } = this;
  33242. renderContextData.currentOcclusionQueryObjects = null;
  33243. renderContextData.currentOcclusionQueries = null;
  33244. const check = () => {
  33245. let completed = 0;
  33246. // check all queries and requeue as appropriate
  33247. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  33248. const query = currentOcclusionQueries[ i ];
  33249. if ( query === null ) continue;
  33250. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  33251. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  33252. currentOcclusionQueries[ i ] = null;
  33253. gl.deleteQuery( query );
  33254. completed ++;
  33255. }
  33256. }
  33257. if ( completed < currentOcclusionQueries.length ) {
  33258. requestAnimationFrame( check );
  33259. } else {
  33260. renderContextData.occluded = occluded;
  33261. }
  33262. };
  33263. check();
  33264. }
  33265. }
  33266. isOccluded( renderContext, object ) {
  33267. const renderContextData = this.get( renderContext );
  33268. return renderContextData.occluded && renderContextData.occluded.has( object );
  33269. }
  33270. updateViewport( renderContext ) {
  33271. const gl = this.gl;
  33272. const { x, y, width, height } = renderContext.viewportValue;
  33273. gl.viewport( x, renderContext.height - height - y, width, height );
  33274. }
  33275. setScissorTest( boolean ) {
  33276. const gl = this.gl;
  33277. if ( boolean ) {
  33278. gl.enable( gl.SCISSOR_TEST );
  33279. } else {
  33280. gl.disable( gl.SCISSOR_TEST );
  33281. }
  33282. }
  33283. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  33284. const { gl } = this;
  33285. if ( descriptor === null ) {
  33286. const clearColor = this.getClearColor();
  33287. // premultiply alpha
  33288. clearColor.r *= clearColor.a;
  33289. clearColor.g *= clearColor.a;
  33290. clearColor.b *= clearColor.a;
  33291. descriptor = {
  33292. textures: null,
  33293. clearColorValue: clearColor
  33294. };
  33295. }
  33296. //
  33297. let clear = 0;
  33298. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  33299. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  33300. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  33301. if ( clear !== 0 ) {
  33302. let clearColor;
  33303. if ( descriptor.clearColorValue ) {
  33304. clearColor = descriptor.clearColorValue;
  33305. } else {
  33306. clearColor = this.getClearColor();
  33307. // premultiply alpha
  33308. clearColor.r *= clearColor.a;
  33309. clearColor.g *= clearColor.a;
  33310. clearColor.b *= clearColor.a;
  33311. }
  33312. if ( depth ) this.state.setDepthMask( true );
  33313. if ( descriptor.textures === null ) {
  33314. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  33315. gl.clear( clear );
  33316. } else {
  33317. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  33318. if ( color ) {
  33319. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  33320. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  33321. }
  33322. }
  33323. if ( depth && stencil ) {
  33324. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  33325. } else if ( depth ) {
  33326. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  33327. } else if ( stencil ) {
  33328. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  33329. }
  33330. }
  33331. }
  33332. }
  33333. beginCompute( computeGroup ) {
  33334. const { state, gl } = this;
  33335. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  33336. this.initTimestampQuery( computeGroup );
  33337. }
  33338. compute( computeGroup, computeNode, bindings, pipeline ) {
  33339. const { state, gl } = this;
  33340. if ( ! this.discard ) {
  33341. // required here to handle async behaviour of render.compute()
  33342. gl.enable( gl.RASTERIZER_DISCARD );
  33343. this.discard = true;
  33344. }
  33345. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  33346. const vaoKey = this._getVaoKey( null, attributes );
  33347. const vaoGPU = this.vaoCache[ vaoKey ];
  33348. if ( vaoGPU === undefined ) {
  33349. this._createVao( null, attributes );
  33350. } else {
  33351. gl.bindVertexArray( vaoGPU );
  33352. }
  33353. state.useProgram( programGPU );
  33354. this._bindUniforms( bindings );
  33355. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  33356. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  33357. gl.beginTransformFeedback( gl.POINTS );
  33358. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  33359. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  33360. } else {
  33361. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  33362. }
  33363. gl.endTransformFeedback();
  33364. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  33365. // switch active buffers
  33366. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  33367. const dualAttributeData = transformBuffers[ i ];
  33368. if ( dualAttributeData.pbo ) {
  33369. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  33370. }
  33371. dualAttributeData.switchBuffers();
  33372. }
  33373. }
  33374. finishCompute( computeGroup ) {
  33375. const gl = this.gl;
  33376. this.discard = false;
  33377. gl.disable( gl.RASTERIZER_DISCARD );
  33378. this.prepareTimestampBuffer( computeGroup );
  33379. if ( this._currentContext ) {
  33380. this._setFramebuffer( this._currentContext );
  33381. }
  33382. }
  33383. draw( renderObject/*, info*/ ) {
  33384. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  33385. const { programGPU } = this.get( pipeline );
  33386. const { gl, state } = this;
  33387. const contextData = this.get( context );
  33388. const drawParams = renderObject.getDrawParameters();
  33389. if ( drawParams === null ) return;
  33390. //
  33391. this._bindUniforms( renderObject.getBindings() );
  33392. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  33393. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  33394. state.useProgram( programGPU );
  33395. //
  33396. const renderObjectData = this.get( renderObject );
  33397. let vaoGPU = renderObjectData.staticVao;
  33398. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  33399. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  33400. vaoGPU = this.vaoCache[ vaoKey ];
  33401. if ( vaoGPU === undefined ) {
  33402. let staticVao;
  33403. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  33404. if ( staticVao ) {
  33405. renderObjectData.staticVao = vaoGPU;
  33406. renderObjectData.geometryId = renderObject.geometry.id;
  33407. }
  33408. }
  33409. }
  33410. gl.bindVertexArray( vaoGPU );
  33411. //
  33412. const index = renderObject.getIndex();
  33413. //
  33414. const lastObject = contextData.lastOcclusionObject;
  33415. if ( lastObject !== object && lastObject !== undefined ) {
  33416. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  33417. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  33418. contextData.occlusionQueryIndex ++;
  33419. }
  33420. if ( object.occlusionTest === true ) {
  33421. const query = gl.createQuery();
  33422. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  33423. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  33424. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  33425. }
  33426. contextData.lastOcclusionObject = object;
  33427. }
  33428. //
  33429. const renderer = this.bufferRenderer;
  33430. if ( object.isPoints ) renderer.mode = gl.POINTS;
  33431. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  33432. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  33433. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  33434. else {
  33435. if ( material.wireframe === true ) {
  33436. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  33437. renderer.mode = gl.LINES;
  33438. } else {
  33439. renderer.mode = gl.TRIANGLES;
  33440. }
  33441. }
  33442. //
  33443. const { vertexCount, instanceCount } = drawParams;
  33444. let { firstVertex } = drawParams;
  33445. renderer.object = object;
  33446. if ( index !== null ) {
  33447. firstVertex *= index.array.BYTES_PER_ELEMENT;
  33448. const indexData = this.get( index );
  33449. renderer.index = index.count;
  33450. renderer.type = indexData.type;
  33451. } else {
  33452. renderer.index = 0;
  33453. }
  33454. if ( object.isBatchedMesh ) {
  33455. if ( object._multiDrawInstances !== null ) {
  33456. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  33457. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  33458. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  33459. } else {
  33460. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  33461. }
  33462. } else if ( instanceCount > 1 ) {
  33463. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  33464. } else {
  33465. renderer.render( firstVertex, vertexCount );
  33466. }
  33467. //
  33468. gl.bindVertexArray( null );
  33469. }
  33470. needsRenderUpdate( /*renderObject*/ ) {
  33471. return false;
  33472. }
  33473. getRenderCacheKey( /*renderObject*/ ) {
  33474. return '';
  33475. }
  33476. // textures
  33477. createDefaultTexture( texture ) {
  33478. this.textureUtils.createDefaultTexture( texture );
  33479. }
  33480. createTexture( texture, options ) {
  33481. this.textureUtils.createTexture( texture, options );
  33482. }
  33483. updateTexture( texture, options ) {
  33484. this.textureUtils.updateTexture( texture, options );
  33485. }
  33486. generateMipmaps( texture ) {
  33487. this.textureUtils.generateMipmaps( texture );
  33488. }
  33489. destroyTexture( texture ) {
  33490. this.textureUtils.destroyTexture( texture );
  33491. }
  33492. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  33493. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  33494. }
  33495. createSampler( /*texture*/ ) {
  33496. //console.warn( 'Abstract class.' );
  33497. }
  33498. destroySampler() {}
  33499. // node builder
  33500. createNodeBuilder( object, renderer ) {
  33501. return new GLSLNodeBuilder( object, renderer );
  33502. }
  33503. // program
  33504. createProgram( program ) {
  33505. const gl = this.gl;
  33506. const { stage, code } = program;
  33507. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  33508. gl.shaderSource( shader, code );
  33509. gl.compileShader( shader );
  33510. this.set( program, {
  33511. shaderGPU: shader
  33512. } );
  33513. }
  33514. destroyProgram( /*program*/ ) {
  33515. console.warn( 'Abstract class.' );
  33516. }
  33517. createRenderPipeline( renderObject, promises ) {
  33518. const gl = this.gl;
  33519. const pipeline = renderObject.pipeline;
  33520. // Program
  33521. const { fragmentProgram, vertexProgram } = pipeline;
  33522. const programGPU = gl.createProgram();
  33523. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  33524. const vertexShader = this.get( vertexProgram ).shaderGPU;
  33525. gl.attachShader( programGPU, fragmentShader );
  33526. gl.attachShader( programGPU, vertexShader );
  33527. gl.linkProgram( programGPU );
  33528. this.set( pipeline, {
  33529. programGPU,
  33530. fragmentShader,
  33531. vertexShader
  33532. } );
  33533. if ( promises !== null && this.parallel ) {
  33534. const p = new Promise( ( resolve /*, reject*/ ) => {
  33535. const parallel = this.parallel;
  33536. const checkStatus = () => {
  33537. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  33538. this._completeCompile( renderObject, pipeline );
  33539. resolve();
  33540. } else {
  33541. requestAnimationFrame( checkStatus );
  33542. }
  33543. };
  33544. checkStatus();
  33545. } );
  33546. promises.push( p );
  33547. return;
  33548. }
  33549. this._completeCompile( renderObject, pipeline );
  33550. }
  33551. _handleSource( string, errorLine ) {
  33552. const lines = string.split( '\n' );
  33553. const lines2 = [];
  33554. const from = Math.max( errorLine - 6, 0 );
  33555. const to = Math.min( errorLine + 6, lines.length );
  33556. for ( let i = from; i < to; i ++ ) {
  33557. const line = i + 1;
  33558. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  33559. }
  33560. return lines2.join( '\n' );
  33561. }
  33562. _getShaderErrors( gl, shader, type ) {
  33563. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  33564. const errors = gl.getShaderInfoLog( shader ).trim();
  33565. if ( status && errors === '' ) return '';
  33566. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  33567. if ( errorMatches ) {
  33568. const errorLine = parseInt( errorMatches[ 1 ] );
  33569. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  33570. } else {
  33571. return errors;
  33572. }
  33573. }
  33574. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  33575. if ( this.renderer.debug.checkShaderErrors ) {
  33576. const gl = this.gl;
  33577. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  33578. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  33579. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  33580. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  33581. } else {
  33582. // default error reporting
  33583. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  33584. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  33585. console.error(
  33586. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  33587. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  33588. 'Program Info Log: ' + programLog + '\n' +
  33589. vertexErrors + '\n' +
  33590. fragmentErrors
  33591. );
  33592. }
  33593. } else if ( programLog !== '' ) {
  33594. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  33595. }
  33596. }
  33597. }
  33598. _completeCompile( renderObject, pipeline ) {
  33599. const { state, gl } = this;
  33600. const pipelineData = this.get( pipeline );
  33601. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  33602. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  33603. this._logProgramError( programGPU, fragmentShader, vertexShader );
  33604. }
  33605. state.useProgram( programGPU );
  33606. // Bindings
  33607. const bindings = renderObject.getBindings();
  33608. this._setupBindings( bindings, programGPU );
  33609. //
  33610. this.set( pipeline, {
  33611. programGPU
  33612. } );
  33613. }
  33614. createComputePipeline( computePipeline, bindings ) {
  33615. const { state, gl } = this;
  33616. // Program
  33617. const fragmentProgram = {
  33618. stage: 'fragment',
  33619. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  33620. };
  33621. this.createProgram( fragmentProgram );
  33622. const { computeProgram } = computePipeline;
  33623. const programGPU = gl.createProgram();
  33624. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  33625. const vertexShader = this.get( computeProgram ).shaderGPU;
  33626. const transforms = computeProgram.transforms;
  33627. const transformVaryingNames = [];
  33628. const transformAttributeNodes = [];
  33629. for ( let i = 0; i < transforms.length; i ++ ) {
  33630. const transform = transforms[ i ];
  33631. transformVaryingNames.push( transform.varyingName );
  33632. transformAttributeNodes.push( transform.attributeNode );
  33633. }
  33634. gl.attachShader( programGPU, fragmentShader );
  33635. gl.attachShader( programGPU, vertexShader );
  33636. gl.transformFeedbackVaryings(
  33637. programGPU,
  33638. transformVaryingNames,
  33639. gl.SEPARATE_ATTRIBS
  33640. );
  33641. gl.linkProgram( programGPU );
  33642. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  33643. this._logProgramError( programGPU, fragmentShader, vertexShader );
  33644. }
  33645. state.useProgram( programGPU );
  33646. // Bindings
  33647. this._setupBindings( bindings, programGPU );
  33648. const attributeNodes = computeProgram.attributes;
  33649. const attributes = [];
  33650. const transformBuffers = [];
  33651. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  33652. const attribute = attributeNodes[ i ].node.attribute;
  33653. attributes.push( attribute );
  33654. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  33655. }
  33656. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  33657. const attribute = transformAttributeNodes[ i ].attribute;
  33658. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  33659. const attributeData = this.get( attribute );
  33660. transformBuffers.push( attributeData );
  33661. }
  33662. //
  33663. this.set( computePipeline, {
  33664. programGPU,
  33665. transformBuffers,
  33666. attributes
  33667. } );
  33668. }
  33669. createBindings( bindGroup, bindings ) {
  33670. if ( this._knownBindings.has( bindings ) === false ) {
  33671. this._knownBindings.add( bindings );
  33672. let uniformBuffers = 0;
  33673. let textures = 0;
  33674. for ( const bindGroup of bindings ) {
  33675. this.set( bindGroup, {
  33676. textures: textures,
  33677. uniformBuffers: uniformBuffers
  33678. } );
  33679. for ( const binding of bindGroup.bindings ) {
  33680. if ( binding.isUniformBuffer ) uniformBuffers ++;
  33681. if ( binding.isSampledTexture ) textures ++;
  33682. }
  33683. }
  33684. }
  33685. this.updateBindings( bindGroup, bindings );
  33686. }
  33687. updateBindings( bindGroup /*, bindings*/ ) {
  33688. const { gl } = this;
  33689. const bindGroupData = this.get( bindGroup );
  33690. let i = bindGroupData.uniformBuffers;
  33691. let t = bindGroupData.textures;
  33692. for ( const binding of bindGroup.bindings ) {
  33693. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  33694. const data = binding.buffer;
  33695. const bufferGPU = gl.createBuffer();
  33696. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  33697. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  33698. this.set( binding, {
  33699. index: i ++,
  33700. bufferGPU
  33701. } );
  33702. } else if ( binding.isSampledTexture ) {
  33703. const { textureGPU, glTextureType } = this.get( binding.texture );
  33704. this.set( binding, {
  33705. index: t ++,
  33706. textureGPU,
  33707. glTextureType
  33708. } );
  33709. }
  33710. }
  33711. }
  33712. updateBinding( binding ) {
  33713. const gl = this.gl;
  33714. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  33715. const bindingData = this.get( binding );
  33716. const bufferGPU = bindingData.bufferGPU;
  33717. const data = binding.buffer;
  33718. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  33719. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  33720. }
  33721. }
  33722. // attributes
  33723. createIndexAttribute( attribute ) {
  33724. const gl = this.gl;
  33725. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  33726. }
  33727. createAttribute( attribute ) {
  33728. if ( this.has( attribute ) ) return;
  33729. const gl = this.gl;
  33730. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  33731. }
  33732. createStorageAttribute( attribute ) {
  33733. if ( this.has( attribute ) ) return;
  33734. const gl = this.gl;
  33735. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  33736. }
  33737. updateAttribute( attribute ) {
  33738. this.attributeUtils.updateAttribute( attribute );
  33739. }
  33740. destroyAttribute( attribute ) {
  33741. this.attributeUtils.destroyAttribute( attribute );
  33742. }
  33743. updateSize() {
  33744. //console.warn( 'Abstract class.' );
  33745. }
  33746. hasFeature( name ) {
  33747. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  33748. const extensions = this.extensions;
  33749. for ( let i = 0; i < keysMatching.length; i ++ ) {
  33750. if ( extensions.has( keysMatching[ i ] ) ) return true;
  33751. }
  33752. return false;
  33753. }
  33754. getMaxAnisotropy() {
  33755. return this.capabilities.getMaxAnisotropy();
  33756. }
  33757. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  33758. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  33759. }
  33760. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  33761. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  33762. }
  33763. _setFramebuffer( descriptor ) {
  33764. const { gl, state } = this;
  33765. let currentFrameBuffer = null;
  33766. if ( descriptor.textures !== null ) {
  33767. const renderTarget = descriptor.renderTarget;
  33768. const renderTargetContextData = this.get( renderTarget );
  33769. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  33770. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  33771. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  33772. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  33773. const cacheKey = getCacheKey( descriptor );
  33774. let fb;
  33775. if ( isCube ) {
  33776. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  33777. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  33778. } else {
  33779. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  33780. fb = renderTargetContextData.framebuffers[ cacheKey ];
  33781. }
  33782. if ( fb === undefined ) {
  33783. fb = gl.createFramebuffer();
  33784. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  33785. const textures = descriptor.textures;
  33786. if ( isCube ) {
  33787. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  33788. const { textureGPU } = this.get( textures[ 0 ] );
  33789. const cubeFace = this.renderer._activeCubeFace;
  33790. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  33791. } else {
  33792. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  33793. for ( let i = 0; i < textures.length; i ++ ) {
  33794. const texture = textures[ i ];
  33795. const textureData = this.get( texture );
  33796. textureData.renderTarget = descriptor.renderTarget;
  33797. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  33798. const attachment = gl.COLOR_ATTACHMENT0 + i;
  33799. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  33800. }
  33801. state.drawBuffers( descriptor, fb );
  33802. }
  33803. if ( descriptor.depthTexture !== null ) {
  33804. const textureData = this.get( descriptor.depthTexture );
  33805. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  33806. textureData.renderTarget = descriptor.renderTarget;
  33807. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  33808. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  33809. }
  33810. }
  33811. if ( samples > 0 ) {
  33812. if ( msaaFb === undefined ) {
  33813. const invalidationArray = [];
  33814. msaaFb = gl.createFramebuffer();
  33815. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  33816. const msaaRenderbuffers = [];
  33817. const textures = descriptor.textures;
  33818. for ( let i = 0; i < textures.length; i ++ ) {
  33819. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  33820. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  33821. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  33822. if ( depthBuffer ) {
  33823. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  33824. invalidationArray.push( depthStyle );
  33825. }
  33826. const texture = descriptor.textures[ i ];
  33827. const textureData = this.get( texture );
  33828. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  33829. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  33830. }
  33831. renderTargetContextData.msaaFrameBuffer = msaaFb;
  33832. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  33833. if ( depthRenderbuffer === undefined ) {
  33834. depthRenderbuffer = gl.createRenderbuffer();
  33835. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  33836. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  33837. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  33838. invalidationArray.push( depthStyle );
  33839. }
  33840. renderTargetContextData.invalidationArray = invalidationArray;
  33841. }
  33842. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  33843. } else {
  33844. currentFrameBuffer = fb;
  33845. }
  33846. }
  33847. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  33848. }
  33849. _getVaoKey( index, attributes ) {
  33850. let key = [];
  33851. if ( index !== null ) {
  33852. const indexData = this.get( index );
  33853. key += ':' + indexData.id;
  33854. }
  33855. for ( let i = 0; i < attributes.length; i ++ ) {
  33856. const attributeData = this.get( attributes[ i ] );
  33857. key += ':' + attributeData.id;
  33858. }
  33859. return key;
  33860. }
  33861. _createVao( index, attributes ) {
  33862. const { gl } = this;
  33863. const vaoGPU = gl.createVertexArray();
  33864. let key = '';
  33865. let staticVao = true;
  33866. gl.bindVertexArray( vaoGPU );
  33867. if ( index !== null ) {
  33868. const indexData = this.get( index );
  33869. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  33870. key += ':' + indexData.id;
  33871. }
  33872. for ( let i = 0; i < attributes.length; i ++ ) {
  33873. const attribute = attributes[ i ];
  33874. const attributeData = this.get( attribute );
  33875. key += ':' + attributeData.id;
  33876. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  33877. gl.enableVertexAttribArray( i );
  33878. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  33879. let stride, offset;
  33880. if ( attribute.isInterleavedBufferAttribute === true ) {
  33881. stride = attribute.data.stride * attributeData.bytesPerElement;
  33882. offset = attribute.offset * attributeData.bytesPerElement;
  33883. } else {
  33884. stride = 0;
  33885. offset = 0;
  33886. }
  33887. if ( attributeData.isInteger ) {
  33888. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  33889. } else {
  33890. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  33891. }
  33892. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  33893. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  33894. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  33895. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  33896. }
  33897. }
  33898. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  33899. this.vaoCache[ key ] = vaoGPU;
  33900. return { vaoGPU, staticVao };
  33901. }
  33902. _getTransformFeedback( transformBuffers ) {
  33903. let key = '';
  33904. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  33905. key += ':' + transformBuffers[ i ].id;
  33906. }
  33907. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  33908. if ( transformFeedbackGPU !== undefined ) {
  33909. return transformFeedbackGPU;
  33910. }
  33911. const { gl } = this;
  33912. transformFeedbackGPU = gl.createTransformFeedback();
  33913. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  33914. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  33915. const attributeData = transformBuffers[ i ];
  33916. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  33917. }
  33918. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  33919. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  33920. return transformFeedbackGPU;
  33921. }
  33922. _setupBindings( bindings, programGPU ) {
  33923. const gl = this.gl;
  33924. for ( const bindGroup of bindings ) {
  33925. for ( const binding of bindGroup.bindings ) {
  33926. const bindingData = this.get( binding );
  33927. const index = bindingData.index;
  33928. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  33929. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  33930. gl.uniformBlockBinding( programGPU, location, index );
  33931. } else if ( binding.isSampledTexture ) {
  33932. const location = gl.getUniformLocation( programGPU, binding.name );
  33933. gl.uniform1i( location, index );
  33934. }
  33935. }
  33936. }
  33937. }
  33938. _bindUniforms( bindings ) {
  33939. const { gl, state } = this;
  33940. for ( const bindGroup of bindings ) {
  33941. for ( const binding of bindGroup.bindings ) {
  33942. const bindingData = this.get( binding );
  33943. const index = bindingData.index;
  33944. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  33945. // TODO USE bindBufferRange to group multiple uniform buffers
  33946. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  33947. } else if ( binding.isSampledTexture ) {
  33948. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  33949. }
  33950. }
  33951. }
  33952. }
  33953. dispose() {
  33954. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  33955. }
  33956. }
  33957. const GPUPrimitiveTopology = {
  33958. PointList: 'point-list',
  33959. LineList: 'line-list',
  33960. LineStrip: 'line-strip',
  33961. TriangleList: 'triangle-list',
  33962. TriangleStrip: 'triangle-strip',
  33963. };
  33964. const GPUCompareFunction = {
  33965. Never: 'never',
  33966. Less: 'less',
  33967. Equal: 'equal',
  33968. LessEqual: 'less-equal',
  33969. Greater: 'greater',
  33970. NotEqual: 'not-equal',
  33971. GreaterEqual: 'greater-equal',
  33972. Always: 'always'
  33973. };
  33974. const GPUStoreOp = {
  33975. Store: 'store',
  33976. Discard: 'discard'
  33977. };
  33978. const GPULoadOp = {
  33979. Load: 'load',
  33980. Clear: 'clear'
  33981. };
  33982. const GPUFrontFace = {
  33983. CCW: 'ccw',
  33984. CW: 'cw'
  33985. };
  33986. const GPUCullMode = {
  33987. None: 'none',
  33988. Front: 'front',
  33989. Back: 'back'
  33990. };
  33991. const GPUIndexFormat = {
  33992. Uint16: 'uint16',
  33993. Uint32: 'uint32'
  33994. };
  33995. const GPUTextureFormat = {
  33996. // 8-bit formats
  33997. R8Unorm: 'r8unorm',
  33998. R8Snorm: 'r8snorm',
  33999. R8Uint: 'r8uint',
  34000. R8Sint: 'r8sint',
  34001. // 16-bit formats
  34002. R16Uint: 'r16uint',
  34003. R16Sint: 'r16sint',
  34004. R16Float: 'r16float',
  34005. RG8Unorm: 'rg8unorm',
  34006. RG8Snorm: 'rg8snorm',
  34007. RG8Uint: 'rg8uint',
  34008. RG8Sint: 'rg8sint',
  34009. // 32-bit formats
  34010. R32Uint: 'r32uint',
  34011. R32Sint: 'r32sint',
  34012. R32Float: 'r32float',
  34013. RG16Uint: 'rg16uint',
  34014. RG16Sint: 'rg16sint',
  34015. RG16Float: 'rg16float',
  34016. RGBA8Unorm: 'rgba8unorm',
  34017. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  34018. RGBA8Snorm: 'rgba8snorm',
  34019. RGBA8Uint: 'rgba8uint',
  34020. RGBA8Sint: 'rgba8sint',
  34021. BGRA8Unorm: 'bgra8unorm',
  34022. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  34023. // Packed 32-bit formats
  34024. RGB9E5UFloat: 'rgb9e5ufloat',
  34025. RGB10A2Unorm: 'rgb10a2unorm',
  34026. RG11B10uFloat: 'rgb10a2unorm',
  34027. // 64-bit formats
  34028. RG32Uint: 'rg32uint',
  34029. RG32Sint: 'rg32sint',
  34030. RG32Float: 'rg32float',
  34031. RGBA16Uint: 'rgba16uint',
  34032. RGBA16Sint: 'rgba16sint',
  34033. RGBA16Float: 'rgba16float',
  34034. // 128-bit formats
  34035. RGBA32Uint: 'rgba32uint',
  34036. RGBA32Sint: 'rgba32sint',
  34037. RGBA32Float: 'rgba32float',
  34038. // Depth and stencil formats
  34039. Stencil8: 'stencil8',
  34040. Depth16Unorm: 'depth16unorm',
  34041. Depth24Plus: 'depth24plus',
  34042. Depth24PlusStencil8: 'depth24plus-stencil8',
  34043. Depth32Float: 'depth32float',
  34044. // 'depth32float-stencil8' extension
  34045. Depth32FloatStencil8: 'depth32float-stencil8',
  34046. // BC compressed formats usable if 'texture-compression-bc' is both
  34047. // supported by the device/user agent and enabled in requestDevice.
  34048. BC1RGBAUnorm: 'bc1-rgba-unorm',
  34049. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  34050. BC2RGBAUnorm: 'bc2-rgba-unorm',
  34051. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  34052. BC3RGBAUnorm: 'bc3-rgba-unorm',
  34053. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  34054. BC4RUnorm: 'bc4-r-unorm',
  34055. BC4RSnorm: 'bc4-r-snorm',
  34056. BC5RGUnorm: 'bc5-rg-unorm',
  34057. BC5RGSnorm: 'bc5-rg-snorm',
  34058. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  34059. BC6HRGBFloat: 'bc6h-rgb-float',
  34060. BC7RGBAUnorm: 'bc7-rgba-unorm',
  34061. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  34062. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  34063. // supported by the device/user agent and enabled in requestDevice.
  34064. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  34065. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  34066. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  34067. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  34068. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  34069. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  34070. EACR11Unorm: 'eac-r11unorm',
  34071. EACR11Snorm: 'eac-r11snorm',
  34072. EACRG11Unorm: 'eac-rg11unorm',
  34073. EACRG11Snorm: 'eac-rg11snorm',
  34074. // ASTC compressed formats usable if 'texture-compression-astc' is both
  34075. // supported by the device/user agent and enabled in requestDevice.
  34076. ASTC4x4Unorm: 'astc-4x4-unorm',
  34077. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  34078. ASTC5x4Unorm: 'astc-5x4-unorm',
  34079. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  34080. ASTC5x5Unorm: 'astc-5x5-unorm',
  34081. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  34082. ASTC6x5Unorm: 'astc-6x5-unorm',
  34083. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  34084. ASTC6x6Unorm: 'astc-6x6-unorm',
  34085. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  34086. ASTC8x5Unorm: 'astc-8x5-unorm',
  34087. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  34088. ASTC8x6Unorm: 'astc-8x6-unorm',
  34089. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  34090. ASTC8x8Unorm: 'astc-8x8-unorm',
  34091. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  34092. ASTC10x5Unorm: 'astc-10x5-unorm',
  34093. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  34094. ASTC10x6Unorm: 'astc-10x6-unorm',
  34095. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  34096. ASTC10x8Unorm: 'astc-10x8-unorm',
  34097. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  34098. ASTC10x10Unorm: 'astc-10x10-unorm',
  34099. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  34100. ASTC12x10Unorm: 'astc-12x10-unorm',
  34101. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  34102. ASTC12x12Unorm: 'astc-12x12-unorm',
  34103. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  34104. };
  34105. const GPUAddressMode = {
  34106. ClampToEdge: 'clamp-to-edge',
  34107. Repeat: 'repeat',
  34108. MirrorRepeat: 'mirror-repeat'
  34109. };
  34110. const GPUFilterMode = {
  34111. Linear: 'linear',
  34112. Nearest: 'nearest'
  34113. };
  34114. const GPUBlendFactor = {
  34115. Zero: 'zero',
  34116. One: 'one',
  34117. Src: 'src',
  34118. OneMinusSrc: 'one-minus-src',
  34119. SrcAlpha: 'src-alpha',
  34120. OneMinusSrcAlpha: 'one-minus-src-alpha',
  34121. Dst: 'dst',
  34122. OneMinusDstColor: 'one-minus-dst',
  34123. DstAlpha: 'dst-alpha',
  34124. OneMinusDstAlpha: 'one-minus-dst-alpha',
  34125. SrcAlphaSaturated: 'src-alpha-saturated',
  34126. Constant: 'constant',
  34127. OneMinusConstant: 'one-minus-constant'
  34128. };
  34129. const GPUBlendOperation = {
  34130. Add: 'add',
  34131. Subtract: 'subtract',
  34132. ReverseSubtract: 'reverse-subtract',
  34133. Min: 'min',
  34134. Max: 'max'
  34135. };
  34136. const GPUColorWriteFlags = {
  34137. None: 0,
  34138. Red: 0x1,
  34139. Green: 0x2,
  34140. Blue: 0x4,
  34141. Alpha: 0x8,
  34142. All: 0xF
  34143. };
  34144. const GPUStencilOperation = {
  34145. Keep: 'keep',
  34146. Zero: 'zero',
  34147. Replace: 'replace',
  34148. Invert: 'invert',
  34149. IncrementClamp: 'increment-clamp',
  34150. DecrementClamp: 'decrement-clamp',
  34151. IncrementWrap: 'increment-wrap',
  34152. DecrementWrap: 'decrement-wrap'
  34153. };
  34154. const GPUBufferBindingType = {
  34155. Uniform: 'uniform',
  34156. Storage: 'storage',
  34157. ReadOnlyStorage: 'read-only-storage'
  34158. };
  34159. const GPUStorageTextureAccess = {
  34160. WriteOnly: 'write-only',
  34161. ReadOnly: 'read-only',
  34162. ReadWrite: 'read-write',
  34163. };
  34164. const GPUTextureSampleType = {
  34165. Float: 'float',
  34166. UnfilterableFloat: 'unfilterable-float',
  34167. Depth: 'depth',
  34168. SInt: 'sint',
  34169. UInt: 'uint'
  34170. };
  34171. const GPUTextureDimension = {
  34172. OneD: '1d',
  34173. TwoD: '2d',
  34174. ThreeD: '3d'
  34175. };
  34176. const GPUTextureViewDimension = {
  34177. OneD: '1d',
  34178. TwoD: '2d',
  34179. TwoDArray: '2d-array',
  34180. Cube: 'cube',
  34181. CubeArray: 'cube-array',
  34182. ThreeD: '3d'
  34183. };
  34184. const GPUTextureAspect = {
  34185. All: 'all',
  34186. StencilOnly: 'stencil-only',
  34187. DepthOnly: 'depth-only'
  34188. };
  34189. const GPUInputStepMode = {
  34190. Vertex: 'vertex',
  34191. Instance: 'instance'
  34192. };
  34193. const GPUFeatureName = {
  34194. DepthClipControl: 'depth-clip-control',
  34195. Depth32FloatStencil8: 'depth32float-stencil8',
  34196. TextureCompressionBC: 'texture-compression-bc',
  34197. TextureCompressionETC2: 'texture-compression-etc2',
  34198. TextureCompressionASTC: 'texture-compression-astc',
  34199. TimestampQuery: 'timestamp-query',
  34200. IndirectFirstInstance: 'indirect-first-instance',
  34201. ShaderF16: 'shader-f16',
  34202. RG11B10UFloat: 'rg11b10ufloat-renderable',
  34203. BGRA8UNormStorage: 'bgra8unorm-storage',
  34204. Float32Filterable: 'float32-filterable',
  34205. ClipDistances: 'clip-distances',
  34206. DualSourceBlending: 'dual-source-blending',
  34207. Subgroups: 'subgroups'
  34208. };
  34209. class Sampler extends Binding {
  34210. constructor( name, texture ) {
  34211. super( name );
  34212. this.texture = texture;
  34213. this.version = texture ? texture.version : 0;
  34214. this.isSampler = true;
  34215. }
  34216. }
  34217. class NodeSampler extends Sampler {
  34218. constructor( name, textureNode, groupNode ) {
  34219. super( name, textureNode ? textureNode.value : null );
  34220. this.textureNode = textureNode;
  34221. this.groupNode = groupNode;
  34222. }
  34223. update() {
  34224. this.texture = this.textureNode.value;
  34225. }
  34226. }
  34227. class StorageBuffer extends Buffer {
  34228. constructor( name, attribute ) {
  34229. super( name, attribute ? attribute.array : null );
  34230. this.attribute = attribute;
  34231. this.isStorageBuffer = true;
  34232. }
  34233. }
  34234. let _id = 0;
  34235. class NodeStorageBuffer extends StorageBuffer {
  34236. constructor( nodeUniform, groupNode ) {
  34237. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  34238. this.nodeUniform = nodeUniform;
  34239. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  34240. this.groupNode = groupNode;
  34241. }
  34242. get buffer() {
  34243. return this.nodeUniform.value;
  34244. }
  34245. }
  34246. class WebGPUTexturePassUtils extends DataMap {
  34247. constructor( device ) {
  34248. super();
  34249. this.device = device;
  34250. const mipmapVertexSource = `
  34251. struct VarysStruct {
  34252. @builtin( position ) Position: vec4<f32>,
  34253. @location( 0 ) vTex : vec2<f32>
  34254. };
  34255. @vertex
  34256. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  34257. var Varys : VarysStruct;
  34258. var pos = array< vec2<f32>, 4 >(
  34259. vec2<f32>( -1.0, 1.0 ),
  34260. vec2<f32>( 1.0, 1.0 ),
  34261. vec2<f32>( -1.0, -1.0 ),
  34262. vec2<f32>( 1.0, -1.0 )
  34263. );
  34264. var tex = array< vec2<f32>, 4 >(
  34265. vec2<f32>( 0.0, 0.0 ),
  34266. vec2<f32>( 1.0, 0.0 ),
  34267. vec2<f32>( 0.0, 1.0 ),
  34268. vec2<f32>( 1.0, 1.0 )
  34269. );
  34270. Varys.vTex = tex[ vertexIndex ];
  34271. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  34272. return Varys;
  34273. }
  34274. `;
  34275. const mipmapFragmentSource = `
  34276. @group( 0 ) @binding( 0 )
  34277. var imgSampler : sampler;
  34278. @group( 0 ) @binding( 1 )
  34279. var img : texture_2d<f32>;
  34280. @fragment
  34281. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  34282. return textureSample( img, imgSampler, vTex );
  34283. }
  34284. `;
  34285. const flipYFragmentSource = `
  34286. @group( 0 ) @binding( 0 )
  34287. var imgSampler : sampler;
  34288. @group( 0 ) @binding( 1 )
  34289. var img : texture_2d<f32>;
  34290. @fragment
  34291. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  34292. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  34293. }
  34294. `;
  34295. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  34296. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  34297. // We'll need a new pipeline for every texture format used.
  34298. this.transferPipelines = {};
  34299. this.flipYPipelines = {};
  34300. this.mipmapVertexShaderModule = device.createShaderModule( {
  34301. label: 'mipmapVertex',
  34302. code: mipmapVertexSource
  34303. } );
  34304. this.mipmapFragmentShaderModule = device.createShaderModule( {
  34305. label: 'mipmapFragment',
  34306. code: mipmapFragmentSource
  34307. } );
  34308. this.flipYFragmentShaderModule = device.createShaderModule( {
  34309. label: 'flipYFragment',
  34310. code: flipYFragmentSource
  34311. } );
  34312. }
  34313. getTransferPipeline( format ) {
  34314. let pipeline = this.transferPipelines[ format ];
  34315. if ( pipeline === undefined ) {
  34316. pipeline = this.device.createRenderPipeline( {
  34317. label: `mipmap-${ format }`,
  34318. vertex: {
  34319. module: this.mipmapVertexShaderModule,
  34320. entryPoint: 'main'
  34321. },
  34322. fragment: {
  34323. module: this.mipmapFragmentShaderModule,
  34324. entryPoint: 'main',
  34325. targets: [ { format } ]
  34326. },
  34327. primitive: {
  34328. topology: GPUPrimitiveTopology.TriangleStrip,
  34329. stripIndexFormat: GPUIndexFormat.Uint32
  34330. },
  34331. layout: 'auto'
  34332. } );
  34333. this.transferPipelines[ format ] = pipeline;
  34334. }
  34335. return pipeline;
  34336. }
  34337. getFlipYPipeline( format ) {
  34338. let pipeline = this.flipYPipelines[ format ];
  34339. if ( pipeline === undefined ) {
  34340. pipeline = this.device.createRenderPipeline( {
  34341. label: `flipY-${ format }`,
  34342. vertex: {
  34343. module: this.mipmapVertexShaderModule,
  34344. entryPoint: 'main'
  34345. },
  34346. fragment: {
  34347. module: this.flipYFragmentShaderModule,
  34348. entryPoint: 'main',
  34349. targets: [ { format } ]
  34350. },
  34351. primitive: {
  34352. topology: GPUPrimitiveTopology.TriangleStrip,
  34353. stripIndexFormat: GPUIndexFormat.Uint32
  34354. },
  34355. layout: 'auto'
  34356. } );
  34357. this.flipYPipelines[ format ] = pipeline;
  34358. }
  34359. return pipeline;
  34360. }
  34361. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  34362. const format = textureGPUDescriptor.format;
  34363. const { width, height } = textureGPUDescriptor.size;
  34364. const transferPipeline = this.getTransferPipeline( format );
  34365. const flipYPipeline = this.getFlipYPipeline( format );
  34366. const tempTexture = this.device.createTexture( {
  34367. size: { width, height, depthOrArrayLayers: 1 },
  34368. format,
  34369. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  34370. } );
  34371. const srcView = textureGPU.createView( {
  34372. baseMipLevel: 0,
  34373. mipLevelCount: 1,
  34374. dimension: GPUTextureViewDimension.TwoD,
  34375. baseArrayLayer
  34376. } );
  34377. const dstView = tempTexture.createView( {
  34378. baseMipLevel: 0,
  34379. mipLevelCount: 1,
  34380. dimension: GPUTextureViewDimension.TwoD,
  34381. baseArrayLayer: 0
  34382. } );
  34383. const commandEncoder = this.device.createCommandEncoder( {} );
  34384. const pass = ( pipeline, sourceView, destinationView ) => {
  34385. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  34386. const bindGroup = this.device.createBindGroup( {
  34387. layout: bindGroupLayout,
  34388. entries: [ {
  34389. binding: 0,
  34390. resource: this.flipYSampler
  34391. }, {
  34392. binding: 1,
  34393. resource: sourceView
  34394. } ]
  34395. } );
  34396. const passEncoder = commandEncoder.beginRenderPass( {
  34397. colorAttachments: [ {
  34398. view: destinationView,
  34399. loadOp: GPULoadOp.Clear,
  34400. storeOp: GPUStoreOp.Store,
  34401. clearValue: [ 0, 0, 0, 0 ]
  34402. } ]
  34403. } );
  34404. passEncoder.setPipeline( pipeline );
  34405. passEncoder.setBindGroup( 0, bindGroup );
  34406. passEncoder.draw( 4, 1, 0, 0 );
  34407. passEncoder.end();
  34408. };
  34409. pass( transferPipeline, srcView, dstView );
  34410. pass( flipYPipeline, dstView, srcView );
  34411. this.device.queue.submit( [ commandEncoder.finish() ] );
  34412. tempTexture.destroy();
  34413. }
  34414. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  34415. const textureData = this.get( textureGPU );
  34416. if ( textureData.useCount === undefined ) {
  34417. textureData.useCount = 0;
  34418. textureData.layers = [];
  34419. }
  34420. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  34421. const commandEncoder = this.device.createCommandEncoder( {} );
  34422. this._mipmapRunBundles( commandEncoder, passes );
  34423. this.device.queue.submit( [ commandEncoder.finish() ] );
  34424. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  34425. textureData.useCount ++;
  34426. }
  34427. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  34428. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  34429. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  34430. let srcView = textureGPU.createView( {
  34431. baseMipLevel: 0,
  34432. mipLevelCount: 1,
  34433. dimension: GPUTextureViewDimension.TwoD,
  34434. baseArrayLayer
  34435. } );
  34436. const passes = [];
  34437. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  34438. const bindGroup = this.device.createBindGroup( {
  34439. layout: bindGroupLayout,
  34440. entries: [ {
  34441. binding: 0,
  34442. resource: this.mipmapSampler
  34443. }, {
  34444. binding: 1,
  34445. resource: srcView
  34446. } ]
  34447. } );
  34448. const dstView = textureGPU.createView( {
  34449. baseMipLevel: i,
  34450. mipLevelCount: 1,
  34451. dimension: GPUTextureViewDimension.TwoD,
  34452. baseArrayLayer
  34453. } );
  34454. const passDescriptor = {
  34455. colorAttachments: [ {
  34456. view: dstView,
  34457. loadOp: GPULoadOp.Clear,
  34458. storeOp: GPUStoreOp.Store,
  34459. clearValue: [ 0, 0, 0, 0 ]
  34460. } ]
  34461. };
  34462. const passEncoder = this.device.createRenderBundleEncoder( {
  34463. colorFormats: [ textureGPUDescriptor.format ]
  34464. } );
  34465. passEncoder.setPipeline( pipeline );
  34466. passEncoder.setBindGroup( 0, bindGroup );
  34467. passEncoder.draw( 4, 1, 0, 0 );
  34468. passes.push( {
  34469. renderBundles: [ passEncoder.finish() ],
  34470. passDescriptor
  34471. } );
  34472. srcView = dstView;
  34473. }
  34474. return passes;
  34475. }
  34476. _mipmapRunBundles( commandEncoder, passes ) {
  34477. const levels = passes.length;
  34478. for ( let i = 0; i < levels; i ++ ) {
  34479. const pass = passes[ i ];
  34480. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  34481. passEncoder.executeBundles( pass.renderBundles );
  34482. passEncoder.end();
  34483. }
  34484. }
  34485. }
  34486. const _compareToWebGPU = {
  34487. [ NeverCompare ]: 'never',
  34488. [ LessCompare ]: 'less',
  34489. [ EqualCompare ]: 'equal',
  34490. [ LessEqualCompare ]: 'less-equal',
  34491. [ GreaterCompare ]: 'greater',
  34492. [ GreaterEqualCompare ]: 'greater-equal',
  34493. [ AlwaysCompare ]: 'always',
  34494. [ NotEqualCompare ]: 'not-equal'
  34495. };
  34496. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  34497. class WebGPUTextureUtils {
  34498. constructor( backend ) {
  34499. this.backend = backend;
  34500. this._passUtils = null;
  34501. this.defaultTexture = {};
  34502. this.defaultCubeTexture = {};
  34503. this.defaultVideoFrame = null;
  34504. this.colorBuffer = null;
  34505. this.depthTexture = new DepthTexture();
  34506. this.depthTexture.name = 'depthBuffer';
  34507. }
  34508. createSampler( texture ) {
  34509. const backend = this.backend;
  34510. const device = backend.device;
  34511. const textureGPU = backend.get( texture );
  34512. const samplerDescriptorGPU = {
  34513. addressModeU: this._convertAddressMode( texture.wrapS ),
  34514. addressModeV: this._convertAddressMode( texture.wrapT ),
  34515. addressModeW: this._convertAddressMode( texture.wrapR ),
  34516. magFilter: this._convertFilterMode( texture.magFilter ),
  34517. minFilter: this._convertFilterMode( texture.minFilter ),
  34518. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  34519. maxAnisotropy: 1
  34520. };
  34521. // anisotropy can only be used when all filter modes are set to linear.
  34522. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  34523. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  34524. }
  34525. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  34526. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  34527. }
  34528. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  34529. }
  34530. createDefaultTexture( texture ) {
  34531. let textureGPU;
  34532. const format = getFormat( texture );
  34533. if ( texture.isCubeTexture ) {
  34534. textureGPU = this._getDefaultCubeTextureGPU( format );
  34535. } else if ( texture.isVideoTexture ) {
  34536. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  34537. } else {
  34538. textureGPU = this._getDefaultTextureGPU( format );
  34539. }
  34540. this.backend.get( texture ).texture = textureGPU;
  34541. }
  34542. createTexture( texture, options = {} ) {
  34543. const backend = this.backend;
  34544. const textureData = backend.get( texture );
  34545. if ( textureData.initialized ) {
  34546. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  34547. }
  34548. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  34549. if ( options.levels === undefined ) options.levels = 1;
  34550. if ( options.depth === undefined ) options.depth = 1;
  34551. const { width, height, depth, levels } = options;
  34552. if ( texture.isFramebufferTexture ) {
  34553. if ( options.renderTarget ) {
  34554. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  34555. } else {
  34556. options.format = this.backend.utils.getPreferredCanvasFormat();
  34557. }
  34558. }
  34559. const dimension = this._getDimension( texture );
  34560. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  34561. textureData.format = format;
  34562. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  34563. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  34564. if ( texture.isStorageTexture === true ) {
  34565. usage |= GPUTextureUsage.STORAGE_BINDING;
  34566. }
  34567. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  34568. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  34569. }
  34570. const textureDescriptorGPU = {
  34571. label: texture.name,
  34572. size: {
  34573. width: width,
  34574. height: height,
  34575. depthOrArrayLayers: depth,
  34576. },
  34577. mipLevelCount: levels,
  34578. sampleCount: primarySamples,
  34579. dimension: dimension,
  34580. format: format,
  34581. usage: usage
  34582. };
  34583. // texture creation
  34584. if ( texture.isVideoTexture ) {
  34585. const video = texture.source.data;
  34586. const videoFrame = new VideoFrame( video );
  34587. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  34588. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  34589. videoFrame.close();
  34590. textureData.externalTexture = video;
  34591. } else {
  34592. if ( format === undefined ) {
  34593. console.warn( 'WebGPURenderer: Texture format not supported.' );
  34594. return this.createDefaultTexture( texture );
  34595. }
  34596. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  34597. }
  34598. if ( isMSAA ) {
  34599. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  34600. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  34601. msaaTextureDescriptorGPU.sampleCount = samples;
  34602. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  34603. }
  34604. textureData.initialized = true;
  34605. textureData.textureDescriptorGPU = textureDescriptorGPU;
  34606. }
  34607. destroyTexture( texture ) {
  34608. const backend = this.backend;
  34609. const textureData = backend.get( texture );
  34610. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  34611. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  34612. backend.delete( texture );
  34613. }
  34614. destroySampler( texture ) {
  34615. const backend = this.backend;
  34616. const textureData = backend.get( texture );
  34617. delete textureData.sampler;
  34618. }
  34619. generateMipmaps( texture ) {
  34620. const textureData = this.backend.get( texture );
  34621. if ( texture.isCubeTexture ) {
  34622. for ( let i = 0; i < 6; i ++ ) {
  34623. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  34624. }
  34625. } else {
  34626. const depth = texture.image.depth || 1;
  34627. for ( let i = 0; i < depth; i ++ ) {
  34628. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  34629. }
  34630. }
  34631. }
  34632. getColorBuffer() {
  34633. if ( this.colorBuffer ) this.colorBuffer.destroy();
  34634. const backend = this.backend;
  34635. const { width, height } = backend.getDrawingBufferSize();
  34636. this.colorBuffer = backend.device.createTexture( {
  34637. label: 'colorBuffer',
  34638. size: {
  34639. width: width,
  34640. height: height,
  34641. depthOrArrayLayers: 1
  34642. },
  34643. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  34644. format: backend.utils.getPreferredCanvasFormat(),
  34645. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  34646. } );
  34647. return this.colorBuffer;
  34648. }
  34649. getDepthBuffer( depth = true, stencil = false ) {
  34650. const backend = this.backend;
  34651. const { width, height } = backend.getDrawingBufferSize();
  34652. const depthTexture = this.depthTexture;
  34653. const depthTextureGPU = backend.get( depthTexture ).texture;
  34654. let format, type;
  34655. if ( stencil ) {
  34656. format = DepthStencilFormat;
  34657. type = UnsignedInt248Type;
  34658. } else if ( depth ) {
  34659. format = DepthFormat;
  34660. type = UnsignedIntType;
  34661. }
  34662. if ( depthTextureGPU !== undefined ) {
  34663. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  34664. return depthTextureGPU;
  34665. }
  34666. this.destroyTexture( depthTexture );
  34667. }
  34668. depthTexture.name = 'depthBuffer';
  34669. depthTexture.format = format;
  34670. depthTexture.type = type;
  34671. depthTexture.image.width = width;
  34672. depthTexture.image.height = height;
  34673. this.createTexture( depthTexture, { width, height } );
  34674. return backend.get( depthTexture ).texture;
  34675. }
  34676. updateTexture( texture, options ) {
  34677. const textureData = this.backend.get( texture );
  34678. const { textureDescriptorGPU } = textureData;
  34679. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  34680. return;
  34681. // transfer texture data
  34682. if ( texture.isDataTexture ) {
  34683. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  34684. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  34685. for ( let i = 0; i < options.image.depth; i ++ ) {
  34686. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  34687. }
  34688. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  34689. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  34690. } else if ( texture.isCubeTexture ) {
  34691. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  34692. } else if ( texture.isVideoTexture ) {
  34693. const video = texture.source.data;
  34694. textureData.externalTexture = video;
  34695. } else {
  34696. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  34697. }
  34698. //
  34699. textureData.version = texture.version;
  34700. if ( texture.onUpdate ) texture.onUpdate( texture );
  34701. }
  34702. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  34703. const device = this.backend.device;
  34704. const textureData = this.backend.get( texture );
  34705. const textureGPU = textureData.texture;
  34706. const format = textureData.textureDescriptorGPU.format;
  34707. const bytesPerTexel = this._getBytesPerTexel( format );
  34708. let bytesPerRow = width * bytesPerTexel;
  34709. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  34710. const readBuffer = device.createBuffer(
  34711. {
  34712. size: width * height * bytesPerTexel,
  34713. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  34714. }
  34715. );
  34716. const encoder = device.createCommandEncoder();
  34717. encoder.copyTextureToBuffer(
  34718. {
  34719. texture: textureGPU,
  34720. origin: { x, y, z: faceIndex },
  34721. },
  34722. {
  34723. buffer: readBuffer,
  34724. bytesPerRow: bytesPerRow
  34725. },
  34726. {
  34727. width: width,
  34728. height: height
  34729. }
  34730. );
  34731. const typedArrayType = this._getTypedArrayType( format );
  34732. device.queue.submit( [ encoder.finish() ] );
  34733. await readBuffer.mapAsync( GPUMapMode.READ );
  34734. const buffer = readBuffer.getMappedRange();
  34735. return new typedArrayType( buffer );
  34736. }
  34737. _isEnvironmentTexture( texture ) {
  34738. const mapping = texture.mapping;
  34739. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  34740. }
  34741. _getDefaultTextureGPU( format ) {
  34742. let defaultTexture = this.defaultTexture[ format ];
  34743. if ( defaultTexture === undefined ) {
  34744. const texture = new Texture();
  34745. texture.minFilter = NearestFilter;
  34746. texture.magFilter = NearestFilter;
  34747. this.createTexture( texture, { width: 1, height: 1, format } );
  34748. this.defaultTexture[ format ] = defaultTexture = texture;
  34749. }
  34750. return this.backend.get( defaultTexture ).texture;
  34751. }
  34752. _getDefaultCubeTextureGPU( format ) {
  34753. let defaultCubeTexture = this.defaultTexture[ format ];
  34754. if ( defaultCubeTexture === undefined ) {
  34755. const texture = new CubeTexture();
  34756. texture.minFilter = NearestFilter;
  34757. texture.magFilter = NearestFilter;
  34758. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  34759. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  34760. }
  34761. return this.backend.get( defaultCubeTexture ).texture;
  34762. }
  34763. _getDefaultVideoFrame() {
  34764. let defaultVideoFrame = this.defaultVideoFrame;
  34765. if ( defaultVideoFrame === null ) {
  34766. const init = {
  34767. timestamp: 0,
  34768. codedWidth: 1,
  34769. codedHeight: 1,
  34770. format: 'RGBA',
  34771. };
  34772. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  34773. }
  34774. return defaultVideoFrame;
  34775. }
  34776. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  34777. for ( let i = 0; i < 6; i ++ ) {
  34778. const image = images[ i ];
  34779. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  34780. if ( image.isDataTexture ) {
  34781. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  34782. } else {
  34783. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  34784. }
  34785. }
  34786. }
  34787. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  34788. const device = this.backend.device;
  34789. device.queue.copyExternalImageToTexture(
  34790. {
  34791. source: image
  34792. }, {
  34793. texture: textureGPU,
  34794. mipLevel: 0,
  34795. origin: { x: 0, y: 0, z: originDepth }
  34796. }, {
  34797. width: image.width,
  34798. height: image.height,
  34799. depthOrArrayLayers: 1
  34800. }
  34801. );
  34802. if ( flipY === true ) {
  34803. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  34804. }
  34805. }
  34806. _getPassUtils() {
  34807. let passUtils = this._passUtils;
  34808. if ( passUtils === null ) {
  34809. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  34810. }
  34811. return passUtils;
  34812. }
  34813. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  34814. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  34815. }
  34816. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  34817. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  34818. }
  34819. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  34820. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  34821. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  34822. const device = this.backend.device;
  34823. const data = image.data;
  34824. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  34825. const bytesPerRow = image.width * bytesPerTexel;
  34826. device.queue.writeTexture(
  34827. {
  34828. texture: textureGPU,
  34829. mipLevel: 0,
  34830. origin: { x: 0, y: 0, z: originDepth }
  34831. },
  34832. data,
  34833. {
  34834. offset: image.width * image.height * bytesPerTexel * depth,
  34835. bytesPerRow
  34836. },
  34837. {
  34838. width: image.width,
  34839. height: image.height,
  34840. depthOrArrayLayers: 1
  34841. } );
  34842. if ( flipY === true ) {
  34843. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  34844. }
  34845. }
  34846. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  34847. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  34848. const device = this.backend.device;
  34849. const blockData = this._getBlockData( textureDescriptorGPU.format );
  34850. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  34851. for ( let i = 0; i < mipmaps.length; i ++ ) {
  34852. const mipmap = mipmaps[ i ];
  34853. const width = mipmap.width;
  34854. const height = mipmap.height;
  34855. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  34856. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  34857. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  34858. for ( let j = 0; j < depth; j ++ ) {
  34859. device.queue.writeTexture(
  34860. {
  34861. texture: textureGPU,
  34862. mipLevel: i,
  34863. origin: { x: 0, y: 0, z: j }
  34864. },
  34865. mipmap.data,
  34866. {
  34867. offset: j * bytesPerImage,
  34868. bytesPerRow,
  34869. rowsPerImage: Math.ceil( height / blockData.height )
  34870. },
  34871. {
  34872. width: Math.ceil( width / blockData.width ) * blockData.width,
  34873. height: Math.ceil( height / blockData.height ) * blockData.height,
  34874. depthOrArrayLayers: 1
  34875. }
  34876. );
  34877. }
  34878. }
  34879. }
  34880. _getBlockData( format ) {
  34881. // this method is only relevant for compressed texture formats
  34882. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  34883. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  34884. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  34885. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  34886. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  34887. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  34888. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  34889. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  34890. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  34891. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  34892. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  34893. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  34894. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  34895. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  34896. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  34897. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  34898. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  34899. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  34900. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  34901. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  34902. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  34903. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  34904. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  34905. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  34906. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  34907. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  34908. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  34909. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  34910. }
  34911. _convertAddressMode( value ) {
  34912. let addressMode = GPUAddressMode.ClampToEdge;
  34913. if ( value === RepeatWrapping ) {
  34914. addressMode = GPUAddressMode.Repeat;
  34915. } else if ( value === MirroredRepeatWrapping ) {
  34916. addressMode = GPUAddressMode.MirrorRepeat;
  34917. }
  34918. return addressMode;
  34919. }
  34920. _convertFilterMode( value ) {
  34921. let filterMode = GPUFilterMode.Linear;
  34922. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  34923. filterMode = GPUFilterMode.Nearest;
  34924. }
  34925. return filterMode;
  34926. }
  34927. _getBytesPerTexel( format ) {
  34928. // 8-bit formats
  34929. if ( format === GPUTextureFormat.R8Unorm ||
  34930. format === GPUTextureFormat.R8Snorm ||
  34931. format === GPUTextureFormat.R8Uint ||
  34932. format === GPUTextureFormat.R8Sint ) return 1;
  34933. // 16-bit formats
  34934. if ( format === GPUTextureFormat.R16Uint ||
  34935. format === GPUTextureFormat.R16Sint ||
  34936. format === GPUTextureFormat.R16Float ||
  34937. format === GPUTextureFormat.RG8Unorm ||
  34938. format === GPUTextureFormat.RG8Snorm ||
  34939. format === GPUTextureFormat.RG8Uint ||
  34940. format === GPUTextureFormat.RG8Sint ) return 2;
  34941. // 32-bit formats
  34942. if ( format === GPUTextureFormat.R32Uint ||
  34943. format === GPUTextureFormat.R32Sint ||
  34944. format === GPUTextureFormat.R32Float ||
  34945. format === GPUTextureFormat.RG16Uint ||
  34946. format === GPUTextureFormat.RG16Sint ||
  34947. format === GPUTextureFormat.RG16Float ||
  34948. format === GPUTextureFormat.RGBA8Unorm ||
  34949. format === GPUTextureFormat.RGBA8UnormSRGB ||
  34950. format === GPUTextureFormat.RGBA8Snorm ||
  34951. format === GPUTextureFormat.RGBA8Uint ||
  34952. format === GPUTextureFormat.RGBA8Sint ||
  34953. format === GPUTextureFormat.BGRA8Unorm ||
  34954. format === GPUTextureFormat.BGRA8UnormSRGB ||
  34955. // Packed 32-bit formats
  34956. format === GPUTextureFormat.RGB9E5UFloat ||
  34957. format === GPUTextureFormat.RGB10A2Unorm ||
  34958. format === GPUTextureFormat.RG11B10UFloat ||
  34959. format === GPUTextureFormat.Depth32Float ||
  34960. format === GPUTextureFormat.Depth24Plus ||
  34961. format === GPUTextureFormat.Depth24PlusStencil8 ||
  34962. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  34963. // 64-bit formats
  34964. if ( format === GPUTextureFormat.RG32Uint ||
  34965. format === GPUTextureFormat.RG32Sint ||
  34966. format === GPUTextureFormat.RG32Float ||
  34967. format === GPUTextureFormat.RGBA16Uint ||
  34968. format === GPUTextureFormat.RGBA16Sint ||
  34969. format === GPUTextureFormat.RGBA16Float ) return 8;
  34970. // 128-bit formats
  34971. if ( format === GPUTextureFormat.RGBA32Uint ||
  34972. format === GPUTextureFormat.RGBA32Sint ||
  34973. format === GPUTextureFormat.RGBA32Float ) return 16;
  34974. }
  34975. _getTypedArrayType( format ) {
  34976. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  34977. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  34978. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  34979. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  34980. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  34981. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  34982. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  34983. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  34984. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  34985. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  34986. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  34987. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  34988. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  34989. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  34990. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  34991. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  34992. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  34993. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  34994. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  34995. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  34996. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  34997. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  34998. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  34999. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  35000. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  35001. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  35002. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  35003. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  35004. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  35005. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  35006. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  35007. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  35008. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  35009. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  35010. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  35011. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  35012. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  35013. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  35014. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  35015. }
  35016. _getDimension( texture ) {
  35017. let dimension;
  35018. if ( texture.isData3DTexture ) {
  35019. dimension = GPUTextureDimension.ThreeD;
  35020. } else {
  35021. dimension = GPUTextureDimension.TwoD;
  35022. }
  35023. return dimension;
  35024. }
  35025. }
  35026. function getFormat( texture, device = null ) {
  35027. const format = texture.format;
  35028. const type = texture.type;
  35029. const colorSpace = texture.colorSpace;
  35030. let formatGPU;
  35031. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  35032. switch ( format ) {
  35033. case RGBA_S3TC_DXT1_Format:
  35034. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  35035. break;
  35036. case RGBA_S3TC_DXT3_Format:
  35037. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  35038. break;
  35039. case RGBA_S3TC_DXT5_Format:
  35040. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  35041. break;
  35042. case RGB_ETC2_Format:
  35043. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  35044. break;
  35045. case RGBA_ETC2_EAC_Format:
  35046. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  35047. break;
  35048. case RGBA_ASTC_4x4_Format:
  35049. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  35050. break;
  35051. case RGBA_ASTC_5x4_Format:
  35052. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  35053. break;
  35054. case RGBA_ASTC_5x5_Format:
  35055. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  35056. break;
  35057. case RGBA_ASTC_6x5_Format:
  35058. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  35059. break;
  35060. case RGBA_ASTC_6x6_Format:
  35061. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  35062. break;
  35063. case RGBA_ASTC_8x5_Format:
  35064. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  35065. break;
  35066. case RGBA_ASTC_8x6_Format:
  35067. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  35068. break;
  35069. case RGBA_ASTC_8x8_Format:
  35070. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  35071. break;
  35072. case RGBA_ASTC_10x5_Format:
  35073. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  35074. break;
  35075. case RGBA_ASTC_10x6_Format:
  35076. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  35077. break;
  35078. case RGBA_ASTC_10x8_Format:
  35079. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  35080. break;
  35081. case RGBA_ASTC_10x10_Format:
  35082. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  35083. break;
  35084. case RGBA_ASTC_12x10_Format:
  35085. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  35086. break;
  35087. case RGBA_ASTC_12x12_Format:
  35088. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  35089. break;
  35090. case RGBAFormat:
  35091. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  35092. break;
  35093. default:
  35094. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  35095. }
  35096. } else {
  35097. switch ( format ) {
  35098. case RGBAFormat:
  35099. switch ( type ) {
  35100. case ByteType:
  35101. formatGPU = GPUTextureFormat.RGBA8Snorm;
  35102. break;
  35103. case ShortType:
  35104. formatGPU = GPUTextureFormat.RGBA16Sint;
  35105. break;
  35106. case UnsignedShortType:
  35107. formatGPU = GPUTextureFormat.RGBA16Uint;
  35108. break;
  35109. case UnsignedIntType:
  35110. formatGPU = GPUTextureFormat.RGBA32Uint;
  35111. break;
  35112. case IntType:
  35113. formatGPU = GPUTextureFormat.RGBA32Sint;
  35114. break;
  35115. case UnsignedByteType:
  35116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  35117. break;
  35118. case HalfFloatType:
  35119. formatGPU = GPUTextureFormat.RGBA16Float;
  35120. break;
  35121. case FloatType:
  35122. formatGPU = GPUTextureFormat.RGBA32Float;
  35123. break;
  35124. default:
  35125. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  35126. }
  35127. break;
  35128. case RGBFormat:
  35129. switch ( type ) {
  35130. case UnsignedInt5999Type:
  35131. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  35132. break;
  35133. default:
  35134. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  35135. }
  35136. break;
  35137. case RedFormat:
  35138. switch ( type ) {
  35139. case ByteType:
  35140. formatGPU = GPUTextureFormat.R8Snorm;
  35141. break;
  35142. case ShortType:
  35143. formatGPU = GPUTextureFormat.R16Sint;
  35144. break;
  35145. case UnsignedShortType:
  35146. formatGPU = GPUTextureFormat.R16Uint;
  35147. break;
  35148. case UnsignedIntType:
  35149. formatGPU = GPUTextureFormat.R32Uint;
  35150. break;
  35151. case IntType:
  35152. formatGPU = GPUTextureFormat.R32Sint;
  35153. break;
  35154. case UnsignedByteType:
  35155. formatGPU = GPUTextureFormat.R8Unorm;
  35156. break;
  35157. case HalfFloatType:
  35158. formatGPU = GPUTextureFormat.R16Float;
  35159. break;
  35160. case FloatType:
  35161. formatGPU = GPUTextureFormat.R32Float;
  35162. break;
  35163. default:
  35164. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  35165. }
  35166. break;
  35167. case RGFormat:
  35168. switch ( type ) {
  35169. case ByteType:
  35170. formatGPU = GPUTextureFormat.RG8Snorm;
  35171. break;
  35172. case ShortType:
  35173. formatGPU = GPUTextureFormat.RG16Sint;
  35174. break;
  35175. case UnsignedShortType:
  35176. formatGPU = GPUTextureFormat.RG16Uint;
  35177. break;
  35178. case UnsignedIntType:
  35179. formatGPU = GPUTextureFormat.RG32Uint;
  35180. break;
  35181. case IntType:
  35182. formatGPU = GPUTextureFormat.RG32Sint;
  35183. break;
  35184. case UnsignedByteType:
  35185. formatGPU = GPUTextureFormat.RG8Unorm;
  35186. break;
  35187. case HalfFloatType:
  35188. formatGPU = GPUTextureFormat.RG16Float;
  35189. break;
  35190. case FloatType:
  35191. formatGPU = GPUTextureFormat.RG32Float;
  35192. break;
  35193. default:
  35194. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  35195. }
  35196. break;
  35197. case DepthFormat:
  35198. switch ( type ) {
  35199. case UnsignedShortType:
  35200. formatGPU = GPUTextureFormat.Depth16Unorm;
  35201. break;
  35202. case UnsignedIntType:
  35203. formatGPU = GPUTextureFormat.Depth24Plus;
  35204. break;
  35205. case FloatType:
  35206. formatGPU = GPUTextureFormat.Depth32Float;
  35207. break;
  35208. default:
  35209. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  35210. }
  35211. break;
  35212. case DepthStencilFormat:
  35213. switch ( type ) {
  35214. case UnsignedInt248Type:
  35215. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  35216. break;
  35217. case FloatType:
  35218. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  35219. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  35220. }
  35221. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  35222. break;
  35223. default:
  35224. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  35225. }
  35226. break;
  35227. case RedIntegerFormat:
  35228. switch ( type ) {
  35229. case IntType:
  35230. formatGPU = GPUTextureFormat.R32Sint;
  35231. break;
  35232. case UnsignedIntType:
  35233. formatGPU = GPUTextureFormat.R32Uint;
  35234. break;
  35235. default:
  35236. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  35237. }
  35238. break;
  35239. case RGIntegerFormat:
  35240. switch ( type ) {
  35241. case IntType:
  35242. formatGPU = GPUTextureFormat.RG32Sint;
  35243. break;
  35244. case UnsignedIntType:
  35245. formatGPU = GPUTextureFormat.RG32Uint;
  35246. break;
  35247. default:
  35248. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  35249. }
  35250. break;
  35251. case RGBAIntegerFormat:
  35252. switch ( type ) {
  35253. case IntType:
  35254. formatGPU = GPUTextureFormat.RGBA32Sint;
  35255. break;
  35256. case UnsignedIntType:
  35257. formatGPU = GPUTextureFormat.RGBA32Uint;
  35258. break;
  35259. default:
  35260. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  35261. }
  35262. break;
  35263. default:
  35264. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  35265. }
  35266. }
  35267. return formatGPU;
  35268. }
  35269. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  35270. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  35271. const wgslTypeLib$1 = {
  35272. 'f32': 'float',
  35273. 'i32': 'int',
  35274. 'u32': 'uint',
  35275. 'bool': 'bool',
  35276. 'vec2<f32>': 'vec2',
  35277. 'vec2<i32>': 'ivec2',
  35278. 'vec2<u32>': 'uvec2',
  35279. 'vec2<bool>': 'bvec2',
  35280. 'vec2f': 'vec2',
  35281. 'vec2i': 'ivec2',
  35282. 'vec2u': 'uvec2',
  35283. 'vec2b': 'bvec2',
  35284. 'vec3<f32>': 'vec3',
  35285. 'vec3<i32>': 'ivec3',
  35286. 'vec3<u32>': 'uvec3',
  35287. 'vec3<bool>': 'bvec3',
  35288. 'vec3f': 'vec3',
  35289. 'vec3i': 'ivec3',
  35290. 'vec3u': 'uvec3',
  35291. 'vec3b': 'bvec3',
  35292. 'vec4<f32>': 'vec4',
  35293. 'vec4<i32>': 'ivec4',
  35294. 'vec4<u32>': 'uvec4',
  35295. 'vec4<bool>': 'bvec4',
  35296. 'vec4f': 'vec4',
  35297. 'vec4i': 'ivec4',
  35298. 'vec4u': 'uvec4',
  35299. 'vec4b': 'bvec4',
  35300. 'mat2x2<f32>': 'mat2',
  35301. 'mat2x2f': 'mat2',
  35302. 'mat3x3<f32>': 'mat3',
  35303. 'mat3x3f': 'mat3',
  35304. 'mat4x4<f32>': 'mat4',
  35305. 'mat4x4f': 'mat4',
  35306. 'sampler': 'sampler',
  35307. 'texture_1d': 'texture',
  35308. 'texture_2d': 'texture',
  35309. 'texture_2d_array': 'texture',
  35310. 'texture_multisampled_2d': 'cubeTexture',
  35311. 'texture_depth_2d': 'depthTexture',
  35312. 'texture_depth_multisampled_2d': 'depthTexture',
  35313. 'texture_3d': 'texture3D',
  35314. 'texture_cube': 'cubeTexture',
  35315. 'texture_cube_array': 'cubeTexture',
  35316. 'texture_storage_1d': 'storageTexture',
  35317. 'texture_storage_2d': 'storageTexture',
  35318. 'texture_storage_2d_array': 'storageTexture',
  35319. 'texture_storage_3d': 'storageTexture'
  35320. };
  35321. const parse = ( source ) => {
  35322. source = source.trim();
  35323. const declaration = source.match( declarationRegexp );
  35324. if ( declaration !== null && declaration.length === 4 ) {
  35325. const inputsCode = declaration[ 2 ];
  35326. const propsMatches = [];
  35327. let match = null;
  35328. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  35329. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  35330. }
  35331. // Process matches to correctly pair names and types
  35332. const inputs = [];
  35333. for ( let i = 0; i < propsMatches.length; i ++ ) {
  35334. const { name, type } = propsMatches[ i ];
  35335. let resolvedType = type;
  35336. if ( resolvedType.startsWith( 'ptr' ) ) {
  35337. resolvedType = 'pointer';
  35338. } else {
  35339. if ( resolvedType.startsWith( 'texture' ) ) {
  35340. resolvedType = type.split( '<' )[ 0 ];
  35341. }
  35342. resolvedType = wgslTypeLib$1[ resolvedType ];
  35343. }
  35344. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  35345. }
  35346. const blockCode = source.substring( declaration[ 0 ].length );
  35347. const outputType = declaration[ 3 ] || 'void';
  35348. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35349. const type = wgslTypeLib$1[ outputType ] || outputType;
  35350. return {
  35351. type,
  35352. inputs,
  35353. name,
  35354. inputsCode,
  35355. blockCode,
  35356. outputType
  35357. };
  35358. } else {
  35359. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  35360. }
  35361. };
  35362. /**
  35363. * This class represents a WSL node function.
  35364. *
  35365. * @augments NodeFunction
  35366. */
  35367. class WGSLNodeFunction extends NodeFunction {
  35368. /**
  35369. * Constructs a new WGSL node function.
  35370. *
  35371. * @param {String} source - The WGSL source.
  35372. */
  35373. constructor( source ) {
  35374. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  35375. super( type, inputs, name );
  35376. this.inputsCode = inputsCode;
  35377. this.blockCode = blockCode;
  35378. this.outputType = outputType;
  35379. }
  35380. /**
  35381. * This method returns the WGSL code of the node function.
  35382. *
  35383. * @param {String} [name=this.name] - The function's name.
  35384. * @return {String} The shader code.
  35385. */
  35386. getCode( name = this.name ) {
  35387. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  35388. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  35389. }
  35390. }
  35391. /**
  35392. * A WGSL node parser.
  35393. *
  35394. * @augments NodeParser
  35395. */
  35396. class WGSLNodeParser extends NodeParser {
  35397. /**
  35398. * The method parses the given WGSL code an returns a node function.
  35399. *
  35400. * @param {String} source - The WGSL code.
  35401. * @return {WGSLNodeFunction} A node function.
  35402. */
  35403. parseFunction( source ) {
  35404. return new WGSLNodeFunction( source );
  35405. }
  35406. }
  35407. // GPUShaderStage is not defined in browsers not supporting WebGPU
  35408. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  35409. const accessNames = {
  35410. [ NodeAccess.READ_ONLY ]: 'read',
  35411. [ NodeAccess.WRITE_ONLY ]: 'write',
  35412. [ NodeAccess.READ_WRITE ]: 'read_write'
  35413. };
  35414. const wrapNames = {
  35415. [ RepeatWrapping ]: 'repeat',
  35416. [ ClampToEdgeWrapping ]: 'clamp',
  35417. [ MirroredRepeatWrapping ]: 'mirror'
  35418. };
  35419. const gpuShaderStageLib = {
  35420. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  35421. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  35422. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  35423. };
  35424. const supports = {
  35425. instance: true,
  35426. swizzleAssign: false,
  35427. storageBuffer: true
  35428. };
  35429. const wgslFnOpLib = {
  35430. '^^': 'tsl_xor'
  35431. };
  35432. const wgslTypeLib = {
  35433. float: 'f32',
  35434. int: 'i32',
  35435. uint: 'u32',
  35436. bool: 'bool',
  35437. color: 'vec3<f32>',
  35438. vec2: 'vec2<f32>',
  35439. ivec2: 'vec2<i32>',
  35440. uvec2: 'vec2<u32>',
  35441. bvec2: 'vec2<bool>',
  35442. vec3: 'vec3<f32>',
  35443. ivec3: 'vec3<i32>',
  35444. uvec3: 'vec3<u32>',
  35445. bvec3: 'vec3<bool>',
  35446. vec4: 'vec4<f32>',
  35447. ivec4: 'vec4<i32>',
  35448. uvec4: 'vec4<u32>',
  35449. bvec4: 'vec4<bool>',
  35450. mat2: 'mat2x2<f32>',
  35451. mat3: 'mat3x3<f32>',
  35452. mat4: 'mat4x4<f32>'
  35453. };
  35454. const wgslCodeCache = {};
  35455. const wgslPolyfill = {
  35456. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  35457. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  35458. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  35459. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  35460. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  35461. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  35462. 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 ); }' ),
  35463. 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 ); }' ),
  35464. 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 ); }' ),
  35465. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  35466. 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 ); }' ),
  35467. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  35468. biquadraticTexture: new CodeNode( /* wgsl */`
  35469. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  35470. let res = vec2f( iRes );
  35471. let uvScaled = coord * res;
  35472. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  35473. // https://www.shadertoy.com/view/WtyXRy
  35474. let uv = uvWrapping - 0.5;
  35475. let iuv = floor( uv );
  35476. let f = fract( uv );
  35477. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  35478. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  35479. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  35480. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  35481. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  35482. }
  35483. ` )
  35484. };
  35485. const wgslMethods = {
  35486. dFdx: 'dpdx',
  35487. dFdy: '- dpdy',
  35488. mod_float: 'tsl_mod_float',
  35489. mod_vec2: 'tsl_mod_vec2',
  35490. mod_vec3: 'tsl_mod_vec3',
  35491. mod_vec4: 'tsl_mod_vec4',
  35492. equals_bool: 'tsl_equals_bool',
  35493. equals_bvec2: 'tsl_equals_bvec2',
  35494. equals_bvec3: 'tsl_equals_bvec3',
  35495. equals_bvec4: 'tsl_equals_bvec4',
  35496. inversesqrt: 'inverseSqrt',
  35497. bitcast: 'bitcast<f32>'
  35498. };
  35499. // WebGPU issue: does not support pow() with negative base on Windows
  35500. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  35501. 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 ); }' );
  35502. 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 ] );
  35503. 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 ] );
  35504. 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 ] );
  35505. wgslMethods.pow_float = 'tsl_pow_float';
  35506. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  35507. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  35508. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  35509. }
  35510. //
  35511. let diagnostics = '';
  35512. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  35513. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  35514. }
  35515. //
  35516. class WGSLNodeBuilder extends NodeBuilder {
  35517. constructor( object, renderer ) {
  35518. super( object, renderer, new WGSLNodeParser() );
  35519. this.uniformGroups = {};
  35520. this.builtins = {};
  35521. this.directives = {};
  35522. this.scopedArrays = new Map();
  35523. }
  35524. needsToWorkingColorSpace( texture ) {
  35525. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  35526. }
  35527. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35528. if ( shaderStage === 'fragment' ) {
  35529. if ( depthSnippet ) {
  35530. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  35531. } else {
  35532. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  35533. }
  35534. } else if ( this.isFilteredTexture( texture ) ) {
  35535. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  35536. } else {
  35537. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  35538. }
  35539. }
  35540. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  35541. if ( shaderStage === 'fragment' ) {
  35542. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  35543. } else {
  35544. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  35545. }
  35546. }
  35547. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35548. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  35549. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  35550. } else if ( this.isFilteredTexture( texture ) ) {
  35551. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  35552. } else {
  35553. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  35554. }
  35555. }
  35556. generateWrapFunction( texture ) {
  35557. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  35558. let nodeCode = wgslCodeCache[ functionName ];
  35559. if ( nodeCode === undefined ) {
  35560. const includes = [];
  35561. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  35562. const addWrapSnippet = ( wrap, axis ) => {
  35563. if ( wrap === RepeatWrapping ) {
  35564. includes.push( wgslPolyfill.repeatWrapping_float );
  35565. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  35566. } else if ( wrap === ClampToEdgeWrapping ) {
  35567. includes.push( wgslPolyfill.clampWrapping_float );
  35568. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  35569. } else if ( wrap === MirroredRepeatWrapping ) {
  35570. includes.push( wgslPolyfill.mirrorWrapping_float );
  35571. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  35572. } else {
  35573. code += `\t\tcoord.${ axis }`;
  35574. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  35575. }
  35576. };
  35577. addWrapSnippet( texture.wrapS, 'x' );
  35578. code += ',\n';
  35579. addWrapSnippet( texture.wrapT, 'y' );
  35580. code += '\n\t);\n\n}\n';
  35581. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  35582. }
  35583. nodeCode.build( this );
  35584. return functionName;
  35585. }
  35586. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  35587. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  35588. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  35589. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  35590. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  35591. let textureDimensionsParams;
  35592. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  35593. if ( primarySamples > 1 ) {
  35594. textureDimensionsParams = textureProperty;
  35595. } else {
  35596. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  35597. }
  35598. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  35599. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  35600. }
  35601. return textureDimensionNode.build( this );
  35602. }
  35603. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  35604. this._include( 'biquadraticTexture' );
  35605. const wrapFunction = this.generateWrapFunction( texture );
  35606. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  35607. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  35608. }
  35609. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  35610. const wrapFunction = this.generateWrapFunction( texture );
  35611. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  35612. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  35613. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  35614. }
  35615. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  35616. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  35617. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  35618. } else if ( depthSnippet ) {
  35619. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  35620. } else {
  35621. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  35622. }
  35623. }
  35624. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  35625. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  35626. }
  35627. isSampleCompare( texture ) {
  35628. return texture.isDepthTexture === true && texture.compareFunction !== null;
  35629. }
  35630. isUnfilterable( texture ) {
  35631. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  35632. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  35633. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  35634. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  35635. }
  35636. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35637. let snippet = null;
  35638. if ( texture.isVideoTexture === true ) {
  35639. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  35640. } else if ( this.isUnfilterable( texture ) ) {
  35641. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  35642. } else {
  35643. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  35644. }
  35645. return snippet;
  35646. }
  35647. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35648. if ( shaderStage === 'fragment' ) {
  35649. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  35650. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  35651. } else {
  35652. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  35653. }
  35654. }
  35655. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35656. if ( shaderStage === 'fragment' ) {
  35657. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  35658. } else {
  35659. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  35660. }
  35661. }
  35662. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35663. let snippet = null;
  35664. if ( texture.isVideoTexture === true ) {
  35665. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  35666. } else {
  35667. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  35668. }
  35669. return snippet;
  35670. }
  35671. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35672. if ( shaderStage === 'fragment' ) {
  35673. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  35674. } else {
  35675. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  35676. }
  35677. }
  35678. getPropertyName( node, shaderStage = this.shaderStage ) {
  35679. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  35680. if ( shaderStage === 'vertex' ) {
  35681. return `varyings.${ node.name }`;
  35682. }
  35683. } else if ( node.isNodeUniform === true ) {
  35684. const name = node.name;
  35685. const type = node.type;
  35686. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  35687. return name;
  35688. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  35689. return `NodeBuffer_${ node.id }.${name}`;
  35690. } else {
  35691. return node.groupNode.name + '.' + name;
  35692. }
  35693. }
  35694. return super.getPropertyName( node );
  35695. }
  35696. getOutputStructName() {
  35697. return 'output';
  35698. }
  35699. _getUniformGroupCount( shaderStage ) {
  35700. return Object.keys( this.uniforms[ shaderStage ] ).length;
  35701. }
  35702. getFunctionOperator( op ) {
  35703. const fnOp = wgslFnOpLib[ op ];
  35704. if ( fnOp !== undefined ) {
  35705. this._include( fnOp );
  35706. return fnOp;
  35707. }
  35708. return null;
  35709. }
  35710. getNodeAccess( node, shaderStage ) {
  35711. if ( shaderStage !== 'compute' )
  35712. return NodeAccess.READ_ONLY;
  35713. return node.access;
  35714. }
  35715. getStorageAccess( node, shaderStage ) {
  35716. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  35717. }
  35718. getUniformFromNode( node, type, shaderStage, name = null ) {
  35719. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  35720. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35721. if ( nodeData.uniformGPU === undefined ) {
  35722. let uniformGPU;
  35723. const group = node.groupNode;
  35724. const groupName = group.name;
  35725. const bindings = this.getBindGroupArray( groupName, shaderStage );
  35726. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  35727. let texture = null;
  35728. const access = this.getNodeAccess( node, shaderStage );
  35729. if ( type === 'texture' || type === 'storageTexture' ) {
  35730. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  35731. } else if ( type === 'cubeTexture' ) {
  35732. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  35733. } else if ( type === 'texture3D' ) {
  35734. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  35735. }
  35736. texture.store = node.isStorageTextureNode === true;
  35737. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35738. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  35739. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  35740. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35741. bindings.push( sampler, texture );
  35742. uniformGPU = [ sampler, texture ];
  35743. } else {
  35744. bindings.push( texture );
  35745. uniformGPU = [ texture ];
  35746. }
  35747. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  35748. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  35749. const buffer = new bufferClass( node, group );
  35750. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35751. bindings.push( buffer );
  35752. uniformGPU = buffer;
  35753. } else {
  35754. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  35755. let uniformsGroup = uniformsStage[ groupName ];
  35756. if ( uniformsGroup === undefined ) {
  35757. uniformsGroup = new NodeUniformsGroup( groupName, group );
  35758. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35759. uniformsStage[ groupName ] = uniformsGroup;
  35760. bindings.push( uniformsGroup );
  35761. }
  35762. uniformGPU = this.getNodeUniform( uniformNode, type );
  35763. uniformsGroup.addUniform( uniformGPU );
  35764. }
  35765. nodeData.uniformGPU = uniformGPU;
  35766. }
  35767. return uniformNode;
  35768. }
  35769. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  35770. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  35771. if ( map.has( name ) === false ) {
  35772. map.set( name, {
  35773. name,
  35774. property,
  35775. type
  35776. } );
  35777. }
  35778. return property;
  35779. }
  35780. hasBuiltin( name, shaderStage = this.shaderStage ) {
  35781. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  35782. }
  35783. getVertexIndex() {
  35784. if ( this.shaderStage === 'vertex' ) {
  35785. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  35786. }
  35787. return 'vertexIndex';
  35788. }
  35789. buildFunctionCode( shaderNode ) {
  35790. const layout = shaderNode.layout;
  35791. const flowData = this.flowShaderNode( shaderNode );
  35792. const parameters = [];
  35793. for ( const input of layout.inputs ) {
  35794. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  35795. }
  35796. //
  35797. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  35798. ${ flowData.vars }
  35799. ${ flowData.code }
  35800. `;
  35801. if ( flowData.result ) {
  35802. code += `\treturn ${ flowData.result };\n`;
  35803. }
  35804. code += '\n}\n';
  35805. //
  35806. return code;
  35807. }
  35808. getInstanceIndex() {
  35809. if ( this.shaderStage === 'vertex' ) {
  35810. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  35811. }
  35812. return 'instanceIndex';
  35813. }
  35814. getInvocationLocalIndex() {
  35815. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  35816. }
  35817. getSubgroupSize() {
  35818. this.enableSubGroups();
  35819. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  35820. }
  35821. getInvocationSubgroupIndex() {
  35822. this.enableSubGroups();
  35823. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  35824. }
  35825. getSubgroupIndex() {
  35826. this.enableSubGroups();
  35827. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  35828. }
  35829. getDrawIndex() {
  35830. return null;
  35831. }
  35832. getFrontFacing() {
  35833. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  35834. }
  35835. getFragCoord() {
  35836. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  35837. }
  35838. getFragDepth() {
  35839. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  35840. }
  35841. getClipDistance() {
  35842. return 'varyings.hw_clip_distances';
  35843. }
  35844. isFlipY() {
  35845. return false;
  35846. }
  35847. enableDirective( name, shaderStage = this.shaderStage ) {
  35848. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  35849. stage.add( name );
  35850. }
  35851. getDirectives( shaderStage ) {
  35852. const snippets = [];
  35853. const directives = this.directives[ shaderStage ];
  35854. if ( directives !== undefined ) {
  35855. for ( const directive of directives ) {
  35856. snippets.push( `enable ${directive};` );
  35857. }
  35858. }
  35859. return snippets.join( '\n' );
  35860. }
  35861. enableSubGroups() {
  35862. this.enableDirective( 'subgroups' );
  35863. }
  35864. enableSubgroupsF16() {
  35865. this.enableDirective( 'subgroups-f16' );
  35866. }
  35867. enableClipDistances() {
  35868. this.enableDirective( 'clip_distances' );
  35869. }
  35870. enableShaderF16() {
  35871. this.enableDirective( 'f16' );
  35872. }
  35873. enableDualSourceBlending() {
  35874. this.enableDirective( 'dual_source_blending' );
  35875. }
  35876. enableHardwareClipping( planeCount ) {
  35877. this.enableClipDistances();
  35878. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  35879. }
  35880. getBuiltins( shaderStage ) {
  35881. const snippets = [];
  35882. const builtins = this.builtins[ shaderStage ];
  35883. if ( builtins !== undefined ) {
  35884. for ( const { name, property, type } of builtins.values() ) {
  35885. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  35886. }
  35887. }
  35888. return snippets.join( ',\n\t' );
  35889. }
  35890. getScopedArray( name, scope, bufferType, bufferCount ) {
  35891. if ( this.scopedArrays.has( name ) === false ) {
  35892. this.scopedArrays.set( name, {
  35893. name,
  35894. scope,
  35895. bufferType,
  35896. bufferCount
  35897. } );
  35898. }
  35899. return name;
  35900. }
  35901. getScopedArrays( shaderStage ) {
  35902. if ( shaderStage !== 'compute' ) {
  35903. return;
  35904. }
  35905. const snippets = [];
  35906. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  35907. const type = this.getType( bufferType );
  35908. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  35909. }
  35910. return snippets.join( '\n' );
  35911. }
  35912. getAttributes( shaderStage ) {
  35913. const snippets = [];
  35914. if ( shaderStage === 'compute' ) {
  35915. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  35916. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  35917. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  35918. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  35919. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  35920. this.enableDirective( 'subgroups', shaderStage );
  35921. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  35922. }
  35923. }
  35924. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35925. const builtins = this.getBuiltins( 'attribute' );
  35926. if ( builtins ) snippets.push( builtins );
  35927. const attributes = this.getAttributesArray();
  35928. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  35929. const attribute = attributes[ index ];
  35930. const name = attribute.name;
  35931. const type = this.getType( attribute.type );
  35932. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  35933. }
  35934. }
  35935. return snippets.join( ',\n\t' );
  35936. }
  35937. getStructMembers( struct ) {
  35938. const snippets = [];
  35939. const members = struct.getMemberTypes();
  35940. for ( let i = 0; i < members.length; i ++ ) {
  35941. const member = members[ i ];
  35942. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  35943. }
  35944. const builtins = this.getBuiltins( 'output' );
  35945. if ( builtins ) snippets.push( '\t' + builtins );
  35946. return snippets.join( ',\n' );
  35947. }
  35948. getStructs( shaderStage ) {
  35949. const snippets = [];
  35950. const structs = this.structs[ shaderStage ];
  35951. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  35952. const struct = structs[ index ];
  35953. const name = struct.name;
  35954. let snippet = `\struct ${ name } {\n`;
  35955. snippet += this.getStructMembers( struct );
  35956. snippet += '\n}';
  35957. snippets.push( snippet );
  35958. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  35959. }
  35960. return snippets.join( '\n\n' );
  35961. }
  35962. getVar( type, name ) {
  35963. return `var ${ name } : ${ this.getType( type ) }`;
  35964. }
  35965. getVars( shaderStage ) {
  35966. const snippets = [];
  35967. const vars = this.vars[ shaderStage ];
  35968. if ( vars !== undefined ) {
  35969. for ( const variable of vars ) {
  35970. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  35971. }
  35972. }
  35973. return `\n${ snippets.join( '\n' ) }\n`;
  35974. }
  35975. getVaryings( shaderStage ) {
  35976. const snippets = [];
  35977. if ( shaderStage === 'vertex' ) {
  35978. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  35979. }
  35980. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  35981. const varyings = this.varyings;
  35982. const vars = this.vars[ shaderStage ];
  35983. for ( let index = 0; index < varyings.length; index ++ ) {
  35984. const varying = varyings[ index ];
  35985. if ( varying.needsInterpolation ) {
  35986. let attributesSnippet = `@location( ${index} )`;
  35987. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  35988. attributesSnippet += ' @interpolate( flat )';
  35989. }
  35990. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  35991. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  35992. vars.push( varying );
  35993. }
  35994. }
  35995. }
  35996. const builtins = this.getBuiltins( shaderStage );
  35997. if ( builtins ) snippets.push( builtins );
  35998. const code = snippets.join( ',\n\t' );
  35999. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  36000. }
  36001. getUniforms( shaderStage ) {
  36002. const uniforms = this.uniforms[ shaderStage ];
  36003. const bindingSnippets = [];
  36004. const bufferSnippets = [];
  36005. const structSnippets = [];
  36006. const uniformGroups = {};
  36007. for ( const uniform of uniforms ) {
  36008. const groupName = uniform.groupNode.name;
  36009. const uniformIndexes = this.bindingsIndexes[ groupName ];
  36010. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  36011. const texture = uniform.node.value;
  36012. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  36013. if ( this.isSampleCompare( texture ) ) {
  36014. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  36015. } else {
  36016. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  36017. }
  36018. }
  36019. let textureType;
  36020. let multisampled = '';
  36021. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  36022. if ( primarySamples > 1 ) {
  36023. multisampled = '_multisampled';
  36024. }
  36025. if ( texture.isCubeTexture === true ) {
  36026. textureType = 'texture_cube<f32>';
  36027. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  36028. textureType = 'texture_2d_array<f32>';
  36029. } else if ( texture.isDepthTexture === true ) {
  36030. textureType = `texture_depth${multisampled}_2d`;
  36031. } else if ( texture.isVideoTexture === true ) {
  36032. textureType = 'texture_external';
  36033. } else if ( texture.isData3DTexture === true ) {
  36034. textureType = 'texture_3d<f32>';
  36035. } else if ( uniform.node.isStorageTextureNode === true ) {
  36036. const format = getFormat( texture );
  36037. const access = this.getStorageAccess( uniform.node, shaderStage );
  36038. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  36039. } else {
  36040. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  36041. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  36042. }
  36043. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  36044. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  36045. const bufferNode = uniform.node;
  36046. const bufferType = this.getType( bufferNode.bufferType );
  36047. const bufferCount = bufferNode.bufferCount;
  36048. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  36049. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  36050. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  36051. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  36052. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  36053. } else {
  36054. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  36055. const groupName = uniform.groupNode.name;
  36056. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  36057. index: uniformIndexes.binding ++,
  36058. id: uniformIndexes.group,
  36059. snippets: []
  36060. } );
  36061. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  36062. }
  36063. }
  36064. for ( const name in uniformGroups ) {
  36065. const group = uniformGroups[ name ];
  36066. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  36067. }
  36068. let code = bindingSnippets.join( '\n' );
  36069. code += bufferSnippets.join( '\n' );
  36070. code += structSnippets.join( '\n' );
  36071. return code;
  36072. }
  36073. buildCode() {
  36074. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  36075. this.sortBindingGroups();
  36076. for ( const shaderStage in shadersData ) {
  36077. const stageData = shadersData[ shaderStage ];
  36078. stageData.uniforms = this.getUniforms( shaderStage );
  36079. stageData.attributes = this.getAttributes( shaderStage );
  36080. stageData.varyings = this.getVaryings( shaderStage );
  36081. stageData.structs = this.getStructs( shaderStage );
  36082. stageData.vars = this.getVars( shaderStage );
  36083. stageData.codes = this.getCodes( shaderStage );
  36084. stageData.directives = this.getDirectives( shaderStage );
  36085. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  36086. //
  36087. let flow = '// code\n\n';
  36088. flow += this.flowCode[ shaderStage ];
  36089. const flowNodes = this.flowNodes[ shaderStage ];
  36090. const mainNode = flowNodes[ flowNodes.length - 1 ];
  36091. const outputNode = mainNode.outputNode;
  36092. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  36093. for ( const node of flowNodes ) {
  36094. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  36095. const slotName = node.name;
  36096. if ( slotName ) {
  36097. if ( flow.length > 0 ) flow += '\n';
  36098. flow += `\t// flow -> ${ slotName }\n\t`;
  36099. }
  36100. flow += `${ flowSlotData.code }\n\t`;
  36101. if ( node === mainNode && shaderStage !== 'compute' ) {
  36102. flow += '// result\n\n\t';
  36103. if ( shaderStage === 'vertex' ) {
  36104. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  36105. } else if ( shaderStage === 'fragment' ) {
  36106. if ( isOutputStruct ) {
  36107. stageData.returnType = outputNode.nodeType;
  36108. flow += `return ${ flowSlotData.result };`;
  36109. } else {
  36110. let structSnippet = '\t@location(0) color: vec4<f32>';
  36111. const builtins = this.getBuiltins( 'output' );
  36112. if ( builtins ) structSnippet += ',\n\t' + builtins;
  36113. stageData.returnType = 'OutputStruct';
  36114. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  36115. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  36116. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  36117. }
  36118. }
  36119. }
  36120. }
  36121. stageData.flow = flow;
  36122. }
  36123. if ( this.material !== null ) {
  36124. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  36125. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  36126. } else {
  36127. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  36128. }
  36129. }
  36130. getMethod( method, output = null ) {
  36131. let wgslMethod;
  36132. if ( output !== null ) {
  36133. wgslMethod = this._getWGSLMethod( method + '_' + output );
  36134. }
  36135. if ( wgslMethod === undefined ) {
  36136. wgslMethod = this._getWGSLMethod( method );
  36137. }
  36138. return wgslMethod || method;
  36139. }
  36140. getType( type ) {
  36141. return wgslTypeLib[ type ] || type;
  36142. }
  36143. isAvailable( name ) {
  36144. let result = supports[ name ];
  36145. if ( result === undefined ) {
  36146. if ( name === 'float32Filterable' ) {
  36147. result = this.renderer.hasFeature( 'float32-filterable' );
  36148. } else if ( name === 'clipDistance' ) {
  36149. result = this.renderer.hasFeature( 'clip-distances' );
  36150. }
  36151. supports[ name ] = result;
  36152. }
  36153. return result;
  36154. }
  36155. _getWGSLMethod( method ) {
  36156. if ( wgslPolyfill[ method ] !== undefined ) {
  36157. this._include( method );
  36158. }
  36159. return wgslMethods[ method ];
  36160. }
  36161. _include( name ) {
  36162. const codeNode = wgslPolyfill[ name ];
  36163. codeNode.build( this );
  36164. if ( this.currentFunctionNode !== null ) {
  36165. this.currentFunctionNode.includes.push( codeNode );
  36166. }
  36167. return codeNode;
  36168. }
  36169. _getWGSLVertexCode( shaderData ) {
  36170. return `${ this.getSignature() }
  36171. // directives
  36172. ${shaderData.directives}
  36173. // uniforms
  36174. ${shaderData.uniforms}
  36175. // varyings
  36176. ${shaderData.varyings}
  36177. var<private> varyings : VaryingsStruct;
  36178. // codes
  36179. ${shaderData.codes}
  36180. @vertex
  36181. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  36182. // vars
  36183. ${shaderData.vars}
  36184. // flow
  36185. ${shaderData.flow}
  36186. return varyings;
  36187. }
  36188. `;
  36189. }
  36190. _getWGSLFragmentCode( shaderData ) {
  36191. return `${ this.getSignature() }
  36192. // global
  36193. ${ diagnostics }
  36194. // uniforms
  36195. ${shaderData.uniforms}
  36196. // structs
  36197. ${shaderData.structs}
  36198. // codes
  36199. ${shaderData.codes}
  36200. @fragment
  36201. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  36202. // vars
  36203. ${shaderData.vars}
  36204. // flow
  36205. ${shaderData.flow}
  36206. }
  36207. `;
  36208. }
  36209. _getWGSLComputeCode( shaderData, workgroupSize ) {
  36210. return `${ this.getSignature() }
  36211. // directives
  36212. ${shaderData.directives}
  36213. // system
  36214. var<private> instanceIndex : u32;
  36215. // locals
  36216. ${shaderData.scopedArrays}
  36217. // uniforms
  36218. ${shaderData.uniforms}
  36219. // codes
  36220. ${shaderData.codes}
  36221. @compute @workgroup_size( ${workgroupSize} )
  36222. fn main( ${shaderData.attributes} ) {
  36223. // system
  36224. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  36225. // vars
  36226. ${shaderData.vars}
  36227. // flow
  36228. ${shaderData.flow}
  36229. }
  36230. `;
  36231. }
  36232. _getWGSLStruct( name, vars ) {
  36233. return `
  36234. struct ${name} {
  36235. ${vars}
  36236. };`;
  36237. }
  36238. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  36239. const structName = name + 'Struct';
  36240. const structSnippet = this._getWGSLStruct( structName, vars );
  36241. return `${structSnippet}
  36242. @binding( ${binding} ) @group( ${group} )
  36243. var<${access}> ${name} : ${structName};`;
  36244. }
  36245. }
  36246. class WebGPUUtils {
  36247. constructor( backend ) {
  36248. this.backend = backend;
  36249. }
  36250. getCurrentDepthStencilFormat( renderContext ) {
  36251. let format;
  36252. if ( renderContext.depthTexture !== null ) {
  36253. format = this.getTextureFormatGPU( renderContext.depthTexture );
  36254. } else if ( renderContext.depth && renderContext.stencil ) {
  36255. format = GPUTextureFormat.Depth24PlusStencil8;
  36256. } else if ( renderContext.depth ) {
  36257. format = GPUTextureFormat.Depth24Plus;
  36258. }
  36259. return format;
  36260. }
  36261. getTextureFormatGPU( texture ) {
  36262. return this.backend.get( texture ).format;
  36263. }
  36264. getTextureSampleData( texture ) {
  36265. let samples;
  36266. if ( texture.isFramebufferTexture ) {
  36267. samples = 1;
  36268. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  36269. const renderer = this.backend.renderer;
  36270. const renderTarget = renderer.getRenderTarget();
  36271. samples = renderTarget ? renderTarget.samples : renderer.samples;
  36272. } else if ( texture.renderTarget ) {
  36273. samples = texture.renderTarget.samples;
  36274. }
  36275. samples = samples || 1;
  36276. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  36277. const primarySamples = isMSAA ? 1 : samples;
  36278. return { samples, primarySamples, isMSAA };
  36279. }
  36280. getCurrentColorFormat( renderContext ) {
  36281. let format;
  36282. if ( renderContext.textures !== null ) {
  36283. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  36284. } else {
  36285. format = this.getPreferredCanvasFormat(); // default context format
  36286. }
  36287. return format;
  36288. }
  36289. getCurrentColorSpace( renderContext ) {
  36290. if ( renderContext.textures !== null ) {
  36291. return renderContext.textures[ 0 ].colorSpace;
  36292. }
  36293. return this.backend.renderer.outputColorSpace;
  36294. }
  36295. getPrimitiveTopology( object, material ) {
  36296. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  36297. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  36298. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  36299. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  36300. }
  36301. getSampleCount( sampleCount ) {
  36302. let count = 1;
  36303. if ( sampleCount > 1 ) {
  36304. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  36305. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  36306. if ( count === 2 ) {
  36307. count = 4;
  36308. }
  36309. }
  36310. return count;
  36311. }
  36312. getSampleCountRenderContext( renderContext ) {
  36313. if ( renderContext.textures !== null ) {
  36314. return this.getSampleCount( renderContext.sampleCount );
  36315. }
  36316. return this.getSampleCount( this.backend.renderer.samples );
  36317. }
  36318. getPreferredCanvasFormat() {
  36319. // TODO: Remove this check when Quest 34.5 is out
  36320. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  36321. if ( navigator.userAgent.includes( 'Quest' ) ) {
  36322. return GPUTextureFormat.BGRA8Unorm;
  36323. } else {
  36324. return navigator.gpu.getPreferredCanvasFormat();
  36325. }
  36326. }
  36327. }
  36328. const typedArraysToVertexFormatPrefix = new Map( [
  36329. [ Int8Array, [ 'sint8', 'snorm8' ]],
  36330. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  36331. [ Int16Array, [ 'sint16', 'snorm16' ]],
  36332. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  36333. [ Int32Array, [ 'sint32', 'snorm32' ]],
  36334. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  36335. [ Float32Array, [ 'float32', ]],
  36336. ] );
  36337. const typedAttributeToVertexFormatPrefix = new Map( [
  36338. [ Float16BufferAttribute, [ 'float16', ]],
  36339. ] );
  36340. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  36341. [ Int32Array, 'sint32' ],
  36342. [ Int16Array, 'sint32' ], // patch for INT16
  36343. [ Uint32Array, 'uint32' ],
  36344. [ Uint16Array, 'uint32' ], // patch for UINT16
  36345. [ Float32Array, 'float32' ]
  36346. ] );
  36347. class WebGPUAttributeUtils {
  36348. constructor( backend ) {
  36349. this.backend = backend;
  36350. }
  36351. createAttribute( attribute, usage ) {
  36352. const bufferAttribute = this._getBufferAttribute( attribute );
  36353. const backend = this.backend;
  36354. const bufferData = backend.get( bufferAttribute );
  36355. let buffer = bufferData.buffer;
  36356. if ( buffer === undefined ) {
  36357. const device = backend.device;
  36358. let array = bufferAttribute.array;
  36359. // patch for INT16 and UINT16
  36360. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  36361. const tempArray = new Uint32Array( array.length );
  36362. for ( let i = 0; i < array.length; i ++ ) {
  36363. tempArray[ i ] = array[ i ];
  36364. }
  36365. array = tempArray;
  36366. }
  36367. bufferAttribute.array = array;
  36368. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  36369. array = new array.constructor( bufferAttribute.count * 4 );
  36370. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  36371. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  36372. }
  36373. // Update BufferAttribute
  36374. bufferAttribute.itemSize = 4;
  36375. bufferAttribute.array = array;
  36376. }
  36377. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  36378. buffer = device.createBuffer( {
  36379. label: bufferAttribute.name,
  36380. size: size,
  36381. usage: usage,
  36382. mappedAtCreation: true
  36383. } );
  36384. new array.constructor( buffer.getMappedRange() ).set( array );
  36385. buffer.unmap();
  36386. bufferData.buffer = buffer;
  36387. }
  36388. }
  36389. updateAttribute( attribute ) {
  36390. const bufferAttribute = this._getBufferAttribute( attribute );
  36391. const backend = this.backend;
  36392. const device = backend.device;
  36393. const buffer = backend.get( bufferAttribute ).buffer;
  36394. const array = bufferAttribute.array;
  36395. const isTypedArray = this._isTypedArray( array );
  36396. const updateRanges = bufferAttribute.updateRanges;
  36397. if ( updateRanges.length === 0 ) {
  36398. // Not using update ranges
  36399. device.queue.writeBuffer(
  36400. buffer,
  36401. 0,
  36402. array,
  36403. 0
  36404. );
  36405. } else {
  36406. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  36407. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  36408. const range = updateRanges[ i ];
  36409. const dataOffset = range.start * byteOffsetFactor;
  36410. const size = range.count * byteOffsetFactor;
  36411. device.queue.writeBuffer(
  36412. buffer,
  36413. 0,
  36414. array,
  36415. dataOffset,
  36416. size
  36417. );
  36418. }
  36419. bufferAttribute.clearUpdateRanges();
  36420. }
  36421. }
  36422. createShaderVertexBuffers( renderObject ) {
  36423. const attributes = renderObject.getAttributes();
  36424. const vertexBuffers = new Map();
  36425. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  36426. const geometryAttribute = attributes[ slot ];
  36427. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  36428. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  36429. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  36430. if ( vertexBufferLayout === undefined ) {
  36431. let arrayStride, stepMode;
  36432. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  36433. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  36434. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  36435. } else {
  36436. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  36437. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  36438. }
  36439. // patch for INT16 and UINT16
  36440. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  36441. arrayStride = 4;
  36442. }
  36443. vertexBufferLayout = {
  36444. arrayStride,
  36445. attributes: [],
  36446. stepMode
  36447. };
  36448. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  36449. }
  36450. const format = this._getVertexFormat( geometryAttribute );
  36451. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  36452. vertexBufferLayout.attributes.push( {
  36453. shaderLocation: slot,
  36454. offset,
  36455. format
  36456. } );
  36457. }
  36458. return Array.from( vertexBuffers.values() );
  36459. }
  36460. destroyAttribute( attribute ) {
  36461. const backend = this.backend;
  36462. const data = backend.get( this._getBufferAttribute( attribute ) );
  36463. data.buffer.destroy();
  36464. backend.delete( attribute );
  36465. }
  36466. async getArrayBufferAsync( attribute ) {
  36467. const backend = this.backend;
  36468. const device = backend.device;
  36469. const data = backend.get( this._getBufferAttribute( attribute ) );
  36470. const bufferGPU = data.buffer;
  36471. const size = bufferGPU.size;
  36472. const readBufferGPU = device.createBuffer( {
  36473. label: `${ attribute.name }_readback`,
  36474. size,
  36475. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  36476. } );
  36477. const cmdEncoder = device.createCommandEncoder( {
  36478. label: `readback_encoder_${ attribute.name }`
  36479. } );
  36480. cmdEncoder.copyBufferToBuffer(
  36481. bufferGPU,
  36482. 0,
  36483. readBufferGPU,
  36484. 0,
  36485. size
  36486. );
  36487. const gpuCommands = cmdEncoder.finish();
  36488. device.queue.submit( [ gpuCommands ] );
  36489. await readBufferGPU.mapAsync( GPUMapMode.READ );
  36490. const arrayBuffer = readBufferGPU.getMappedRange();
  36491. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  36492. readBufferGPU.unmap();
  36493. return dstBuffer.buffer;
  36494. }
  36495. _getVertexFormat( geometryAttribute ) {
  36496. const { itemSize, normalized } = geometryAttribute;
  36497. const ArrayType = geometryAttribute.array.constructor;
  36498. const AttributeType = geometryAttribute.constructor;
  36499. let format;
  36500. if ( itemSize === 1 ) {
  36501. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  36502. } else {
  36503. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  36504. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  36505. if ( prefix ) {
  36506. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  36507. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  36508. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  36509. if ( paddedItemSize % 1 ) {
  36510. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  36511. }
  36512. format = `${prefix}x${paddedItemSize}`;
  36513. }
  36514. }
  36515. if ( ! format ) {
  36516. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  36517. }
  36518. return format;
  36519. }
  36520. _isTypedArray( array ) {
  36521. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  36522. }
  36523. _getBufferAttribute( attribute ) {
  36524. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  36525. return attribute;
  36526. }
  36527. }
  36528. class WebGPUBindingUtils {
  36529. constructor( backend ) {
  36530. this.backend = backend;
  36531. this.bindGroupLayoutCache = new WeakMap();
  36532. }
  36533. createBindingsLayout( bindGroup ) {
  36534. const backend = this.backend;
  36535. const device = backend.device;
  36536. const entries = [];
  36537. let index = 0;
  36538. for ( const binding of bindGroup.bindings ) {
  36539. const bindingGPU = {
  36540. binding: index ++,
  36541. visibility: binding.visibility
  36542. };
  36543. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  36544. const buffer = {}; // GPUBufferBindingLayout
  36545. if ( binding.isStorageBuffer ) {
  36546. if ( binding.visibility & 4 ) {
  36547. // compute
  36548. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  36549. buffer.type = GPUBufferBindingType.Storage;
  36550. } else {
  36551. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  36552. }
  36553. } else {
  36554. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  36555. }
  36556. }
  36557. bindingGPU.buffer = buffer;
  36558. } else if ( binding.isSampler ) {
  36559. const sampler = {}; // GPUSamplerBindingLayout
  36560. if ( binding.texture.isDepthTexture ) {
  36561. if ( binding.texture.compareFunction !== null ) {
  36562. sampler.type = 'comparison';
  36563. }
  36564. }
  36565. bindingGPU.sampler = sampler;
  36566. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  36567. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  36568. } else if ( binding.isSampledTexture && binding.store ) {
  36569. const storageTexture = {}; // GPUStorageTextureBindingLayout
  36570. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  36571. const access = binding.access;
  36572. if ( access === NodeAccess.READ_WRITE ) {
  36573. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  36574. } else if ( access === NodeAccess.WRITE_ONLY ) {
  36575. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  36576. } else {
  36577. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  36578. }
  36579. bindingGPU.storageTexture = storageTexture;
  36580. } else if ( binding.isSampledTexture ) {
  36581. const texture = {}; // GPUTextureBindingLayout
  36582. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  36583. if ( primarySamples > 1 ) {
  36584. texture.multisampled = true;
  36585. if ( ! binding.texture.isDepthTexture ) {
  36586. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  36587. }
  36588. }
  36589. if ( binding.texture.isDepthTexture ) {
  36590. texture.sampleType = GPUTextureSampleType.Depth;
  36591. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  36592. const type = binding.texture.type;
  36593. if ( type === IntType ) {
  36594. texture.sampleType = GPUTextureSampleType.SInt;
  36595. } else if ( type === UnsignedIntType ) {
  36596. texture.sampleType = GPUTextureSampleType.UInt;
  36597. } else if ( type === FloatType ) {
  36598. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  36599. texture.sampleType = GPUTextureSampleType.Float;
  36600. } else {
  36601. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  36602. }
  36603. }
  36604. }
  36605. if ( binding.isSampledCubeTexture ) {
  36606. texture.viewDimension = GPUTextureViewDimension.Cube;
  36607. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  36608. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  36609. } else if ( binding.isSampledTexture3D ) {
  36610. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  36611. }
  36612. bindingGPU.texture = texture;
  36613. } else {
  36614. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  36615. }
  36616. entries.push( bindingGPU );
  36617. }
  36618. return device.createBindGroupLayout( { entries } );
  36619. }
  36620. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  36621. const { backend, bindGroupLayoutCache } = this;
  36622. const bindingsData = backend.get( bindGroup );
  36623. // setup (static) binding layout and (dynamic) binding group
  36624. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  36625. if ( bindLayoutGPU === undefined ) {
  36626. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  36627. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  36628. }
  36629. let bindGroupGPU;
  36630. if ( cacheIndex > 0 ) {
  36631. if ( bindingsData.groups === undefined ) {
  36632. bindingsData.groups = [];
  36633. bindingsData.versions = [];
  36634. }
  36635. if ( bindingsData.versions[ cacheIndex ] === version ) {
  36636. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  36637. }
  36638. }
  36639. if ( bindGroupGPU === undefined ) {
  36640. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  36641. if ( cacheIndex > 0 ) {
  36642. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  36643. bindingsData.versions[ cacheIndex ] = version;
  36644. }
  36645. }
  36646. bindingsData.group = bindGroupGPU;
  36647. bindingsData.layout = bindLayoutGPU;
  36648. }
  36649. updateBinding( binding ) {
  36650. const backend = this.backend;
  36651. const device = backend.device;
  36652. const buffer = binding.buffer;
  36653. const bufferGPU = backend.get( binding ).buffer;
  36654. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  36655. }
  36656. createBindGroup( bindGroup, layoutGPU ) {
  36657. const backend = this.backend;
  36658. const device = backend.device;
  36659. let bindingPoint = 0;
  36660. const entriesGPU = [];
  36661. for ( const binding of bindGroup.bindings ) {
  36662. if ( binding.isUniformBuffer ) {
  36663. const bindingData = backend.get( binding );
  36664. if ( bindingData.buffer === undefined ) {
  36665. const byteLength = binding.byteLength;
  36666. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  36667. const bufferGPU = device.createBuffer( {
  36668. label: 'bindingBuffer_' + binding.name,
  36669. size: byteLength,
  36670. usage: usage
  36671. } );
  36672. bindingData.buffer = bufferGPU;
  36673. }
  36674. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  36675. } else if ( binding.isStorageBuffer ) {
  36676. const bindingData = backend.get( binding );
  36677. if ( bindingData.buffer === undefined ) {
  36678. const attribute = binding.attribute;
  36679. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  36680. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  36681. bindingData.buffer = backend.get( attribute ).buffer;
  36682. }
  36683. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  36684. } else if ( binding.isSampler ) {
  36685. const textureGPU = backend.get( binding.texture );
  36686. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  36687. } else if ( binding.isSampledTexture ) {
  36688. const textureData = backend.get( binding.texture );
  36689. let resourceGPU;
  36690. if ( textureData.externalTexture !== undefined ) {
  36691. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  36692. } else {
  36693. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  36694. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  36695. resourceGPU = textureData[ propertyName ];
  36696. if ( resourceGPU === undefined ) {
  36697. const aspectGPU = GPUTextureAspect.All;
  36698. let dimensionViewGPU;
  36699. if ( binding.isSampledCubeTexture ) {
  36700. dimensionViewGPU = GPUTextureViewDimension.Cube;
  36701. } else if ( binding.isSampledTexture3D ) {
  36702. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  36703. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  36704. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  36705. } else {
  36706. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  36707. }
  36708. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  36709. }
  36710. }
  36711. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  36712. }
  36713. bindingPoint ++;
  36714. }
  36715. return device.createBindGroup( {
  36716. label: 'bindGroup_' + bindGroup.name,
  36717. layout: layoutGPU,
  36718. entries: entriesGPU
  36719. } );
  36720. }
  36721. }
  36722. class WebGPUPipelineUtils {
  36723. constructor( backend ) {
  36724. this.backend = backend;
  36725. }
  36726. _getSampleCount( renderObjectContext ) {
  36727. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  36728. }
  36729. createRenderPipeline( renderObject, promises ) {
  36730. const { object, material, geometry, pipeline } = renderObject;
  36731. const { vertexProgram, fragmentProgram } = pipeline;
  36732. const backend = this.backend;
  36733. const device = backend.device;
  36734. const utils = backend.utils;
  36735. const pipelineData = backend.get( pipeline );
  36736. // bind group layouts
  36737. const bindGroupLayouts = [];
  36738. for ( const bindGroup of renderObject.getBindings() ) {
  36739. const bindingsData = backend.get( bindGroup );
  36740. bindGroupLayouts.push( bindingsData.layout );
  36741. }
  36742. // vertex buffers
  36743. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  36744. // blending
  36745. let blending;
  36746. if ( material.transparent === true && material.blending !== NoBlending ) {
  36747. blending = this._getBlending( material );
  36748. }
  36749. // stencil
  36750. let stencilFront = {};
  36751. if ( material.stencilWrite === true ) {
  36752. stencilFront = {
  36753. compare: this._getStencilCompare( material ),
  36754. failOp: this._getStencilOperation( material.stencilFail ),
  36755. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  36756. passOp: this._getStencilOperation( material.stencilZPass )
  36757. };
  36758. }
  36759. const colorWriteMask = this._getColorWriteMask( material );
  36760. const targets = [];
  36761. if ( renderObject.context.textures !== null ) {
  36762. const textures = renderObject.context.textures;
  36763. for ( let i = 0; i < textures.length; i ++ ) {
  36764. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  36765. targets.push( {
  36766. format: colorFormat,
  36767. blend: blending,
  36768. writeMask: colorWriteMask
  36769. } );
  36770. }
  36771. } else {
  36772. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  36773. targets.push( {
  36774. format: colorFormat,
  36775. blend: blending,
  36776. writeMask: colorWriteMask
  36777. } );
  36778. }
  36779. const vertexModule = backend.get( vertexProgram ).module;
  36780. const fragmentModule = backend.get( fragmentProgram ).module;
  36781. const primitiveState = this._getPrimitiveState( object, geometry, material );
  36782. const depthCompare = this._getDepthCompare( material );
  36783. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  36784. const sampleCount = this._getSampleCount( renderObject.context );
  36785. const pipelineDescriptor = {
  36786. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  36787. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  36788. fragment: Object.assign( {}, fragmentModule, { targets } ),
  36789. primitive: primitiveState,
  36790. multisample: {
  36791. count: sampleCount,
  36792. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  36793. },
  36794. layout: device.createPipelineLayout( {
  36795. bindGroupLayouts
  36796. } )
  36797. };
  36798. const depthStencil = {};
  36799. const renderDepth = renderObject.context.depth;
  36800. const renderStencil = renderObject.context.stencil;
  36801. if ( renderDepth === true || renderStencil === true ) {
  36802. if ( renderDepth === true ) {
  36803. depthStencil.format = depthStencilFormat;
  36804. depthStencil.depthWriteEnabled = material.depthWrite;
  36805. depthStencil.depthCompare = depthCompare;
  36806. }
  36807. if ( renderStencil === true ) {
  36808. depthStencil.stencilFront = stencilFront;
  36809. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  36810. depthStencil.stencilReadMask = material.stencilFuncMask;
  36811. depthStencil.stencilWriteMask = material.stencilWriteMask;
  36812. }
  36813. pipelineDescriptor.depthStencil = depthStencil;
  36814. }
  36815. if ( promises === null ) {
  36816. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  36817. } else {
  36818. const p = new Promise( ( resolve /*, reject*/ ) => {
  36819. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  36820. pipelineData.pipeline = pipeline;
  36821. resolve();
  36822. } );
  36823. } );
  36824. promises.push( p );
  36825. }
  36826. }
  36827. createBundleEncoder( renderContext ) {
  36828. const backend = this.backend;
  36829. const { utils, device } = backend;
  36830. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  36831. const colorFormat = utils.getCurrentColorFormat( renderContext );
  36832. const sampleCount = this._getSampleCount( renderContext );
  36833. const descriptor = {
  36834. label: 'renderBundleEncoder',
  36835. colorFormats: [ colorFormat ],
  36836. depthStencilFormat,
  36837. sampleCount
  36838. };
  36839. return device.createRenderBundleEncoder( descriptor );
  36840. }
  36841. createComputePipeline( pipeline, bindings ) {
  36842. const backend = this.backend;
  36843. const device = backend.device;
  36844. const computeProgram = backend.get( pipeline.computeProgram ).module;
  36845. const pipelineGPU = backend.get( pipeline );
  36846. // bind group layouts
  36847. const bindGroupLayouts = [];
  36848. for ( const bindingsGroup of bindings ) {
  36849. const bindingsData = backend.get( bindingsGroup );
  36850. bindGroupLayouts.push( bindingsData.layout );
  36851. }
  36852. pipelineGPU.pipeline = device.createComputePipeline( {
  36853. compute: computeProgram,
  36854. layout: device.createPipelineLayout( {
  36855. bindGroupLayouts
  36856. } )
  36857. } );
  36858. }
  36859. _getBlending( material ) {
  36860. let color, alpha;
  36861. const blending = material.blending;
  36862. const blendSrc = material.blendSrc;
  36863. const blendDst = material.blendDst;
  36864. const blendEquation = material.blendEquation;
  36865. if ( blending === CustomBlending ) {
  36866. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  36867. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  36868. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  36869. color = {
  36870. srcFactor: this._getBlendFactor( blendSrc ),
  36871. dstFactor: this._getBlendFactor( blendDst ),
  36872. operation: this._getBlendOperation( blendEquation )
  36873. };
  36874. alpha = {
  36875. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  36876. dstFactor: this._getBlendFactor( blendDstAlpha ),
  36877. operation: this._getBlendOperation( blendEquationAlpha )
  36878. };
  36879. } else {
  36880. const premultipliedAlpha = material.premultipliedAlpha;
  36881. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  36882. color = {
  36883. srcFactor: srcRGB,
  36884. dstFactor: dstRGB,
  36885. operation: GPUBlendOperation.Add
  36886. };
  36887. alpha = {
  36888. srcFactor: srcAlpha,
  36889. dstFactor: dstAlpha,
  36890. operation: GPUBlendOperation.Add
  36891. };
  36892. };
  36893. if ( premultipliedAlpha ) {
  36894. switch ( blending ) {
  36895. case NormalBlending:
  36896. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  36897. break;
  36898. case AdditiveBlending:
  36899. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  36900. break;
  36901. case SubtractiveBlending:
  36902. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  36903. break;
  36904. case MultiplyBlending:
  36905. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  36906. break;
  36907. }
  36908. } else {
  36909. switch ( blending ) {
  36910. case NormalBlending:
  36911. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  36912. break;
  36913. case AdditiveBlending:
  36914. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  36915. break;
  36916. case SubtractiveBlending:
  36917. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  36918. break;
  36919. case MultiplyBlending:
  36920. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  36921. break;
  36922. }
  36923. }
  36924. }
  36925. if ( color !== undefined && alpha !== undefined ) {
  36926. return { color, alpha };
  36927. } else {
  36928. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  36929. }
  36930. }
  36931. _getBlendFactor( blend ) {
  36932. let blendFactor;
  36933. switch ( blend ) {
  36934. case ZeroFactor:
  36935. blendFactor = GPUBlendFactor.Zero;
  36936. break;
  36937. case OneFactor:
  36938. blendFactor = GPUBlendFactor.One;
  36939. break;
  36940. case SrcColorFactor:
  36941. blendFactor = GPUBlendFactor.Src;
  36942. break;
  36943. case OneMinusSrcColorFactor:
  36944. blendFactor = GPUBlendFactor.OneMinusSrc;
  36945. break;
  36946. case SrcAlphaFactor:
  36947. blendFactor = GPUBlendFactor.SrcAlpha;
  36948. break;
  36949. case OneMinusSrcAlphaFactor:
  36950. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  36951. break;
  36952. case DstColorFactor:
  36953. blendFactor = GPUBlendFactor.Dst;
  36954. break;
  36955. case OneMinusDstColorFactor:
  36956. blendFactor = GPUBlendFactor.OneMinusDstColor;
  36957. break;
  36958. case DstAlphaFactor:
  36959. blendFactor = GPUBlendFactor.DstAlpha;
  36960. break;
  36961. case OneMinusDstAlphaFactor:
  36962. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  36963. break;
  36964. case SrcAlphaSaturateFactor:
  36965. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  36966. break;
  36967. case BlendColorFactor:
  36968. blendFactor = GPUBlendFactor.Constant;
  36969. break;
  36970. case OneMinusBlendColorFactor:
  36971. blendFactor = GPUBlendFactor.OneMinusConstant;
  36972. break;
  36973. default:
  36974. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  36975. }
  36976. return blendFactor;
  36977. }
  36978. _getStencilCompare( material ) {
  36979. let stencilCompare;
  36980. const stencilFunc = material.stencilFunc;
  36981. switch ( stencilFunc ) {
  36982. case NeverStencilFunc:
  36983. stencilCompare = GPUCompareFunction.Never;
  36984. break;
  36985. case AlwaysStencilFunc:
  36986. stencilCompare = GPUCompareFunction.Always;
  36987. break;
  36988. case LessStencilFunc:
  36989. stencilCompare = GPUCompareFunction.Less;
  36990. break;
  36991. case LessEqualStencilFunc:
  36992. stencilCompare = GPUCompareFunction.LessEqual;
  36993. break;
  36994. case EqualStencilFunc:
  36995. stencilCompare = GPUCompareFunction.Equal;
  36996. break;
  36997. case GreaterEqualStencilFunc:
  36998. stencilCompare = GPUCompareFunction.GreaterEqual;
  36999. break;
  37000. case GreaterStencilFunc:
  37001. stencilCompare = GPUCompareFunction.Greater;
  37002. break;
  37003. case NotEqualStencilFunc:
  37004. stencilCompare = GPUCompareFunction.NotEqual;
  37005. break;
  37006. default:
  37007. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  37008. }
  37009. return stencilCompare;
  37010. }
  37011. _getStencilOperation( op ) {
  37012. let stencilOperation;
  37013. switch ( op ) {
  37014. case KeepStencilOp:
  37015. stencilOperation = GPUStencilOperation.Keep;
  37016. break;
  37017. case ZeroStencilOp:
  37018. stencilOperation = GPUStencilOperation.Zero;
  37019. break;
  37020. case ReplaceStencilOp:
  37021. stencilOperation = GPUStencilOperation.Replace;
  37022. break;
  37023. case InvertStencilOp:
  37024. stencilOperation = GPUStencilOperation.Invert;
  37025. break;
  37026. case IncrementStencilOp:
  37027. stencilOperation = GPUStencilOperation.IncrementClamp;
  37028. break;
  37029. case DecrementStencilOp:
  37030. stencilOperation = GPUStencilOperation.DecrementClamp;
  37031. break;
  37032. case IncrementWrapStencilOp:
  37033. stencilOperation = GPUStencilOperation.IncrementWrap;
  37034. break;
  37035. case DecrementWrapStencilOp:
  37036. stencilOperation = GPUStencilOperation.DecrementWrap;
  37037. break;
  37038. default:
  37039. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  37040. }
  37041. return stencilOperation;
  37042. }
  37043. _getBlendOperation( blendEquation ) {
  37044. let blendOperation;
  37045. switch ( blendEquation ) {
  37046. case AddEquation:
  37047. blendOperation = GPUBlendOperation.Add;
  37048. break;
  37049. case SubtractEquation:
  37050. blendOperation = GPUBlendOperation.Subtract;
  37051. break;
  37052. case ReverseSubtractEquation:
  37053. blendOperation = GPUBlendOperation.ReverseSubtract;
  37054. break;
  37055. case MinEquation:
  37056. blendOperation = GPUBlendOperation.Min;
  37057. break;
  37058. case MaxEquation:
  37059. blendOperation = GPUBlendOperation.Max;
  37060. break;
  37061. default:
  37062. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  37063. }
  37064. return blendOperation;
  37065. }
  37066. _getPrimitiveState( object, geometry, material ) {
  37067. const descriptor = {};
  37068. const utils = this.backend.utils;
  37069. descriptor.topology = utils.getPrimitiveTopology( object, material );
  37070. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  37071. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  37072. }
  37073. switch ( material.side ) {
  37074. case FrontSide:
  37075. descriptor.frontFace = GPUFrontFace.CCW;
  37076. descriptor.cullMode = GPUCullMode.Back;
  37077. break;
  37078. case BackSide:
  37079. descriptor.frontFace = GPUFrontFace.CCW;
  37080. descriptor.cullMode = GPUCullMode.Front;
  37081. break;
  37082. case DoubleSide:
  37083. descriptor.frontFace = GPUFrontFace.CCW;
  37084. descriptor.cullMode = GPUCullMode.None;
  37085. break;
  37086. default:
  37087. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  37088. break;
  37089. }
  37090. return descriptor;
  37091. }
  37092. _getColorWriteMask( material ) {
  37093. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  37094. }
  37095. _getDepthCompare( material ) {
  37096. let depthCompare;
  37097. if ( material.depthTest === false ) {
  37098. depthCompare = GPUCompareFunction.Always;
  37099. } else {
  37100. const depthFunc = material.depthFunc;
  37101. switch ( depthFunc ) {
  37102. case NeverDepth:
  37103. depthCompare = GPUCompareFunction.Never;
  37104. break;
  37105. case AlwaysDepth:
  37106. depthCompare = GPUCompareFunction.Always;
  37107. break;
  37108. case LessDepth:
  37109. depthCompare = GPUCompareFunction.Less;
  37110. break;
  37111. case LessEqualDepth:
  37112. depthCompare = GPUCompareFunction.LessEqual;
  37113. break;
  37114. case EqualDepth:
  37115. depthCompare = GPUCompareFunction.Equal;
  37116. break;
  37117. case GreaterEqualDepth:
  37118. depthCompare = GPUCompareFunction.GreaterEqual;
  37119. break;
  37120. case GreaterDepth:
  37121. depthCompare = GPUCompareFunction.Greater;
  37122. break;
  37123. case NotEqualDepth:
  37124. depthCompare = GPUCompareFunction.NotEqual;
  37125. break;
  37126. default:
  37127. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  37128. }
  37129. }
  37130. return depthCompare;
  37131. }
  37132. }
  37133. /*// debugger tools
  37134. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  37135. //*/
  37136. //
  37137. class WebGPUBackend extends Backend {
  37138. constructor( parameters = {} ) {
  37139. super( parameters );
  37140. this.isWebGPUBackend = true;
  37141. // some parameters require default values other than "undefined"
  37142. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  37143. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  37144. this.trackTimestamp = ( parameters.trackTimestamp === true );
  37145. this.device = null;
  37146. this.context = null;
  37147. this.colorBuffer = null;
  37148. this.defaultRenderPassdescriptor = null;
  37149. this.utils = new WebGPUUtils( this );
  37150. this.attributeUtils = new WebGPUAttributeUtils( this );
  37151. this.bindingUtils = new WebGPUBindingUtils( this );
  37152. this.pipelineUtils = new WebGPUPipelineUtils( this );
  37153. this.textureUtils = new WebGPUTextureUtils( this );
  37154. this.occludedResolveCache = new Map();
  37155. }
  37156. async init( renderer ) {
  37157. await super.init( renderer );
  37158. //
  37159. const parameters = this.parameters;
  37160. // create the device if it is not passed with parameters
  37161. let device;
  37162. if ( parameters.device === undefined ) {
  37163. const adapterOptions = {
  37164. powerPreference: parameters.powerPreference
  37165. };
  37166. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  37167. if ( adapter === null ) {
  37168. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  37169. }
  37170. // feature support
  37171. const features = Object.values( GPUFeatureName );
  37172. const supportedFeatures = [];
  37173. for ( const name of features ) {
  37174. if ( adapter.features.has( name ) ) {
  37175. supportedFeatures.push( name );
  37176. }
  37177. }
  37178. const deviceDescriptor = {
  37179. requiredFeatures: supportedFeatures,
  37180. requiredLimits: parameters.requiredLimits
  37181. };
  37182. device = await adapter.requestDevice( deviceDescriptor );
  37183. } else {
  37184. device = parameters.device;
  37185. }
  37186. device.lost.then( ( info ) => {
  37187. const deviceLossInfo = {
  37188. api: 'WebGPU',
  37189. message: info.message || 'Unknown reason',
  37190. reason: info.reason || null,
  37191. originalEvent: info
  37192. };
  37193. renderer.onDeviceLost( deviceLossInfo );
  37194. } );
  37195. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  37196. this.device = device;
  37197. this.context = context;
  37198. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  37199. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  37200. this.context.configure( {
  37201. device: this.device,
  37202. format: this.utils.getPreferredCanvasFormat(),
  37203. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  37204. alphaMode: alphaMode
  37205. } );
  37206. this.updateSize();
  37207. }
  37208. get coordinateSystem() {
  37209. return WebGPUCoordinateSystem;
  37210. }
  37211. async getArrayBufferAsync( attribute ) {
  37212. return await this.attributeUtils.getArrayBufferAsync( attribute );
  37213. }
  37214. getContext() {
  37215. return this.context;
  37216. }
  37217. _getDefaultRenderPassDescriptor() {
  37218. let descriptor = this.defaultRenderPassdescriptor;
  37219. if ( descriptor === null ) {
  37220. const renderer = this.renderer;
  37221. descriptor = {
  37222. colorAttachments: [ {
  37223. view: null
  37224. } ],
  37225. };
  37226. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  37227. descriptor.depthStencilAttachment = {
  37228. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  37229. };
  37230. }
  37231. const colorAttachment = descriptor.colorAttachments[ 0 ];
  37232. if ( this.renderer.samples > 0 ) {
  37233. colorAttachment.view = this.colorBuffer.createView();
  37234. } else {
  37235. colorAttachment.resolveTarget = undefined;
  37236. }
  37237. this.defaultRenderPassdescriptor = descriptor;
  37238. }
  37239. const colorAttachment = descriptor.colorAttachments[ 0 ];
  37240. if ( this.renderer.samples > 0 ) {
  37241. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  37242. } else {
  37243. colorAttachment.view = this.context.getCurrentTexture().createView();
  37244. }
  37245. return descriptor;
  37246. }
  37247. _getRenderPassDescriptor( renderContext ) {
  37248. const renderTarget = renderContext.renderTarget;
  37249. const renderTargetData = this.get( renderTarget );
  37250. let descriptors = renderTargetData.descriptors;
  37251. if ( descriptors === undefined ||
  37252. renderTargetData.width !== renderTarget.width ||
  37253. renderTargetData.height !== renderTarget.height ||
  37254. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  37255. renderTargetData.samples !== renderTarget.samples
  37256. ) {
  37257. descriptors = {};
  37258. renderTargetData.descriptors = descriptors;
  37259. // dispose
  37260. const onDispose = () => {
  37261. renderTarget.removeEventListener( 'dispose', onDispose );
  37262. this.delete( renderTarget );
  37263. };
  37264. renderTarget.addEventListener( 'dispose', onDispose );
  37265. }
  37266. const cacheKey = renderContext.getCacheKey();
  37267. let descriptor = descriptors[ cacheKey ];
  37268. if ( descriptor === undefined ) {
  37269. const textures = renderContext.textures;
  37270. const colorAttachments = [];
  37271. for ( let i = 0; i < textures.length; i ++ ) {
  37272. const textureData = this.get( textures[ i ] );
  37273. const textureView = textureData.texture.createView( {
  37274. baseMipLevel: renderContext.activeMipmapLevel,
  37275. mipLevelCount: 1,
  37276. baseArrayLayer: renderContext.activeCubeFace,
  37277. dimension: GPUTextureViewDimension.TwoD
  37278. } );
  37279. let view, resolveTarget;
  37280. if ( textureData.msaaTexture !== undefined ) {
  37281. view = textureData.msaaTexture.createView();
  37282. resolveTarget = textureView;
  37283. } else {
  37284. view = textureView;
  37285. resolveTarget = undefined;
  37286. }
  37287. colorAttachments.push( {
  37288. view,
  37289. resolveTarget,
  37290. loadOp: GPULoadOp.Load,
  37291. storeOp: GPUStoreOp.Store
  37292. } );
  37293. }
  37294. descriptor = {
  37295. colorAttachments,
  37296. };
  37297. if ( renderContext.depth ) {
  37298. const depthTextureData = this.get( renderContext.depthTexture );
  37299. const depthStencilAttachment = {
  37300. view: depthTextureData.texture.createView()
  37301. };
  37302. descriptor.depthStencilAttachment = depthStencilAttachment;
  37303. }
  37304. descriptors[ cacheKey ] = descriptor;
  37305. renderTargetData.width = renderTarget.width;
  37306. renderTargetData.height = renderTarget.height;
  37307. renderTargetData.samples = renderTarget.samples;
  37308. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  37309. }
  37310. return descriptor;
  37311. }
  37312. beginRender( renderContext ) {
  37313. const renderContextData = this.get( renderContext );
  37314. const device = this.device;
  37315. const occlusionQueryCount = renderContext.occlusionQueryCount;
  37316. let occlusionQuerySet;
  37317. if ( occlusionQueryCount > 0 ) {
  37318. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  37319. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  37320. // Get a reference to the array of objects with queries. The renderContextData property
  37321. // can be changed by another render pass before the buffer.mapAsyc() completes.
  37322. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  37323. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  37324. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  37325. //
  37326. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  37327. renderContextData.occlusionQuerySet = occlusionQuerySet;
  37328. renderContextData.occlusionQueryIndex = 0;
  37329. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  37330. renderContextData.lastOcclusionObject = null;
  37331. }
  37332. let descriptor;
  37333. if ( renderContext.textures === null ) {
  37334. descriptor = this._getDefaultRenderPassDescriptor();
  37335. } else {
  37336. descriptor = this._getRenderPassDescriptor( renderContext );
  37337. }
  37338. this.initTimestampQuery( renderContext, descriptor );
  37339. descriptor.occlusionQuerySet = occlusionQuerySet;
  37340. const depthStencilAttachment = descriptor.depthStencilAttachment;
  37341. if ( renderContext.textures !== null ) {
  37342. const colorAttachments = descriptor.colorAttachments;
  37343. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  37344. const colorAttachment = colorAttachments[ i ];
  37345. if ( renderContext.clearColor ) {
  37346. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  37347. colorAttachment.loadOp = GPULoadOp.Clear;
  37348. colorAttachment.storeOp = GPUStoreOp.Store;
  37349. } else {
  37350. colorAttachment.loadOp = GPULoadOp.Load;
  37351. colorAttachment.storeOp = GPUStoreOp.Store;
  37352. }
  37353. }
  37354. } else {
  37355. const colorAttachment = descriptor.colorAttachments[ 0 ];
  37356. if ( renderContext.clearColor ) {
  37357. colorAttachment.clearValue = renderContext.clearColorValue;
  37358. colorAttachment.loadOp = GPULoadOp.Clear;
  37359. colorAttachment.storeOp = GPUStoreOp.Store;
  37360. } else {
  37361. colorAttachment.loadOp = GPULoadOp.Load;
  37362. colorAttachment.storeOp = GPUStoreOp.Store;
  37363. }
  37364. }
  37365. //
  37366. if ( renderContext.depth ) {
  37367. if ( renderContext.clearDepth ) {
  37368. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  37369. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  37370. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  37371. } else {
  37372. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  37373. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  37374. }
  37375. }
  37376. if ( renderContext.stencil ) {
  37377. if ( renderContext.clearStencil ) {
  37378. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  37379. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  37380. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  37381. } else {
  37382. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  37383. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  37384. }
  37385. }
  37386. //
  37387. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  37388. const currentPass = encoder.beginRenderPass( descriptor );
  37389. //
  37390. renderContextData.descriptor = descriptor;
  37391. renderContextData.encoder = encoder;
  37392. renderContextData.currentPass = currentPass;
  37393. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  37394. renderContextData.renderBundles = [];
  37395. //
  37396. if ( renderContext.viewport ) {
  37397. this.updateViewport( renderContext );
  37398. }
  37399. if ( renderContext.scissor ) {
  37400. const { x, y, width, height } = renderContext.scissorValue;
  37401. currentPass.setScissorRect( x, y, width, height );
  37402. }
  37403. }
  37404. finishRender( renderContext ) {
  37405. const renderContextData = this.get( renderContext );
  37406. const occlusionQueryCount = renderContext.occlusionQueryCount;
  37407. if ( renderContextData.renderBundles.length > 0 ) {
  37408. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  37409. }
  37410. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  37411. renderContextData.currentPass.endOcclusionQuery();
  37412. }
  37413. renderContextData.currentPass.end();
  37414. if ( occlusionQueryCount > 0 ) {
  37415. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  37416. //
  37417. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  37418. if ( queryResolveBuffer === undefined ) {
  37419. queryResolveBuffer = this.device.createBuffer(
  37420. {
  37421. size: bufferSize,
  37422. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  37423. }
  37424. );
  37425. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  37426. }
  37427. //
  37428. const readBuffer = this.device.createBuffer(
  37429. {
  37430. size: bufferSize,
  37431. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  37432. }
  37433. );
  37434. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  37435. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  37436. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  37437. renderContextData.occlusionQueryBuffer = readBuffer;
  37438. //
  37439. this.resolveOccludedAsync( renderContext );
  37440. }
  37441. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  37442. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  37443. //
  37444. if ( renderContext.textures !== null ) {
  37445. const textures = renderContext.textures;
  37446. for ( let i = 0; i < textures.length; i ++ ) {
  37447. const texture = textures[ i ];
  37448. if ( texture.generateMipmaps === true ) {
  37449. this.textureUtils.generateMipmaps( texture );
  37450. }
  37451. }
  37452. }
  37453. }
  37454. isOccluded( renderContext, object ) {
  37455. const renderContextData = this.get( renderContext );
  37456. return renderContextData.occluded && renderContextData.occluded.has( object );
  37457. }
  37458. async resolveOccludedAsync( renderContext ) {
  37459. const renderContextData = this.get( renderContext );
  37460. // handle occlusion query results
  37461. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  37462. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  37463. const occluded = new WeakSet();
  37464. renderContextData.currentOcclusionQueryObjects = null;
  37465. renderContextData.currentOcclusionQueryBuffer = null;
  37466. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  37467. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  37468. const results = new BigUint64Array( buffer );
  37469. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  37470. if ( results[ i ] !== BigInt( 0 ) ) {
  37471. occluded.add( currentOcclusionQueryObjects[ i ] );
  37472. }
  37473. }
  37474. currentOcclusionQueryBuffer.destroy();
  37475. renderContextData.occluded = occluded;
  37476. }
  37477. }
  37478. updateViewport( renderContext ) {
  37479. const { currentPass } = this.get( renderContext );
  37480. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  37481. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  37482. }
  37483. clear( color, depth, stencil, renderTargetData = null ) {
  37484. const device = this.device;
  37485. const renderer = this.renderer;
  37486. let colorAttachments = [];
  37487. let depthStencilAttachment;
  37488. let clearValue;
  37489. let supportsDepth;
  37490. let supportsStencil;
  37491. if ( color ) {
  37492. const clearColor = this.getClearColor();
  37493. if ( this.renderer.alpha === true ) {
  37494. // premultiply alpha
  37495. const a = clearColor.a;
  37496. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  37497. } else {
  37498. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  37499. }
  37500. }
  37501. if ( renderTargetData === null ) {
  37502. supportsDepth = renderer.depth;
  37503. supportsStencil = renderer.stencil;
  37504. const descriptor = this._getDefaultRenderPassDescriptor();
  37505. if ( color ) {
  37506. colorAttachments = descriptor.colorAttachments;
  37507. const colorAttachment = colorAttachments[ 0 ];
  37508. colorAttachment.clearValue = clearValue;
  37509. colorAttachment.loadOp = GPULoadOp.Clear;
  37510. colorAttachment.storeOp = GPUStoreOp.Store;
  37511. }
  37512. if ( supportsDepth || supportsStencil ) {
  37513. depthStencilAttachment = descriptor.depthStencilAttachment;
  37514. }
  37515. } else {
  37516. supportsDepth = renderTargetData.depth;
  37517. supportsStencil = renderTargetData.stencil;
  37518. if ( color ) {
  37519. for ( const texture of renderTargetData.textures ) {
  37520. const textureData = this.get( texture );
  37521. const textureView = textureData.texture.createView();
  37522. let view, resolveTarget;
  37523. if ( textureData.msaaTexture !== undefined ) {
  37524. view = textureData.msaaTexture.createView();
  37525. resolveTarget = textureView;
  37526. } else {
  37527. view = textureView;
  37528. resolveTarget = undefined;
  37529. }
  37530. colorAttachments.push( {
  37531. view,
  37532. resolveTarget,
  37533. clearValue,
  37534. loadOp: GPULoadOp.Clear,
  37535. storeOp: GPUStoreOp.Store
  37536. } );
  37537. }
  37538. }
  37539. if ( supportsDepth || supportsStencil ) {
  37540. const depthTextureData = this.get( renderTargetData.depthTexture );
  37541. depthStencilAttachment = {
  37542. view: depthTextureData.texture.createView()
  37543. };
  37544. }
  37545. }
  37546. //
  37547. if ( supportsDepth ) {
  37548. if ( depth ) {
  37549. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  37550. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  37551. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  37552. } else {
  37553. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  37554. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  37555. }
  37556. }
  37557. //
  37558. if ( supportsStencil ) {
  37559. if ( stencil ) {
  37560. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  37561. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  37562. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  37563. } else {
  37564. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  37565. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  37566. }
  37567. }
  37568. //
  37569. const encoder = device.createCommandEncoder( {} );
  37570. const currentPass = encoder.beginRenderPass( {
  37571. colorAttachments,
  37572. depthStencilAttachment
  37573. } );
  37574. currentPass.end();
  37575. device.queue.submit( [ encoder.finish() ] );
  37576. }
  37577. // compute
  37578. beginCompute( computeGroup ) {
  37579. const groupGPU = this.get( computeGroup );
  37580. const descriptor = {};
  37581. this.initTimestampQuery( computeGroup, descriptor );
  37582. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  37583. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  37584. }
  37585. compute( computeGroup, computeNode, bindings, pipeline ) {
  37586. const { passEncoderGPU } = this.get( computeGroup );
  37587. // pipeline
  37588. const pipelineGPU = this.get( pipeline ).pipeline;
  37589. passEncoderGPU.setPipeline( pipelineGPU );
  37590. // bind groups
  37591. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  37592. const bindGroup = bindings[ i ];
  37593. const bindingsData = this.get( bindGroup );
  37594. passEncoderGPU.setBindGroup( i, bindingsData.group );
  37595. }
  37596. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  37597. const computeNodeData = this.get( computeNode );
  37598. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  37599. const { dispatchSize } = computeNodeData;
  37600. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  37601. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  37602. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  37603. } else {
  37604. dispatchSize.x = computeNode.dispatchCount;
  37605. }
  37606. passEncoderGPU.dispatchWorkgroups(
  37607. dispatchSize.x,
  37608. dispatchSize.y,
  37609. dispatchSize.z
  37610. );
  37611. }
  37612. finishCompute( computeGroup ) {
  37613. const groupData = this.get( computeGroup );
  37614. groupData.passEncoderGPU.end();
  37615. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  37616. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  37617. }
  37618. async waitForGPU() {
  37619. await this.device.queue.onSubmittedWorkDone();
  37620. }
  37621. // render object
  37622. draw( renderObject, info ) {
  37623. const { object, context, pipeline } = renderObject;
  37624. const bindings = renderObject.getBindings();
  37625. const renderContextData = this.get( context );
  37626. const pipelineGPU = this.get( pipeline ).pipeline;
  37627. const currentSets = renderContextData.currentSets;
  37628. const passEncoderGPU = renderContextData.currentPass;
  37629. const drawParams = renderObject.getDrawParameters();
  37630. if ( drawParams === null ) return;
  37631. // pipeline
  37632. if ( currentSets.pipeline !== pipelineGPU ) {
  37633. passEncoderGPU.setPipeline( pipelineGPU );
  37634. currentSets.pipeline = pipelineGPU;
  37635. }
  37636. // bind groups
  37637. const currentBindingGroups = currentSets.bindingGroups;
  37638. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  37639. const bindGroup = bindings[ i ];
  37640. const bindingsData = this.get( bindGroup );
  37641. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  37642. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  37643. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  37644. }
  37645. }
  37646. // attributes
  37647. const index = renderObject.getIndex();
  37648. const hasIndex = ( index !== null );
  37649. // index
  37650. if ( hasIndex === true ) {
  37651. if ( currentSets.index !== index ) {
  37652. const buffer = this.get( index ).buffer;
  37653. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  37654. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  37655. currentSets.index = index;
  37656. }
  37657. }
  37658. // vertex buffers
  37659. const vertexBuffers = renderObject.getVertexBuffers();
  37660. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  37661. const vertexBuffer = vertexBuffers[ i ];
  37662. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  37663. const buffer = this.get( vertexBuffer ).buffer;
  37664. passEncoderGPU.setVertexBuffer( i, buffer );
  37665. currentSets.attributes[ i ] = vertexBuffer;
  37666. }
  37667. }
  37668. // occlusion queries - handle multiple consecutive draw calls for an object
  37669. if ( renderContextData.occlusionQuerySet !== undefined ) {
  37670. const lastObject = renderContextData.lastOcclusionObject;
  37671. if ( lastObject !== object ) {
  37672. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  37673. passEncoderGPU.endOcclusionQuery();
  37674. renderContextData.occlusionQueryIndex ++;
  37675. }
  37676. if ( object.occlusionTest === true ) {
  37677. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  37678. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  37679. }
  37680. renderContextData.lastOcclusionObject = object;
  37681. }
  37682. }
  37683. // draw
  37684. if ( object.isBatchedMesh === true ) {
  37685. const starts = object._multiDrawStarts;
  37686. const counts = object._multiDrawCounts;
  37687. const drawCount = object._multiDrawCount;
  37688. const drawInstances = object._multiDrawInstances;
  37689. for ( let i = 0; i < drawCount; i ++ ) {
  37690. const count = drawInstances ? drawInstances[ i ] : 1;
  37691. const firstInstance = count > 1 ? 0 : i;
  37692. if ( hasIndex === true ) {
  37693. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  37694. } else {
  37695. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  37696. }
  37697. }
  37698. } else if ( hasIndex === true ) {
  37699. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  37700. const indirect = renderObject.getIndirect();
  37701. if ( indirect !== null ) {
  37702. const buffer = this.get( indirect ).buffer;
  37703. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  37704. } else {
  37705. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  37706. }
  37707. info.update( object, indexCount, instanceCount );
  37708. } else {
  37709. const { vertexCount, instanceCount, firstVertex } = drawParams;
  37710. const indirect = renderObject.getIndirect();
  37711. if ( indirect !== null ) {
  37712. const buffer = this.get( indirect ).buffer;
  37713. passEncoderGPU.drawIndirect( buffer, 0 );
  37714. } else {
  37715. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  37716. }
  37717. info.update( object, vertexCount, instanceCount );
  37718. }
  37719. }
  37720. // cache key
  37721. needsRenderUpdate( renderObject ) {
  37722. const data = this.get( renderObject );
  37723. const { object, material } = renderObject;
  37724. const utils = this.utils;
  37725. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  37726. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  37727. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  37728. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  37729. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  37730. let needsUpdate = false;
  37731. if ( data.material !== material || data.materialVersion !== material.version ||
  37732. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  37733. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  37734. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  37735. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  37736. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  37737. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  37738. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  37739. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  37740. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  37741. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  37742. data.primitiveTopology !== primitiveTopology ||
  37743. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  37744. ) {
  37745. data.material = material; data.materialVersion = material.version;
  37746. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  37747. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  37748. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  37749. data.colorWrite = material.colorWrite;
  37750. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  37751. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  37752. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  37753. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  37754. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  37755. data.sampleCount = sampleCount;
  37756. data.colorSpace = colorSpace;
  37757. data.colorFormat = colorFormat;
  37758. data.depthStencilFormat = depthStencilFormat;
  37759. data.primitiveTopology = primitiveTopology;
  37760. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  37761. needsUpdate = true;
  37762. }
  37763. return needsUpdate;
  37764. }
  37765. getRenderCacheKey( renderObject ) {
  37766. const { object, material } = renderObject;
  37767. const utils = this.utils;
  37768. const renderContext = renderObject.context;
  37769. return [
  37770. material.transparent, material.blending, material.premultipliedAlpha,
  37771. material.blendSrc, material.blendDst, material.blendEquation,
  37772. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  37773. material.colorWrite,
  37774. material.depthWrite, material.depthTest, material.depthFunc,
  37775. material.stencilWrite, material.stencilFunc,
  37776. material.stencilFail, material.stencilZFail, material.stencilZPass,
  37777. material.stencilFuncMask, material.stencilWriteMask,
  37778. material.side,
  37779. utils.getSampleCountRenderContext( renderContext ),
  37780. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  37781. utils.getPrimitiveTopology( object, material ),
  37782. renderObject.getGeometryCacheKey(),
  37783. renderObject.clippingContextCacheKey
  37784. ].join();
  37785. }
  37786. // textures
  37787. createSampler( texture ) {
  37788. this.textureUtils.createSampler( texture );
  37789. }
  37790. destroySampler( texture ) {
  37791. this.textureUtils.destroySampler( texture );
  37792. }
  37793. createDefaultTexture( texture ) {
  37794. this.textureUtils.createDefaultTexture( texture );
  37795. }
  37796. createTexture( texture, options ) {
  37797. this.textureUtils.createTexture( texture, options );
  37798. }
  37799. updateTexture( texture, options ) {
  37800. this.textureUtils.updateTexture( texture, options );
  37801. }
  37802. generateMipmaps( texture ) {
  37803. this.textureUtils.generateMipmaps( texture );
  37804. }
  37805. destroyTexture( texture ) {
  37806. this.textureUtils.destroyTexture( texture );
  37807. }
  37808. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  37809. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  37810. }
  37811. initTimestampQuery( renderContext, descriptor ) {
  37812. if ( ! this.trackTimestamp ) return;
  37813. const renderContextData = this.get( renderContext );
  37814. if ( ! renderContextData.timeStampQuerySet ) {
  37815. const type = renderContext.isComputeNode ? 'compute' : 'render';
  37816. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  37817. const timestampWrites = {
  37818. querySet: timeStampQuerySet,
  37819. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  37820. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  37821. };
  37822. Object.assign( descriptor, { timestampWrites } );
  37823. renderContextData.timeStampQuerySet = timeStampQuerySet;
  37824. }
  37825. }
  37826. // timestamp utils
  37827. prepareTimestampBuffer( renderContext, encoder ) {
  37828. if ( ! this.trackTimestamp ) return;
  37829. const renderContextData = this.get( renderContext );
  37830. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  37831. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  37832. renderContextData.currentTimestampQueryBuffers = {
  37833. resolveBuffer: this.device.createBuffer( {
  37834. label: 'timestamp resolve buffer',
  37835. size: size,
  37836. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  37837. } ),
  37838. resultBuffer: this.device.createBuffer( {
  37839. label: 'timestamp result buffer',
  37840. size: size,
  37841. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  37842. } )
  37843. };
  37844. }
  37845. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  37846. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  37847. if ( resultBuffer.mapState === 'unmapped' ) {
  37848. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  37849. }
  37850. }
  37851. async resolveTimestampAsync( renderContext, type = 'render' ) {
  37852. if ( ! this.trackTimestamp ) return;
  37853. const renderContextData = this.get( renderContext );
  37854. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  37855. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  37856. if ( resultBuffer.mapState === 'unmapped' ) {
  37857. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  37858. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  37859. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  37860. this.renderer.info.updateTimestamp( type, duration );
  37861. resultBuffer.unmap();
  37862. } );
  37863. }
  37864. }
  37865. // node builder
  37866. createNodeBuilder( object, renderer ) {
  37867. return new WGSLNodeBuilder( object, renderer );
  37868. }
  37869. // program
  37870. createProgram( program ) {
  37871. const programGPU = this.get( program );
  37872. programGPU.module = {
  37873. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  37874. entryPoint: 'main'
  37875. };
  37876. }
  37877. destroyProgram( program ) {
  37878. this.delete( program );
  37879. }
  37880. // pipelines
  37881. createRenderPipeline( renderObject, promises ) {
  37882. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  37883. }
  37884. createComputePipeline( computePipeline, bindings ) {
  37885. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  37886. }
  37887. beginBundle( renderContext ) {
  37888. const renderContextData = this.get( renderContext );
  37889. renderContextData._currentPass = renderContextData.currentPass;
  37890. renderContextData._currentSets = renderContextData.currentSets;
  37891. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  37892. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  37893. }
  37894. finishBundle( renderContext, bundle ) {
  37895. const renderContextData = this.get( renderContext );
  37896. const bundleEncoder = renderContextData.currentPass;
  37897. const bundleGPU = bundleEncoder.finish();
  37898. this.get( bundle ).bundleGPU = bundleGPU;
  37899. // restore render pass state
  37900. renderContextData.currentSets = renderContextData._currentSets;
  37901. renderContextData.currentPass = renderContextData._currentPass;
  37902. }
  37903. addBundle( renderContext, bundle ) {
  37904. const renderContextData = this.get( renderContext );
  37905. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  37906. }
  37907. // bindings
  37908. createBindings( bindGroup, bindings, cacheIndex, version ) {
  37909. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  37910. }
  37911. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  37912. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  37913. }
  37914. updateBinding( binding ) {
  37915. this.bindingUtils.updateBinding( binding );
  37916. }
  37917. // attributes
  37918. createIndexAttribute( attribute ) {
  37919. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  37920. }
  37921. createAttribute( attribute ) {
  37922. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  37923. }
  37924. createStorageAttribute( attribute ) {
  37925. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  37926. }
  37927. createIndirectStorageAttribute( attribute ) {
  37928. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  37929. }
  37930. updateAttribute( attribute ) {
  37931. this.attributeUtils.updateAttribute( attribute );
  37932. }
  37933. destroyAttribute( attribute ) {
  37934. this.attributeUtils.destroyAttribute( attribute );
  37935. }
  37936. // canvas
  37937. updateSize() {
  37938. this.colorBuffer = this.textureUtils.getColorBuffer();
  37939. this.defaultRenderPassdescriptor = null;
  37940. }
  37941. // utils public
  37942. getMaxAnisotropy() {
  37943. return 16;
  37944. }
  37945. hasFeature( name ) {
  37946. return this.device.features.has( name );
  37947. }
  37948. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37949. let dstX = 0;
  37950. let dstY = 0;
  37951. let dstLayer = 0;
  37952. let srcX = 0;
  37953. let srcY = 0;
  37954. let srcLayer = 0;
  37955. let srcWidth = srcTexture.image.width;
  37956. let srcHeight = srcTexture.image.height;
  37957. if ( srcRegion !== null ) {
  37958. srcX = srcRegion.x;
  37959. srcY = srcRegion.y;
  37960. srcLayer = srcRegion.z || 0;
  37961. srcWidth = srcRegion.width;
  37962. srcHeight = srcRegion.height;
  37963. }
  37964. if ( dstPosition !== null ) {
  37965. dstX = dstPosition.x;
  37966. dstY = dstPosition.y;
  37967. dstLayer = dstPosition.z || 0;
  37968. }
  37969. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  37970. const sourceGPU = this.get( srcTexture ).texture;
  37971. const destinationGPU = this.get( dstTexture ).texture;
  37972. encoder.copyTextureToTexture(
  37973. {
  37974. texture: sourceGPU,
  37975. mipLevel: level,
  37976. origin: { x: srcX, y: srcY, z: srcLayer }
  37977. },
  37978. {
  37979. texture: destinationGPU,
  37980. mipLevel: level,
  37981. origin: { x: dstX, y: dstY, z: dstLayer }
  37982. },
  37983. [
  37984. srcWidth,
  37985. srcHeight,
  37986. 1
  37987. ]
  37988. );
  37989. this.device.queue.submit( [ encoder.finish() ] );
  37990. }
  37991. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  37992. const renderContextData = this.get( renderContext );
  37993. let sourceGPU = null;
  37994. if ( renderContext.renderTarget ) {
  37995. if ( texture.isDepthTexture ) {
  37996. sourceGPU = this.get( renderContext.depthTexture ).texture;
  37997. } else {
  37998. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  37999. }
  38000. } else {
  38001. if ( texture.isDepthTexture ) {
  38002. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  38003. } else {
  38004. sourceGPU = this.context.getCurrentTexture();
  38005. }
  38006. }
  38007. const destinationGPU = this.get( texture ).texture;
  38008. if ( sourceGPU.format !== destinationGPU.format ) {
  38009. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  38010. return;
  38011. }
  38012. let encoder;
  38013. if ( renderContextData.currentPass ) {
  38014. renderContextData.currentPass.end();
  38015. encoder = renderContextData.encoder;
  38016. } else {
  38017. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  38018. }
  38019. encoder.copyTextureToTexture(
  38020. {
  38021. texture: sourceGPU,
  38022. origin: [ rectangle.x, rectangle.y, 0 ],
  38023. },
  38024. {
  38025. texture: destinationGPU
  38026. },
  38027. [
  38028. rectangle.z,
  38029. rectangle.w
  38030. ]
  38031. );
  38032. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  38033. if ( renderContextData.currentPass ) {
  38034. const { descriptor } = renderContextData;
  38035. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  38036. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  38037. }
  38038. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  38039. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  38040. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  38041. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  38042. if ( renderContext.viewport ) {
  38043. this.updateViewport( renderContext );
  38044. }
  38045. if ( renderContext.scissor ) {
  38046. const { x, y, width, height } = renderContext.scissorValue;
  38047. renderContextData.currentPass.setScissorRect( x, y, width, height );
  38048. }
  38049. } else {
  38050. this.device.queue.submit( [ encoder.finish() ] );
  38051. }
  38052. }
  38053. }
  38054. class IESSpotLight extends SpotLight {
  38055. constructor( color, intensity, distance, angle, penumbra, decay ) {
  38056. super( color, intensity, distance, angle, penumbra, decay );
  38057. this.iesMap = null;
  38058. }
  38059. copy( source, recursive ) {
  38060. super.copy( source, recursive );
  38061. this.iesMap = source.iesMap;
  38062. return this;
  38063. }
  38064. }
  38065. class BasicNodeLibrary extends NodeLibrary {
  38066. constructor() {
  38067. super();
  38068. this.addLight( PointLightNode, PointLight );
  38069. this.addLight( DirectionalLightNode, DirectionalLight );
  38070. this.addLight( RectAreaLightNode, RectAreaLight );
  38071. this.addLight( SpotLightNode, SpotLight );
  38072. this.addLight( AmbientLightNode, AmbientLight );
  38073. this.addLight( HemisphereLightNode, HemisphereLight );
  38074. this.addLight( LightProbeNode, LightProbe );
  38075. this.addLight( IESSpotLightNode, IESSpotLight );
  38076. this.addToneMapping( linearToneMapping, LinearToneMapping );
  38077. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  38078. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  38079. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  38080. this.addToneMapping( agxToneMapping, AgXToneMapping );
  38081. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  38082. }
  38083. }
  38084. class WebGPURenderer extends Renderer {
  38085. constructor( parameters = {} ) {
  38086. let BackendClass;
  38087. if ( parameters.forceWebGL ) {
  38088. BackendClass = WebGLBackend;
  38089. } else {
  38090. BackendClass = WebGPUBackend;
  38091. parameters.getFallback = () => {
  38092. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  38093. return new WebGLBackend( parameters );
  38094. };
  38095. }
  38096. const backend = new BackendClass( parameters );
  38097. super( backend, parameters );
  38098. this.library = new BasicNodeLibrary();
  38099. this.isWebGPURenderer = true;
  38100. }
  38101. }
  38102. class BundleGroup extends Group {
  38103. constructor() {
  38104. super();
  38105. this.isBundleGroup = true;
  38106. this.type = 'BundleGroup';
  38107. this.static = true;
  38108. this.version = 0;
  38109. }
  38110. set needsUpdate( value ) {
  38111. if ( value === true ) this.version ++;
  38112. }
  38113. }
  38114. const _material = /*@__PURE__*/ new NodeMaterial();
  38115. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  38116. class PostProcessing {
  38117. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  38118. this.renderer = renderer;
  38119. this.outputNode = outputNode;
  38120. this.outputColorTransform = true;
  38121. this.needsUpdate = true;
  38122. _material.name = 'PostProcessing';
  38123. }
  38124. render() {
  38125. this.update();
  38126. const renderer = this.renderer;
  38127. const toneMapping = renderer.toneMapping;
  38128. const outputColorSpace = renderer.outputColorSpace;
  38129. renderer.toneMapping = NoToneMapping;
  38130. renderer.outputColorSpace = LinearSRGBColorSpace;
  38131. //
  38132. _quadMesh.render( renderer );
  38133. //
  38134. renderer.toneMapping = toneMapping;
  38135. renderer.outputColorSpace = outputColorSpace;
  38136. }
  38137. update() {
  38138. if ( this.needsUpdate === true ) {
  38139. const renderer = this.renderer;
  38140. const toneMapping = renderer.toneMapping;
  38141. const outputColorSpace = renderer.outputColorSpace;
  38142. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  38143. _quadMesh.material.needsUpdate = true;
  38144. this.needsUpdate = false;
  38145. }
  38146. }
  38147. async renderAsync() {
  38148. this.update();
  38149. const renderer = this.renderer;
  38150. const toneMapping = renderer.toneMapping;
  38151. const outputColorSpace = renderer.outputColorSpace;
  38152. renderer.toneMapping = NoToneMapping;
  38153. renderer.outputColorSpace = LinearSRGBColorSpace;
  38154. //
  38155. await _quadMesh.renderAsync( renderer );
  38156. //
  38157. renderer.toneMapping = toneMapping;
  38158. renderer.outputColorSpace = outputColorSpace;
  38159. }
  38160. }
  38161. class StorageTexture extends Texture {
  38162. constructor( width = 1, height = 1 ) {
  38163. super();
  38164. this.image = { width, height };
  38165. this.magFilter = LinearFilter;
  38166. this.minFilter = LinearFilter;
  38167. this.isStorageTexture = true;
  38168. }
  38169. }
  38170. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  38171. constructor( array, itemSize ) {
  38172. super( array, itemSize, Uint32Array );
  38173. this.isIndirectStorageBufferAttribute = true;
  38174. }
  38175. }
  38176. /**
  38177. * A loader for loading node objects in the three.js JSON Object/Scene format.
  38178. *
  38179. * @augments Loader
  38180. */
  38181. class NodeLoader extends Loader {
  38182. /**
  38183. * Constructs a new node loader.
  38184. *
  38185. * @param {LoadingManager?} manager - A reference to a loading manager.
  38186. */
  38187. constructor( manager ) {
  38188. super( manager );
  38189. /**
  38190. * Represents a dictionary of textures.
  38191. *
  38192. * @type {Object<String,Texture>}
  38193. */
  38194. this.textures = {};
  38195. /**
  38196. * Represents a dictionary of node types.
  38197. *
  38198. * @type {Object<String,Node.constructor>}
  38199. */
  38200. this.nodes = {};
  38201. }
  38202. /**
  38203. * Loads the node definitions from the given URL.
  38204. *
  38205. * @param {String} url - The path/URL of the file to be loaded.
  38206. * @param {Function} onLoad - Will be called when load completes.
  38207. * @param {Function} onProgress - Will be called while load progresses.
  38208. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  38209. */
  38210. load( url, onLoad, onProgress, onError ) {
  38211. const loader = new FileLoader( this.manager );
  38212. loader.setPath( this.path );
  38213. loader.setRequestHeader( this.requestHeader );
  38214. loader.setWithCredentials( this.withCredentials );
  38215. loader.load( url, ( text ) => {
  38216. try {
  38217. onLoad( this.parse( JSON.parse( text ) ) );
  38218. } catch ( e ) {
  38219. if ( onError ) {
  38220. onError( e );
  38221. } else {
  38222. console.error( e );
  38223. }
  38224. this.manager.itemError( url );
  38225. }
  38226. }, onProgress, onError );
  38227. }
  38228. /**
  38229. * Parse the node dependencies for the loaded node.
  38230. *
  38231. * @param {Object} json - The JSON definition
  38232. * @return {Object<String,Node>} A dictionary with node dependencies.
  38233. */
  38234. parseNodes( json ) {
  38235. const nodes = {};
  38236. if ( json !== undefined ) {
  38237. for ( const nodeJSON of json ) {
  38238. const { uuid, type } = nodeJSON;
  38239. nodes[ uuid ] = this.createNodeFromType( type );
  38240. nodes[ uuid ].uuid = uuid;
  38241. }
  38242. const meta = { nodes, textures: this.textures };
  38243. for ( const nodeJSON of json ) {
  38244. nodeJSON.meta = meta;
  38245. const node = nodes[ nodeJSON.uuid ];
  38246. node.deserialize( nodeJSON );
  38247. delete nodeJSON.meta;
  38248. }
  38249. }
  38250. return nodes;
  38251. }
  38252. /**
  38253. * Parses the node from the given JSON.
  38254. *
  38255. * @param {Object} json - The JSON definition
  38256. * @return {Node} The parsed node.
  38257. */
  38258. parse( json ) {
  38259. const node = this.createNodeFromType( json.type );
  38260. node.uuid = json.uuid;
  38261. const nodes = this.parseNodes( json.nodes );
  38262. const meta = { nodes, textures: this.textures };
  38263. json.meta = meta;
  38264. node.deserialize( json );
  38265. delete json.meta;
  38266. return node;
  38267. }
  38268. /**
  38269. * Defines the dictionary of textures.
  38270. *
  38271. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  38272. * @return {NodeLoader} A reference to this loader.
  38273. */
  38274. setTextures( value ) {
  38275. this.textures = value;
  38276. return this;
  38277. }
  38278. /**
  38279. * Defines the dictionary of node types.
  38280. *
  38281. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38282. * @return {NodeLoader} A reference to this loader.
  38283. */
  38284. setNodes( value ) {
  38285. this.nodes = value;
  38286. return this;
  38287. }
  38288. /**
  38289. * Creates a node object from the given type.
  38290. *
  38291. * @param {String} type - The node type.
  38292. * @return {Node} The created node instance.
  38293. */
  38294. createNodeFromType( type ) {
  38295. if ( this.nodes[ type ] === undefined ) {
  38296. console.error( 'THREE.NodeLoader: Node type not found:', type );
  38297. return float();
  38298. }
  38299. return nodeObject( new this.nodes[ type ]() );
  38300. }
  38301. }
  38302. /**
  38303. * A special type of material loader for loading node materials.
  38304. *
  38305. * @augments MaterialLoader
  38306. */
  38307. class NodeMaterialLoader extends MaterialLoader {
  38308. /**
  38309. * Constructs a new node material loader.
  38310. *
  38311. * @param {LoadingManager?} manager - A reference to a loading manager.
  38312. */
  38313. constructor( manager ) {
  38314. super( manager );
  38315. /**
  38316. * Represents a dictionary of node types.
  38317. *
  38318. * @type {Object<String,Node.constructor>}
  38319. */
  38320. this.nodes = {};
  38321. /**
  38322. * Represents a dictionary of node material types.
  38323. *
  38324. * @type {Object<String,NodeMaterial.constructor>}
  38325. */
  38326. this.nodeMaterials = {};
  38327. }
  38328. /**
  38329. * Parses the node material from the given JSON.
  38330. *
  38331. * @param {Object} json - The JSON definition
  38332. * @return {NodeMaterial}. The parsed material.
  38333. */
  38334. parse( json ) {
  38335. const material = super.parse( json );
  38336. const nodes = this.nodes;
  38337. const inputNodes = json.inputNodes;
  38338. for ( const property in inputNodes ) {
  38339. const uuid = inputNodes[ property ];
  38340. material[ property ] = nodes[ uuid ];
  38341. }
  38342. return material;
  38343. }
  38344. /**
  38345. * Defines the dictionary of node types.
  38346. *
  38347. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38348. * @return {NodeLoader} A reference to this loader.
  38349. */
  38350. setNodes( value ) {
  38351. this.nodes = value;
  38352. return this;
  38353. }
  38354. /**
  38355. * Defines the dictionary of node material types.
  38356. *
  38357. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  38358. * @return {NodeLoader} A reference to this loader.
  38359. */
  38360. setNodeMaterials( value ) {
  38361. this.nodeMaterials = value;
  38362. return this;
  38363. }
  38364. /**
  38365. * Creates a node material from the given type.
  38366. *
  38367. * @param {String} type - The node material type.
  38368. * @return {Node} The created node material instance.
  38369. */
  38370. createMaterialFromType( type ) {
  38371. const materialClass = this.nodeMaterials[ type ];
  38372. if ( materialClass !== undefined ) {
  38373. return new materialClass();
  38374. }
  38375. return super.createMaterialFromType( type );
  38376. }
  38377. }
  38378. /**
  38379. * A special type of object loader for loading 3D objects using
  38380. * node materials.
  38381. *
  38382. * @augments ObjectLoader
  38383. */
  38384. class NodeObjectLoader extends ObjectLoader {
  38385. /**
  38386. * Constructs a new node object loader.
  38387. *
  38388. * @param {LoadingManager?} manager - A reference to a loading manager.
  38389. */
  38390. constructor( manager ) {
  38391. super( manager );
  38392. /**
  38393. * Represents a dictionary of node types.
  38394. *
  38395. * @type {Object<String,Node.constructor>}
  38396. */
  38397. this.nodes = {};
  38398. /**
  38399. * Represents a dictionary of node material types.
  38400. *
  38401. * @type {Object<String,NodeMaterial.constructor>}
  38402. */
  38403. this.nodeMaterials = {};
  38404. /**
  38405. * A reference for holdng the `nodes` JSON property.
  38406. *
  38407. * @private
  38408. * @type {Object?}
  38409. */
  38410. this._nodesJSON = null;
  38411. }
  38412. /**
  38413. * Defines the dictionary of node types.
  38414. *
  38415. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38416. * @return {NodeLoader} A reference to this loader.
  38417. */
  38418. setNodes( value ) {
  38419. this.nodes = value;
  38420. return this;
  38421. }
  38422. /**
  38423. * Defines the dictionary of node material types.
  38424. *
  38425. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  38426. * @return {NodeLoader} A reference to this loader.
  38427. */
  38428. setNodeMaterials( value ) {
  38429. this.nodeMaterials = value;
  38430. return this;
  38431. }
  38432. /**
  38433. * Parses the node objects from the given JSON.
  38434. *
  38435. * @param {Object} json - The JSON definition
  38436. * @param {Function} onLoad - The onLoad callback function.
  38437. * @return {Object3D}. The parsed 3D object.
  38438. */
  38439. parse( json, onLoad ) {
  38440. this._nodesJSON = json.nodes;
  38441. const data = super.parse( json, onLoad );
  38442. this._nodesJSON = null; // dispose
  38443. return data;
  38444. }
  38445. /**
  38446. * Parses the node objects from the given JSON and textures.
  38447. *
  38448. * @param {Object} json - The JSON definition
  38449. * @param {Object<String,Texture>} textures - The texture library.
  38450. * @return {Object<String,Node>}. The parsed nodes.
  38451. */
  38452. parseNodes( json, textures ) {
  38453. if ( json !== undefined ) {
  38454. const loader = new NodeLoader();
  38455. loader.setNodes( this.nodes );
  38456. loader.setTextures( textures );
  38457. return loader.parseNodes( json );
  38458. }
  38459. return {};
  38460. }
  38461. /**
  38462. * Parses the node objects from the given JSON and textures.
  38463. *
  38464. * @param {Object} json - The JSON definition
  38465. * @param {Object<String,Texture>} textures - The texture library.
  38466. * @return {Object<String,NodeMaterial>}. The parsed materials.
  38467. */
  38468. parseMaterials( json, textures ) {
  38469. const materials = {};
  38470. if ( json !== undefined ) {
  38471. const nodes = this.parseNodes( this._nodesJSON, textures );
  38472. const loader = new NodeMaterialLoader();
  38473. loader.setTextures( textures );
  38474. loader.setNodes( nodes );
  38475. loader.setNodeMaterials( this.nodeMaterials );
  38476. for ( let i = 0, l = json.length; i < l; i ++ ) {
  38477. const data = json[ i ];
  38478. materials[ data.uuid ] = loader.parse( data );
  38479. }
  38480. }
  38481. return materials;
  38482. }
  38483. }
  38484. class ClippingGroup extends Group {
  38485. constructor() {
  38486. super();
  38487. this.isClippingGroup = true;
  38488. this.clippingPlanes = [];
  38489. this.enabled = true;
  38490. this.clipIntersection = false;
  38491. this.clipShadows = false;
  38492. }
  38493. }
  38494. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, 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, InstancedPointsNodeMaterial, 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, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号