three.webgpu.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262
  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 StandardNodeLibrary extends NodeLibrary {
  38066. constructor() {
  38067. super();
  38068. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  38069. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  38070. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  38071. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  38072. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  38073. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  38074. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  38075. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  38076. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  38077. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  38078. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  38079. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  38080. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  38081. this.addLight( PointLightNode, PointLight );
  38082. this.addLight( DirectionalLightNode, DirectionalLight );
  38083. this.addLight( RectAreaLightNode, RectAreaLight );
  38084. this.addLight( SpotLightNode, SpotLight );
  38085. this.addLight( AmbientLightNode, AmbientLight );
  38086. this.addLight( HemisphereLightNode, HemisphereLight );
  38087. this.addLight( LightProbeNode, LightProbe );
  38088. this.addLight( IESSpotLightNode, IESSpotLight );
  38089. this.addToneMapping( linearToneMapping, LinearToneMapping );
  38090. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  38091. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  38092. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  38093. this.addToneMapping( agxToneMapping, AgXToneMapping );
  38094. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  38095. }
  38096. }
  38097. /*
  38098. const debugHandler = {
  38099. get: function ( target, name ) {
  38100. // Add |update
  38101. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  38102. return target[ name ];
  38103. }
  38104. };
  38105. */
  38106. class WebGPURenderer extends Renderer {
  38107. constructor( parameters = {} ) {
  38108. let BackendClass;
  38109. if ( parameters.forceWebGL ) {
  38110. BackendClass = WebGLBackend;
  38111. } else {
  38112. BackendClass = WebGPUBackend;
  38113. parameters.getFallback = () => {
  38114. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  38115. return new WebGLBackend( parameters );
  38116. };
  38117. }
  38118. const backend = new BackendClass( parameters );
  38119. //super( new Proxy( backend, debugHandler ) );
  38120. super( backend, parameters );
  38121. this.library = new StandardNodeLibrary();
  38122. this.isWebGPURenderer = true;
  38123. }
  38124. }
  38125. class BundleGroup extends Group {
  38126. constructor() {
  38127. super();
  38128. this.isBundleGroup = true;
  38129. this.type = 'BundleGroup';
  38130. this.static = true;
  38131. this.version = 0;
  38132. }
  38133. set needsUpdate( value ) {
  38134. if ( value === true ) this.version ++;
  38135. }
  38136. }
  38137. const _material = /*@__PURE__*/ new NodeMaterial();
  38138. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  38139. class PostProcessing {
  38140. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  38141. this.renderer = renderer;
  38142. this.outputNode = outputNode;
  38143. this.outputColorTransform = true;
  38144. this.needsUpdate = true;
  38145. _material.name = 'PostProcessing';
  38146. }
  38147. render() {
  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. _quadMesh.render( renderer );
  38156. //
  38157. renderer.toneMapping = toneMapping;
  38158. renderer.outputColorSpace = outputColorSpace;
  38159. }
  38160. update() {
  38161. if ( this.needsUpdate === true ) {
  38162. const renderer = this.renderer;
  38163. const toneMapping = renderer.toneMapping;
  38164. const outputColorSpace = renderer.outputColorSpace;
  38165. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  38166. _quadMesh.material.needsUpdate = true;
  38167. this.needsUpdate = false;
  38168. }
  38169. }
  38170. async renderAsync() {
  38171. this.update();
  38172. const renderer = this.renderer;
  38173. const toneMapping = renderer.toneMapping;
  38174. const outputColorSpace = renderer.outputColorSpace;
  38175. renderer.toneMapping = NoToneMapping;
  38176. renderer.outputColorSpace = LinearSRGBColorSpace;
  38177. //
  38178. await _quadMesh.renderAsync( renderer );
  38179. //
  38180. renderer.toneMapping = toneMapping;
  38181. renderer.outputColorSpace = outputColorSpace;
  38182. }
  38183. }
  38184. class StorageTexture extends Texture {
  38185. constructor( width = 1, height = 1 ) {
  38186. super();
  38187. this.image = { width, height };
  38188. this.magFilter = LinearFilter;
  38189. this.minFilter = LinearFilter;
  38190. this.isStorageTexture = true;
  38191. }
  38192. }
  38193. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  38194. constructor( array, itemSize ) {
  38195. super( array, itemSize, Uint32Array );
  38196. this.isIndirectStorageBufferAttribute = true;
  38197. }
  38198. }
  38199. /**
  38200. * A loader for loading node objects in the three.js JSON Object/Scene format.
  38201. *
  38202. * @augments Loader
  38203. */
  38204. class NodeLoader extends Loader {
  38205. /**
  38206. * Constructs a new node loader.
  38207. *
  38208. * @param {LoadingManager?} manager - A reference to a loading manager.
  38209. */
  38210. constructor( manager ) {
  38211. super( manager );
  38212. /**
  38213. * Represents a dictionary of textures.
  38214. *
  38215. * @type {Object<String,Texture>}
  38216. */
  38217. this.textures = {};
  38218. /**
  38219. * Represents a dictionary of node types.
  38220. *
  38221. * @type {Object<String,Node.constructor>}
  38222. */
  38223. this.nodes = {};
  38224. }
  38225. /**
  38226. * Loads the node definitions from the given URL.
  38227. *
  38228. * @param {String} url - The path/URL of the file to be loaded.
  38229. * @param {Function} onLoad - Will be called when load completes.
  38230. * @param {Function} onProgress - Will be called while load progresses.
  38231. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  38232. */
  38233. load( url, onLoad, onProgress, onError ) {
  38234. const loader = new FileLoader( this.manager );
  38235. loader.setPath( this.path );
  38236. loader.setRequestHeader( this.requestHeader );
  38237. loader.setWithCredentials( this.withCredentials );
  38238. loader.load( url, ( text ) => {
  38239. try {
  38240. onLoad( this.parse( JSON.parse( text ) ) );
  38241. } catch ( e ) {
  38242. if ( onError ) {
  38243. onError( e );
  38244. } else {
  38245. console.error( e );
  38246. }
  38247. this.manager.itemError( url );
  38248. }
  38249. }, onProgress, onError );
  38250. }
  38251. /**
  38252. * Parse the node dependencies for the loaded node.
  38253. *
  38254. * @param {Object} json - The JSON definition
  38255. * @return {Object<String,Node>} A dictionary with node dependencies.
  38256. */
  38257. parseNodes( json ) {
  38258. const nodes = {};
  38259. if ( json !== undefined ) {
  38260. for ( const nodeJSON of json ) {
  38261. const { uuid, type } = nodeJSON;
  38262. nodes[ uuid ] = this.createNodeFromType( type );
  38263. nodes[ uuid ].uuid = uuid;
  38264. }
  38265. const meta = { nodes, textures: this.textures };
  38266. for ( const nodeJSON of json ) {
  38267. nodeJSON.meta = meta;
  38268. const node = nodes[ nodeJSON.uuid ];
  38269. node.deserialize( nodeJSON );
  38270. delete nodeJSON.meta;
  38271. }
  38272. }
  38273. return nodes;
  38274. }
  38275. /**
  38276. * Parses the node from the given JSON.
  38277. *
  38278. * @param {Object} json - The JSON definition
  38279. * @return {Node} The parsed node.
  38280. */
  38281. parse( json ) {
  38282. const node = this.createNodeFromType( json.type );
  38283. node.uuid = json.uuid;
  38284. const nodes = this.parseNodes( json.nodes );
  38285. const meta = { nodes, textures: this.textures };
  38286. json.meta = meta;
  38287. node.deserialize( json );
  38288. delete json.meta;
  38289. return node;
  38290. }
  38291. /**
  38292. * Defines the dictionary of textures.
  38293. *
  38294. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  38295. * @return {NodeLoader} A reference to this loader.
  38296. */
  38297. setTextures( value ) {
  38298. this.textures = value;
  38299. return this;
  38300. }
  38301. /**
  38302. * Defines the dictionary of node types.
  38303. *
  38304. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38305. * @return {NodeLoader} A reference to this loader.
  38306. */
  38307. setNodes( value ) {
  38308. this.nodes = value;
  38309. return this;
  38310. }
  38311. /**
  38312. * Creates a node object from the given type.
  38313. *
  38314. * @param {String} type - The node type.
  38315. * @return {Node} The created node instance.
  38316. */
  38317. createNodeFromType( type ) {
  38318. if ( this.nodes[ type ] === undefined ) {
  38319. console.error( 'THREE.NodeLoader: Node type not found:', type );
  38320. return float();
  38321. }
  38322. return nodeObject( new this.nodes[ type ]() );
  38323. }
  38324. }
  38325. /**
  38326. * A special type of material loader for loading node materials.
  38327. *
  38328. * @augments MaterialLoader
  38329. */
  38330. class NodeMaterialLoader extends MaterialLoader {
  38331. /**
  38332. * Constructs a new node material loader.
  38333. *
  38334. * @param {LoadingManager?} manager - A reference to a loading manager.
  38335. */
  38336. constructor( manager ) {
  38337. super( manager );
  38338. /**
  38339. * Represents a dictionary of node types.
  38340. *
  38341. * @type {Object<String,Node.constructor>}
  38342. */
  38343. this.nodes = {};
  38344. /**
  38345. * Represents a dictionary of node material types.
  38346. *
  38347. * @type {Object<String,NodeMaterial.constructor>}
  38348. */
  38349. this.nodeMaterials = {};
  38350. }
  38351. /**
  38352. * Parses the node material from the given JSON.
  38353. *
  38354. * @param {Object} json - The JSON definition
  38355. * @return {NodeMaterial}. The parsed material.
  38356. */
  38357. parse( json ) {
  38358. const material = super.parse( json );
  38359. const nodes = this.nodes;
  38360. const inputNodes = json.inputNodes;
  38361. for ( const property in inputNodes ) {
  38362. const uuid = inputNodes[ property ];
  38363. material[ property ] = nodes[ uuid ];
  38364. }
  38365. return material;
  38366. }
  38367. /**
  38368. * Defines the dictionary of node types.
  38369. *
  38370. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38371. * @return {NodeLoader} A reference to this loader.
  38372. */
  38373. setNodes( value ) {
  38374. this.nodes = value;
  38375. return this;
  38376. }
  38377. /**
  38378. * Defines the dictionary of node material types.
  38379. *
  38380. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  38381. * @return {NodeLoader} A reference to this loader.
  38382. */
  38383. setNodeMaterials( value ) {
  38384. this.nodeMaterials = value;
  38385. return this;
  38386. }
  38387. /**
  38388. * Creates a node material from the given type.
  38389. *
  38390. * @param {String} type - The node material type.
  38391. * @return {Node} The created node material instance.
  38392. */
  38393. createMaterialFromType( type ) {
  38394. const materialClass = this.nodeMaterials[ type ];
  38395. if ( materialClass !== undefined ) {
  38396. return new materialClass();
  38397. }
  38398. return super.createMaterialFromType( type );
  38399. }
  38400. }
  38401. /**
  38402. * A special type of object loader for loading 3D objects using
  38403. * node materials.
  38404. *
  38405. * @augments ObjectLoader
  38406. */
  38407. class NodeObjectLoader extends ObjectLoader {
  38408. /**
  38409. * Constructs a new node object loader.
  38410. *
  38411. * @param {LoadingManager?} manager - A reference to a loading manager.
  38412. */
  38413. constructor( manager ) {
  38414. super( manager );
  38415. /**
  38416. * Represents a dictionary of node types.
  38417. *
  38418. * @type {Object<String,Node.constructor>}
  38419. */
  38420. this.nodes = {};
  38421. /**
  38422. * Represents a dictionary of node material types.
  38423. *
  38424. * @type {Object<String,NodeMaterial.constructor>}
  38425. */
  38426. this.nodeMaterials = {};
  38427. /**
  38428. * A reference for holdng the `nodes` JSON property.
  38429. *
  38430. * @private
  38431. * @type {Object?}
  38432. */
  38433. this._nodesJSON = null;
  38434. }
  38435. /**
  38436. * Defines the dictionary of node types.
  38437. *
  38438. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  38439. * @return {NodeLoader} A reference to this loader.
  38440. */
  38441. setNodes( value ) {
  38442. this.nodes = value;
  38443. return this;
  38444. }
  38445. /**
  38446. * Defines the dictionary of node material types.
  38447. *
  38448. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  38449. * @return {NodeLoader} A reference to this loader.
  38450. */
  38451. setNodeMaterials( value ) {
  38452. this.nodeMaterials = value;
  38453. return this;
  38454. }
  38455. /**
  38456. * Parses the node objects from the given JSON.
  38457. *
  38458. * @param {Object} json - The JSON definition
  38459. * @param {Function} onLoad - The onLoad callback function.
  38460. * @return {Object3D}. The parsed 3D object.
  38461. */
  38462. parse( json, onLoad ) {
  38463. this._nodesJSON = json.nodes;
  38464. const data = super.parse( json, onLoad );
  38465. this._nodesJSON = null; // dispose
  38466. return data;
  38467. }
  38468. /**
  38469. * Parses the node objects from the given JSON and textures.
  38470. *
  38471. * @param {Object} json - The JSON definition
  38472. * @param {Object<String,Texture>} textures - The texture library.
  38473. * @return {Object<String,Node>}. The parsed nodes.
  38474. */
  38475. parseNodes( json, textures ) {
  38476. if ( json !== undefined ) {
  38477. const loader = new NodeLoader();
  38478. loader.setNodes( this.nodes );
  38479. loader.setTextures( textures );
  38480. return loader.parseNodes( json );
  38481. }
  38482. return {};
  38483. }
  38484. /**
  38485. * Parses the node objects from the given JSON and textures.
  38486. *
  38487. * @param {Object} json - The JSON definition
  38488. * @param {Object<String,Texture>} textures - The texture library.
  38489. * @return {Object<String,NodeMaterial>}. The parsed materials.
  38490. */
  38491. parseMaterials( json, textures ) {
  38492. const materials = {};
  38493. if ( json !== undefined ) {
  38494. const nodes = this.parseNodes( this._nodesJSON, textures );
  38495. const loader = new NodeMaterialLoader();
  38496. loader.setTextures( textures );
  38497. loader.setNodes( nodes );
  38498. loader.setNodeMaterials( this.nodeMaterials );
  38499. for ( let i = 0, l = json.length; i < l; i ++ ) {
  38500. const data = json[ i ];
  38501. materials[ data.uuid ] = loader.parse( data );
  38502. }
  38503. }
  38504. return materials;
  38505. }
  38506. }
  38507. class ClippingGroup extends Group {
  38508. constructor() {
  38509. super();
  38510. this.isClippingGroup = true;
  38511. this.clippingPlanes = [];
  38512. this.enabled = true;
  38513. this.clipIntersection = false;
  38514. this.clipShadows = false;
  38515. }
  38516. }
  38517. 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号