three.webgpu.nodes.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501
  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, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, 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. class NodeMaterialObserver {
  61. constructor( builder ) {
  62. this.renderObjects = new WeakMap();
  63. this.hasNode = this.containsNode( builder );
  64. this.hasAnimation = builder.object.isSkinnedMesh === true;
  65. this.refreshUniforms = refreshUniforms;
  66. this.renderId = 0;
  67. }
  68. firstInitialization( renderObject ) {
  69. const hasInitialized = this.renderObjects.has( renderObject );
  70. if ( hasInitialized === false ) {
  71. this.getRenderObjectData( renderObject );
  72. return true;
  73. }
  74. return false;
  75. }
  76. getRenderObjectData( renderObject ) {
  77. let data = this.renderObjects.get( renderObject );
  78. if ( data === undefined ) {
  79. const { geometry, material, object } = renderObject;
  80. data = {
  81. material: this.getMaterialData( material ),
  82. geometry: {
  83. attributes: this.getAttributesData( geometry.attributes ),
  84. indexVersion: geometry.index ? geometry.index.version : null,
  85. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  86. },
  87. worldMatrix: object.matrixWorld.clone()
  88. };
  89. if ( object.center ) {
  90. data.center = object.center.clone();
  91. }
  92. if ( object.morphTargetInfluences ) {
  93. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  94. }
  95. if ( renderObject.bundle !== null ) {
  96. data.version = renderObject.bundle.version;
  97. }
  98. if ( data.material.transmission > 0 ) {
  99. const { width, height } = renderObject.context;
  100. data.bufferWidth = width;
  101. data.bufferHeight = height;
  102. }
  103. this.renderObjects.set( renderObject, data );
  104. }
  105. return data;
  106. }
  107. getAttributesData( attributes ) {
  108. const attributesData = {};
  109. for ( const name in attributes ) {
  110. const attribute = attributes[ name ];
  111. attributesData[ name ] = {
  112. version: attribute.version
  113. };
  114. }
  115. return attributesData;
  116. }
  117. containsNode( builder ) {
  118. const material = builder.material;
  119. for ( const property in material ) {
  120. if ( material[ property ] && material[ property ].isNode )
  121. return true;
  122. }
  123. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  124. return true;
  125. return false;
  126. }
  127. getMaterialData( material ) {
  128. const data = {};
  129. for ( const property of this.refreshUniforms ) {
  130. const value = material[ property ];
  131. if ( value === null || value === undefined ) continue;
  132. if ( typeof value === 'object' && value.clone !== undefined ) {
  133. if ( value.isTexture === true ) {
  134. data[ property ] = { id: value.id, version: value.version };
  135. } else {
  136. data[ property ] = value.clone();
  137. }
  138. } else {
  139. data[ property ] = value;
  140. }
  141. }
  142. return data;
  143. }
  144. equals( renderObject ) {
  145. const { object, material, geometry } = renderObject;
  146. const renderObjectData = this.getRenderObjectData( renderObject );
  147. // world matrix
  148. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  149. renderObjectData.worldMatrix.copy( object.matrixWorld );
  150. return false;
  151. }
  152. // material
  153. const materialData = renderObjectData.material;
  154. for ( const property in materialData ) {
  155. const value = materialData[ property ];
  156. const mtlValue = material[ property ];
  157. if ( value.equals !== undefined ) {
  158. if ( value.equals( mtlValue ) === false ) {
  159. value.copy( mtlValue );
  160. return false;
  161. }
  162. } else if ( mtlValue.isTexture === true ) {
  163. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  164. value.id = mtlValue.id;
  165. value.version = mtlValue.version;
  166. return false;
  167. }
  168. } else if ( value !== mtlValue ) {
  169. materialData[ property ] = mtlValue;
  170. return false;
  171. }
  172. }
  173. if ( materialData.transmission > 0 ) {
  174. const { width, height } = renderObject.context;
  175. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  176. renderObjectData.bufferWidth = width;
  177. renderObjectData.bufferHeight = height;
  178. return false;
  179. }
  180. }
  181. // geometry
  182. const storedGeometryData = renderObjectData.geometry;
  183. const attributes = geometry.attributes;
  184. const storedAttributes = storedGeometryData.attributes;
  185. const storedAttributeNames = Object.keys( storedAttributes );
  186. const currentAttributeNames = Object.keys( attributes );
  187. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  188. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  189. return false;
  190. }
  191. // compare each attribute
  192. for ( const name of storedAttributeNames ) {
  193. const storedAttributeData = storedAttributes[ name ];
  194. const attribute = attributes[ name ];
  195. if ( attribute === undefined ) {
  196. // attribute was removed
  197. delete storedAttributes[ name ];
  198. return false;
  199. }
  200. if ( storedAttributeData.version !== attribute.version ) {
  201. storedAttributeData.version = attribute.version;
  202. return false;
  203. }
  204. }
  205. // check index
  206. const index = geometry.index;
  207. const storedIndexVersion = storedGeometryData.indexVersion;
  208. const currentIndexVersion = index ? index.version : null;
  209. if ( storedIndexVersion !== currentIndexVersion ) {
  210. storedGeometryData.indexVersion = currentIndexVersion;
  211. return false;
  212. }
  213. // check drawRange
  214. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  215. storedGeometryData.drawRange.start = geometry.drawRange.start;
  216. storedGeometryData.drawRange.count = geometry.drawRange.count;
  217. return false;
  218. }
  219. // morph targets
  220. if ( renderObjectData.morphTargetInfluences ) {
  221. let morphChanged = false;
  222. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  223. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  224. morphChanged = true;
  225. }
  226. }
  227. if ( morphChanged ) return true;
  228. }
  229. // center
  230. if ( renderObjectData.center ) {
  231. if ( renderObjectData.center.equals( object.center ) === false ) {
  232. renderObjectData.center.copy( object.center );
  233. return true;
  234. }
  235. }
  236. // bundle
  237. if ( renderObject.bundle !== null ) {
  238. renderObjectData.version = renderObject.bundle.version;
  239. }
  240. return true;
  241. }
  242. needsRefresh( renderObject, nodeFrame ) {
  243. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  244. return true;
  245. const { renderId } = nodeFrame;
  246. if ( this.renderId !== renderId ) {
  247. this.renderId = renderId;
  248. return true;
  249. }
  250. const isStatic = renderObject.object.static === true;
  251. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  252. if ( isStatic || isBundle )
  253. return false;
  254. const notEqual = this.equals( renderObject ) !== true;
  255. return notEqual;
  256. }
  257. }
  258. /** @module NodeUtils **/
  259. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  260. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  261. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  262. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  263. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  264. function cyrb53( value, seed = 0 ) {
  265. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  266. if ( value instanceof Array ) {
  267. for ( let i = 0, val; i < value.length; i ++ ) {
  268. val = value[ i ];
  269. h1 = Math.imul( h1 ^ val, 2654435761 );
  270. h2 = Math.imul( h2 ^ val, 1597334677 );
  271. }
  272. } else {
  273. for ( let i = 0, ch; i < value.length; i ++ ) {
  274. ch = value.charCodeAt( i );
  275. h1 = Math.imul( h1 ^ ch, 2654435761 );
  276. h2 = Math.imul( h2 ^ ch, 1597334677 );
  277. }
  278. }
  279. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  280. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  281. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  282. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  283. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  284. }
  285. /**
  286. * Computes a hash for the given string.
  287. *
  288. * @method
  289. * @param {String} str - The string to be hashed.
  290. * @return {Number} The hash.
  291. */
  292. const hashString = ( str ) => cyrb53( str );
  293. /**
  294. * Computes a hash for the given array.
  295. *
  296. * @method
  297. * @param {Array<Number>} array - The array to be hashed.
  298. * @return {Number} The hash.
  299. */
  300. const hashArray = ( array ) => cyrb53( array );
  301. /**
  302. * Computes a hash for the given list of parameters.
  303. *
  304. * @method
  305. * @param {...Number} params - A list of parameters.
  306. * @return {Number} The hash.
  307. */
  308. const hash$1 = ( ...params ) => cyrb53( params );
  309. /**
  310. * Computes a cache key for the given node.
  311. *
  312. * @method
  313. * @param {Object} object - The object to be hashed.
  314. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  315. * @return {Number} The hash.
  316. */
  317. function getCacheKey$1( object, force = false ) {
  318. const values = [];
  319. if ( object.isNode === true ) {
  320. values.push( object.id );
  321. object = object.getSelf();
  322. }
  323. for ( const { property, childNode } of getNodeChildren( object ) ) {
  324. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  325. }
  326. return cyrb53( values );
  327. }
  328. /**
  329. * This generator function can be used to iterate over the node children
  330. * of the given object.
  331. *
  332. * @generator
  333. * @param {Object} node - The object to be hashed.
  334. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  335. * @yields {Object} A result node holding the property, index (if available) and the child node.
  336. */
  337. function* getNodeChildren( node, toJSON = false ) {
  338. for ( const property in node ) {
  339. // Ignore private properties.
  340. if ( property.startsWith( '_' ) === true ) continue;
  341. const object = node[ property ];
  342. if ( Array.isArray( object ) === true ) {
  343. for ( let i = 0; i < object.length; i ++ ) {
  344. const child = object[ i ];
  345. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  346. yield { property, index: i, childNode: child };
  347. }
  348. }
  349. } else if ( object && object.isNode === true ) {
  350. yield { property, childNode: object };
  351. } else if ( typeof object === 'object' ) {
  352. for ( const subProperty in object ) {
  353. const child = object[ subProperty ];
  354. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  355. yield { property, index: subProperty, childNode: child };
  356. }
  357. }
  358. }
  359. }
  360. }
  361. const typeFromLength = /*@__PURE__*/ new Map( [
  362. [ 1, 'float' ],
  363. [ 2, 'vec2' ],
  364. [ 3, 'vec3' ],
  365. [ 4, 'vec4' ],
  366. [ 9, 'mat3' ],
  367. [ 16, 'mat4' ]
  368. ] );
  369. /**
  370. * Returns the data type for the given the length.
  371. *
  372. * @method
  373. * @param {Number} length - The length.
  374. * @return {String} The data type.
  375. */
  376. function getTypeFromLength( length ) {
  377. return typeFromLength.get( length );
  378. }
  379. /**
  380. * Returns the length for the given data type.
  381. *
  382. * @method
  383. * @param {String} type - The data type.
  384. * @return {Number} The length.
  385. */
  386. function getLengthFromType( type ) {
  387. if ( /float|int|uint/.test( type ) ) return 1;
  388. if ( /vec2/.test( type ) ) return 2;
  389. if ( /vec3/.test( type ) ) return 3;
  390. if ( /vec4/.test( type ) ) return 4;
  391. if ( /mat3/.test( type ) ) return 9;
  392. if ( /mat4/.test( type ) ) return 16;
  393. console.error( 'THREE.TSL: Unsupported type:', type );
  394. }
  395. /**
  396. * Returns the data type for the given value.
  397. *
  398. * @method
  399. * @param {Any} value - The value.
  400. * @return {String?} The data type.
  401. */
  402. function getValueType( value ) {
  403. if ( value === undefined || value === null ) return null;
  404. const typeOf = typeof value;
  405. if ( value.isNode === true ) {
  406. return 'node';
  407. } else if ( typeOf === 'number' ) {
  408. return 'float';
  409. } else if ( typeOf === 'boolean' ) {
  410. return 'bool';
  411. } else if ( typeOf === 'string' ) {
  412. return 'string';
  413. } else if ( typeOf === 'function' ) {
  414. return 'shader';
  415. } else if ( value.isVector2 === true ) {
  416. return 'vec2';
  417. } else if ( value.isVector3 === true ) {
  418. return 'vec3';
  419. } else if ( value.isVector4 === true ) {
  420. return 'vec4';
  421. } else if ( value.isMatrix3 === true ) {
  422. return 'mat3';
  423. } else if ( value.isMatrix4 === true ) {
  424. return 'mat4';
  425. } else if ( value.isColor === true ) {
  426. return 'color';
  427. } else if ( value instanceof ArrayBuffer ) {
  428. return 'ArrayBuffer';
  429. }
  430. return null;
  431. }
  432. /**
  433. * Returns the value/object for the given data type and parameters.
  434. *
  435. * @method
  436. * @param {String} type - The given type.
  437. * @param {...Any} params - A parameter list.
  438. * @return {Any} The value/object.
  439. */
  440. function getValueFromType( type, ...params ) {
  441. const last4 = type ? type.slice( - 4 ) : undefined;
  442. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  443. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  444. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  445. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  446. }
  447. if ( type === 'color' ) {
  448. return new Color( ...params );
  449. } else if ( last4 === 'vec2' ) {
  450. return new Vector2( ...params );
  451. } else if ( last4 === 'vec3' ) {
  452. return new Vector3( ...params );
  453. } else if ( last4 === 'vec4' ) {
  454. return new Vector4( ...params );
  455. } else if ( last4 === 'mat3' ) {
  456. return new Matrix3( ...params );
  457. } else if ( last4 === 'mat4' ) {
  458. return new Matrix4( ...params );
  459. } else if ( type === 'bool' ) {
  460. return params[ 0 ] || false;
  461. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  462. return params[ 0 ] || 0;
  463. } else if ( type === 'string' ) {
  464. return params[ 0 ] || '';
  465. } else if ( type === 'ArrayBuffer' ) {
  466. return base64ToArrayBuffer( params[ 0 ] );
  467. }
  468. return null;
  469. }
  470. /**
  471. * Converts the given array buffer to a Base64 string.
  472. *
  473. * @method
  474. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  475. * @return {String} The Base64 string.
  476. */
  477. function arrayBufferToBase64( arrayBuffer ) {
  478. let chars = '';
  479. const array = new Uint8Array( arrayBuffer );
  480. for ( let i = 0; i < array.length; i ++ ) {
  481. chars += String.fromCharCode( array[ i ] );
  482. }
  483. return btoa( chars );
  484. }
  485. /**
  486. * Converts the given Base64 string to an array buffer.
  487. *
  488. * @method
  489. * @param {String} base64 - The Base64 string.
  490. * @return {ArrayBuffer} The array buffer.
  491. */
  492. function base64ToArrayBuffer( base64 ) {
  493. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  494. }
  495. var NodeUtils = /*#__PURE__*/Object.freeze({
  496. __proto__: null,
  497. arrayBufferToBase64: arrayBufferToBase64,
  498. base64ToArrayBuffer: base64ToArrayBuffer,
  499. getCacheKey: getCacheKey$1,
  500. getLengthFromType: getLengthFromType,
  501. getNodeChildren: getNodeChildren,
  502. getTypeFromLength: getTypeFromLength,
  503. getValueFromType: getValueFromType,
  504. getValueType: getValueType,
  505. hash: hash$1,
  506. hashArray: hashArray,
  507. hashString: hashString
  508. });
  509. /**
  510. * Possible shader stages.
  511. *
  512. * @property {string} VERTEX The vertex shader stage.
  513. * @property {string} FRAGMENT The fragment shader stage.
  514. */
  515. const NodeShaderStage = {
  516. VERTEX: 'vertex',
  517. FRAGMENT: 'fragment'
  518. };
  519. /**
  520. * Update types of a node.
  521. *
  522. * @property {string} NONE The update method is not executed.
  523. * @property {string} FRAME The update method is executed per frame.
  524. * @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.
  525. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  526. */
  527. const NodeUpdateType = {
  528. NONE: 'none',
  529. FRAME: 'frame',
  530. RENDER: 'render',
  531. OBJECT: 'object'
  532. };
  533. /**
  534. * Data types of a node.
  535. *
  536. * @property {string} BOOLEAN Boolean type.
  537. * @property {string} INTEGER Integer type.
  538. * @property {string} FLOAT Float type.
  539. * @property {string} VECTOR2 Two-dimensional vector type.
  540. * @property {string} VECTOR3 Three-dimensional vector type.
  541. * @property {string} VECTOR4 Four-dimensional vector type.
  542. * @property {string} MATRIX2 2x2 matrix type.
  543. * @property {string} MATRIX3 3x3 matrix type.
  544. * @property {string} MATRIX4 4x4 matrix type.
  545. */
  546. const NodeType = {
  547. BOOLEAN: 'bool',
  548. INTEGER: 'int',
  549. FLOAT: 'float',
  550. VECTOR2: 'vec2',
  551. VECTOR3: 'vec3',
  552. VECTOR4: 'vec4',
  553. MATRIX2: 'mat2',
  554. MATRIX3: 'mat3',
  555. MATRIX4: 'mat4'
  556. };
  557. /**
  558. * Access types of a node. These are relevant for compute and storage usage.
  559. *
  560. * @property {string} READ_ONLY Read-only access
  561. * @property {string} WRITE_ONLY Write-only access.
  562. * @property {string} READ_WRITE Read and write access.
  563. */
  564. const NodeAccess = {
  565. READ_ONLY: 'readOnly',
  566. WRITE_ONLY: 'writeOnly',
  567. READ_WRITE: 'readWrite',
  568. };
  569. const defaultShaderStages = [ 'fragment', 'vertex' ];
  570. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  571. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  572. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  573. let _nodeId = 0;
  574. /**
  575. * Base class for all nodes.
  576. *
  577. * @augments EventDispatcher
  578. */
  579. class Node extends EventDispatcher {
  580. static get type() {
  581. return 'Node';
  582. }
  583. /**
  584. * Constructs a new node.
  585. *
  586. * @param {String?} nodeType - The node type.
  587. */
  588. constructor( nodeType = null ) {
  589. super();
  590. /**
  591. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  592. *
  593. * @type {String?}
  594. * @default null
  595. */
  596. this.nodeType = nodeType;
  597. /**
  598. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  599. *
  600. * @type {String}
  601. * @default 'none'
  602. */
  603. this.updateType = NodeUpdateType.NONE;
  604. /**
  605. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  606. *
  607. * @type {String}
  608. * @default 'none'
  609. */
  610. this.updateBeforeType = NodeUpdateType.NONE;
  611. /**
  612. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  613. *
  614. * @type {String}
  615. * @default 'none'
  616. */
  617. this.updateAfterType = NodeUpdateType.NONE;
  618. /**
  619. * The UUID of the node.
  620. *
  621. * @type {String}
  622. * @readonly
  623. */
  624. this.uuid = MathUtils.generateUUID();
  625. /**
  626. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  627. *
  628. * @type {Number}
  629. * @readonly
  630. * @default 0
  631. */
  632. this.version = 0;
  633. /**
  634. * Whether this node is global or not. This property is relevant for the internal
  635. * node caching system. All nodes which should be declared just once should
  636. * set this flag to `true` (a typical example is {@link AttributeNode}).
  637. *
  638. * @type {Boolean}
  639. * @default false
  640. */
  641. this.global = false;
  642. /**
  643. * This flag can be used for type testing.
  644. *
  645. * @type {Boolean}
  646. * @readonly
  647. * @default true
  648. */
  649. this.isNode = true;
  650. // private
  651. /**
  652. * The cache key of this node.
  653. *
  654. * @private
  655. * @type {Number?}
  656. * @default null
  657. */
  658. this._cacheKey = null;
  659. /**
  660. * The cache key 's version.
  661. *
  662. * @private
  663. * @type {Number}
  664. * @default 0
  665. */
  666. this._cacheKeyVersion = 0;
  667. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  668. }
  669. /**
  670. * Set this property to `true` when the node should be regenerated.
  671. *
  672. * @type {Boolean}
  673. * @default false
  674. * @param {boolean} value
  675. */
  676. set needsUpdate( value ) {
  677. if ( value === true ) {
  678. this.version ++;
  679. }
  680. }
  681. /**
  682. * The type of the class. The value is usually the constructor name.
  683. *
  684. * @type {String}
  685. * @readonly
  686. */
  687. get type() {
  688. return this.constructor.type;
  689. }
  690. /**
  691. * Convenient method for defining {@link Node#update}.
  692. *
  693. * @param {Function} callback - The update method.
  694. * @param {String} updateType - The update type.
  695. * @return {Node} A reference to this node.
  696. */
  697. onUpdate( callback, updateType ) {
  698. this.updateType = updateType;
  699. this.update = callback.bind( this.getSelf() );
  700. return this;
  701. }
  702. /**
  703. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  704. * this method automatically sets the update type to `FRAME`.
  705. *
  706. * @param {Function} callback - The update method.
  707. * @return {Node} A reference to this node.
  708. */
  709. onFrameUpdate( callback ) {
  710. return this.onUpdate( callback, NodeUpdateType.FRAME );
  711. }
  712. /**
  713. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  714. * this method automatically sets the update type to `RENDER`.
  715. *
  716. * @param {Function} callback - The update method.
  717. * @return {Node} A reference to this node.
  718. */
  719. onRenderUpdate( callback ) {
  720. return this.onUpdate( callback, NodeUpdateType.RENDER );
  721. }
  722. /**
  723. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  724. * this method automatically sets the update type to `OBJECT`.
  725. *
  726. * @param {Function} callback - The update method.
  727. * @return {Node} A reference to this node.
  728. */
  729. onObjectUpdate( callback ) {
  730. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  731. }
  732. /**
  733. * Convenient method for defining {@link Node#updateReference}.
  734. *
  735. * @param {Function} callback - The update method.
  736. * @return {Node} A reference to this node.
  737. */
  738. onReference( callback ) {
  739. this.updateReference = callback.bind( this.getSelf() );
  740. return this;
  741. }
  742. /**
  743. * The `this` reference might point to a Proxy so this method can be used
  744. * to get the reference to the actual node instance.
  745. *
  746. * @return {Node} A reference to the node.
  747. */
  748. getSelf() {
  749. // Returns non-node object.
  750. return this.self || this;
  751. }
  752. /**
  753. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  754. * to such objects based on a given state (e.g. the current node frame or builder).
  755. *
  756. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  757. * @return {Any} The updated reference.
  758. */
  759. updateReference( /*state*/ ) {
  760. return this;
  761. }
  762. /**
  763. * By default this method returns the value of the {@link Node#global} flag. This method
  764. * can be overwritten in derived classes if an analytical way is required to determine the
  765. * global status.
  766. *
  767. * @param {NodeBuilder} builder - The current node builder.
  768. * @return {Boolean} Whether this node is global or not.
  769. */
  770. isGlobal( /*builder*/ ) {
  771. return this.global;
  772. }
  773. /**
  774. * Generator function that can be used to iterate over the child nodes.
  775. *
  776. * @generator
  777. * @yields {Node} A child node.
  778. */
  779. * getChildren() {
  780. for ( const { childNode } of getNodeChildren( this ) ) {
  781. yield childNode;
  782. }
  783. }
  784. /**
  785. * Calling this method dispatches the `dispose` event. This event can be used
  786. * to register event listeners for clean up tasks.
  787. */
  788. dispose() {
  789. this.dispatchEvent( { type: 'dispose' } );
  790. }
  791. /**
  792. * Callback for {@link Node#traverse}.
  793. *
  794. * @callback traverseCallback
  795. * @param {Node} node - The current node.
  796. */
  797. /**
  798. * Can be used to traverse through the node's hierarchy.
  799. *
  800. * @param {traverseCallback} callback - A callback that is executed per node.
  801. */
  802. traverse( callback ) {
  803. callback( this );
  804. for ( const childNode of this.getChildren() ) {
  805. childNode.traverse( callback );
  806. }
  807. }
  808. /**
  809. * Returns the cache key for this node.
  810. *
  811. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  812. * @return {Number} The cache key of the node.
  813. */
  814. getCacheKey( force = false ) {
  815. force = force || this.version !== this._cacheKeyVersion;
  816. if ( force === true || this._cacheKey === null ) {
  817. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  818. this._cacheKeyVersion = this.version;
  819. }
  820. return this._cacheKey;
  821. }
  822. /**
  823. * Generate a custom cache key for this node.
  824. *
  825. * @return {Number} The cache key of the node.
  826. */
  827. customCacheKey() {
  828. return 0;
  829. }
  830. /**
  831. * Returns the references to this node which is by default `this`.
  832. *
  833. * @return {Node} A reference to this node.
  834. */
  835. getScope() {
  836. return this;
  837. }
  838. /**
  839. * Returns the hash of the node which is used to identify the node. By default it's
  840. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  841. * depending on their implementation.
  842. *
  843. * @param {NodeBuilder} builder - The current node builder.
  844. * @return {String} The hash.
  845. */
  846. getHash( /*builder*/ ) {
  847. return this.uuid;
  848. }
  849. /**
  850. * Returns the update type of {@link Node#update}.
  851. *
  852. * @return {NodeUpdateType} The update type.
  853. */
  854. getUpdateType() {
  855. return this.updateType;
  856. }
  857. /**
  858. * Returns the update type of {@link Node#updateBefore}.
  859. *
  860. * @return {NodeUpdateType} The update type.
  861. */
  862. getUpdateBeforeType() {
  863. return this.updateBeforeType;
  864. }
  865. /**
  866. * Returns the update type of {@link Node#updateAfter}.
  867. *
  868. * @return {NodeUpdateType} The update type.
  869. */
  870. getUpdateAfterType() {
  871. return this.updateAfterType;
  872. }
  873. /**
  874. * Certain types are composed of multiple elements. For example a `vec3`
  875. * is composed of three `float` values. This method returns the type of
  876. * these elements.
  877. *
  878. * @param {NodeBuilder} builder - The current node builder.
  879. * @return {String} The type of the node.
  880. */
  881. getElementType( builder ) {
  882. const type = this.getNodeType( builder );
  883. const elementType = builder.getElementType( type );
  884. return elementType;
  885. }
  886. /**
  887. * Returns the node's type.
  888. *
  889. * @param {NodeBuilder} builder - The current node builder.
  890. * @return {String} The type of the node.
  891. */
  892. getNodeType( builder ) {
  893. const nodeProperties = builder.getNodeProperties( this );
  894. if ( nodeProperties.outputNode ) {
  895. return nodeProperties.outputNode.getNodeType( builder );
  896. }
  897. return this.nodeType;
  898. }
  899. /**
  900. * This method is used during the build process of a node and ensures
  901. * equal nodes are not built multiple times but just once. For example if
  902. * `attribute( 'uv' )` is used multiple times by the user, the build
  903. * process makes sure to process just the first node.
  904. *
  905. * @param {NodeBuilder} builder - The current node builder.
  906. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  907. */
  908. getShared( builder ) {
  909. const hash = this.getHash( builder );
  910. const nodeFromHash = builder.getNodeFromHash( hash );
  911. return nodeFromHash || this;
  912. }
  913. /**
  914. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  915. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  916. * The output node must be returned in the `return` statement.
  917. *
  918. * @param {NodeBuilder} builder - The current node builder.
  919. * @return {Node?} The output node.
  920. */
  921. setup( builder ) {
  922. const nodeProperties = builder.getNodeProperties( this );
  923. let index = 0;
  924. for ( const childNode of this.getChildren() ) {
  925. nodeProperties[ 'node' + index ++ ] = childNode;
  926. }
  927. // return a outputNode if exists
  928. return null;
  929. }
  930. /**
  931. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  932. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  933. *
  934. * @param {NodeBuilder} builder - The current node builder.
  935. */
  936. analyze( builder ) {
  937. const usageCount = builder.increaseUsage( this );
  938. if ( usageCount === 1 ) {
  939. // node flow children
  940. const nodeProperties = builder.getNodeProperties( this );
  941. for ( const childNode of Object.values( nodeProperties ) ) {
  942. if ( childNode && childNode.isNode === true ) {
  943. childNode.build( builder );
  944. }
  945. }
  946. }
  947. }
  948. /**
  949. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  950. * This state builds the output node and returns the resulting shader string.
  951. *
  952. * @param {NodeBuilder} builder - The current node builder.
  953. * @param {String?} output - Can be used to define the output type.
  954. * @return {String?} The generated shader string.
  955. */
  956. generate( builder, output ) {
  957. const { outputNode } = builder.getNodeProperties( this );
  958. if ( outputNode && outputNode.isNode === true ) {
  959. return outputNode.build( builder, output );
  960. }
  961. }
  962. /**
  963. * The method can be implemented to update the node's internal state before it is used to render an object.
  964. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  965. *
  966. * @abstract
  967. * @param {NodeFrame} frame - A reference to the current node frame.
  968. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  969. */
  970. updateBefore( /*frame*/ ) {
  971. console.warn( 'Abstract function.' );
  972. }
  973. /**
  974. * The method can be implemented to update the node's internal state after it was used to render an object.
  975. * The {@link Node#updateAfterType} property defines how often the update is executed.
  976. *
  977. * @abstract
  978. * @param {NodeFrame} frame - A reference to the current node frame.
  979. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  980. */
  981. updateAfter( /*frame*/ ) {
  982. console.warn( 'Abstract function.' );
  983. }
  984. /**
  985. * The method can be implemented to update the node's internal state when it is used to render an object.
  986. * The {@link Node#updateType} property defines how often the update is executed.
  987. *
  988. * @abstract
  989. * @param {NodeFrame} frame - A reference to the current node frame.
  990. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  991. */
  992. update( /*frame*/ ) {
  993. console.warn( 'Abstract function.' );
  994. }
  995. /**
  996. * This method performs the build of a node. The behavior of this method as well as its return value depend
  997. * on the current build stage (setup, analyze or generate).
  998. *
  999. * @param {NodeBuilder} builder - The current node builder.
  1000. * @param {String?} output - Can be used to define the output type.
  1001. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1002. */
  1003. build( builder, output = null ) {
  1004. const refNode = this.getShared( builder );
  1005. if ( this !== refNode ) {
  1006. return refNode.build( builder, output );
  1007. }
  1008. builder.addNode( this );
  1009. builder.addChain( this );
  1010. /* Build stages expected results:
  1011. - "setup" -> Node
  1012. - "analyze" -> null
  1013. - "generate" -> String
  1014. */
  1015. let result = null;
  1016. const buildStage = builder.getBuildStage();
  1017. if ( buildStage === 'setup' ) {
  1018. this.updateReference( builder );
  1019. const properties = builder.getNodeProperties( this );
  1020. if ( properties.initialized !== true ) {
  1021. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1022. properties.initialized = true;
  1023. properties.outputNode = this.setup( builder );
  1024. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1025. for ( const childNode of Object.values( properties ) ) {
  1026. if ( childNode && childNode.isNode === true ) {
  1027. childNode.build( builder );
  1028. }
  1029. }
  1030. }
  1031. } else if ( buildStage === 'analyze' ) {
  1032. this.analyze( builder );
  1033. } else if ( buildStage === 'generate' ) {
  1034. const isGenerateOnce = this.generate.length === 1;
  1035. if ( isGenerateOnce ) {
  1036. const type = this.getNodeType( builder );
  1037. const nodeData = builder.getDataFromNode( this );
  1038. result = nodeData.snippet;
  1039. if ( result === undefined ) {
  1040. result = this.generate( builder ) || '';
  1041. nodeData.snippet = result;
  1042. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1043. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1044. }
  1045. result = builder.format( result, type, output );
  1046. } else {
  1047. result = this.generate( builder, output ) || '';
  1048. }
  1049. }
  1050. builder.removeChain( this );
  1051. builder.addSequentialNode( this );
  1052. return result;
  1053. }
  1054. /**
  1055. * Returns the child nodes as a JSON object.
  1056. *
  1057. * @return {Object} The serialized child objects as JSON.
  1058. */
  1059. getSerializeChildren() {
  1060. return getNodeChildren( this );
  1061. }
  1062. /**
  1063. * Serializes the node to JSON.
  1064. *
  1065. * @param {Object} json - The output JSON object.
  1066. */
  1067. serialize( json ) {
  1068. const nodeChildren = this.getSerializeChildren();
  1069. const inputNodes = {};
  1070. for ( const { property, index, childNode } of nodeChildren ) {
  1071. if ( index !== undefined ) {
  1072. if ( inputNodes[ property ] === undefined ) {
  1073. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1074. }
  1075. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1076. } else {
  1077. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1078. }
  1079. }
  1080. if ( Object.keys( inputNodes ).length > 0 ) {
  1081. json.inputNodes = inputNodes;
  1082. }
  1083. }
  1084. /**
  1085. * Deserializes the node from the given JSON.
  1086. *
  1087. * @param {Object} json - The JSON object.
  1088. */
  1089. deserialize( json ) {
  1090. if ( json.inputNodes !== undefined ) {
  1091. const nodes = json.meta.nodes;
  1092. for ( const property in json.inputNodes ) {
  1093. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1094. const inputArray = [];
  1095. for ( const uuid of json.inputNodes[ property ] ) {
  1096. inputArray.push( nodes[ uuid ] );
  1097. }
  1098. this[ property ] = inputArray;
  1099. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1100. const inputObject = {};
  1101. for ( const subProperty in json.inputNodes[ property ] ) {
  1102. const uuid = json.inputNodes[ property ][ subProperty ];
  1103. inputObject[ subProperty ] = nodes[ uuid ];
  1104. }
  1105. this[ property ] = inputObject;
  1106. } else {
  1107. const uuid = json.inputNodes[ property ];
  1108. this[ property ] = nodes[ uuid ];
  1109. }
  1110. }
  1111. }
  1112. }
  1113. /**
  1114. * Serializes the node into the three.js JSON Object/Scene format.
  1115. *
  1116. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1117. * @return {Object} The serialized node.
  1118. */
  1119. toJSON( meta ) {
  1120. const { uuid, type } = this;
  1121. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1122. if ( isRoot ) {
  1123. meta = {
  1124. textures: {},
  1125. images: {},
  1126. nodes: {}
  1127. };
  1128. }
  1129. // serialize
  1130. let data = meta.nodes[ uuid ];
  1131. if ( data === undefined ) {
  1132. data = {
  1133. uuid,
  1134. type,
  1135. meta,
  1136. metadata: {
  1137. version: 4.6,
  1138. type: 'Node',
  1139. generator: 'Node.toJSON'
  1140. }
  1141. };
  1142. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1143. this.serialize( data );
  1144. delete data.meta;
  1145. }
  1146. // TODO: Copied from Object3D.toJSON
  1147. function extractFromCache( cache ) {
  1148. const values = [];
  1149. for ( const key in cache ) {
  1150. const data = cache[ key ];
  1151. delete data.metadata;
  1152. values.push( data );
  1153. }
  1154. return values;
  1155. }
  1156. if ( isRoot ) {
  1157. const textures = extractFromCache( meta.textures );
  1158. const images = extractFromCache( meta.images );
  1159. const nodes = extractFromCache( meta.nodes );
  1160. if ( textures.length > 0 ) data.textures = textures;
  1161. if ( images.length > 0 ) data.images = images;
  1162. if ( nodes.length > 0 ) data.nodes = nodes;
  1163. }
  1164. return data;
  1165. }
  1166. }
  1167. /**
  1168. * Base class for representing element access on an array-like
  1169. * node data structures.
  1170. *
  1171. * @augments Node
  1172. */
  1173. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1174. static get type() {
  1175. return 'ArrayElementNode';
  1176. }
  1177. /**
  1178. * Constructs array element node.
  1179. *
  1180. * @param {Node} node - The array-like node.
  1181. * @param {Node} indexNode - The index node that defines the element access.
  1182. */
  1183. constructor( node, indexNode ) {
  1184. super();
  1185. /**
  1186. * The array-like node.
  1187. *
  1188. * @type {Node}
  1189. */
  1190. this.node = node;
  1191. /**
  1192. * The index node that defines the element access.
  1193. *
  1194. * @type {Node}
  1195. */
  1196. this.indexNode = indexNode;
  1197. /**
  1198. * This flag can be used for type testing.
  1199. *
  1200. * @type {Boolean}
  1201. * @readonly
  1202. * @default true
  1203. */
  1204. this.isArrayElementNode = true;
  1205. }
  1206. /**
  1207. * This method is overwritten since the node type is inferred from the array-like node.
  1208. *
  1209. * @param {NodeBuilder} builder - The current node builder.
  1210. * @return {String} The node type.
  1211. */
  1212. getNodeType( builder ) {
  1213. return this.node.getElementType( builder );
  1214. }
  1215. generate( builder ) {
  1216. const nodeSnippet = this.node.build( builder );
  1217. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1218. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1219. }
  1220. }
  1221. /**
  1222. * This module is part of the TSL core and usually not used in app level code.
  1223. * It represents a convert operation during the shader generation process
  1224. * meaning it converts the data type of a node to a target data type.
  1225. *
  1226. * @augments Node
  1227. */
  1228. class ConvertNode extends Node {
  1229. static get type() {
  1230. return 'ConvertNode';
  1231. }
  1232. /**
  1233. * Constructs a new convert node.
  1234. *
  1235. * @param {Node} node - The node which type should be converted.
  1236. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1237. */
  1238. constructor( node, convertTo ) {
  1239. super();
  1240. /**
  1241. * The node which type should be converted.
  1242. *
  1243. * @type {Node}
  1244. */
  1245. this.node = node;
  1246. /**
  1247. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1248. *
  1249. * @type {String}
  1250. */
  1251. this.convertTo = convertTo;
  1252. }
  1253. /**
  1254. * This method is overwritten since the implementation tries to infer the best
  1255. * matching type from the {@link ConvertNode#convertTo} property.
  1256. *
  1257. * @param {NodeBuilder} builder - The current node builder.
  1258. * @return {String} The node type.
  1259. */
  1260. getNodeType( builder ) {
  1261. const requestType = this.node.getNodeType( builder );
  1262. let convertTo = null;
  1263. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1264. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1265. convertTo = overloadingType;
  1266. }
  1267. }
  1268. return convertTo;
  1269. }
  1270. serialize( data ) {
  1271. super.serialize( data );
  1272. data.convertTo = this.convertTo;
  1273. }
  1274. deserialize( data ) {
  1275. super.deserialize( data );
  1276. this.convertTo = data.convertTo;
  1277. }
  1278. generate( builder, output ) {
  1279. const node = this.node;
  1280. const type = this.getNodeType( builder );
  1281. const snippet = node.build( builder, type );
  1282. return builder.format( snippet, type, output );
  1283. }
  1284. }
  1285. /**
  1286. * This module uses cache management to create temporary variables
  1287. * if the node is used more than once to prevent duplicate calculations.
  1288. *
  1289. * The class acts as a base class for many other nodes types.
  1290. *
  1291. * @augments Node
  1292. */
  1293. class TempNode extends Node {
  1294. static get type() {
  1295. return 'TempNode';
  1296. }
  1297. /**
  1298. * Constructs a temp node.
  1299. *
  1300. * @param {String?} nodeType - The node type.
  1301. */
  1302. constructor( nodeType = null ) {
  1303. super( nodeType );
  1304. /**
  1305. * This flag can be used for type testing.
  1306. *
  1307. * @type {Boolean}
  1308. * @readonly
  1309. * @default true
  1310. */
  1311. this.isTempNode = true;
  1312. }
  1313. /**
  1314. * Whether this node is used more than once in context of other nodes.
  1315. *
  1316. * @param {NodeBuilder} builder - The node builder.
  1317. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1318. */
  1319. hasDependencies( builder ) {
  1320. return builder.getDataFromNode( this ).usageCount > 1;
  1321. }
  1322. build( builder, output ) {
  1323. const buildStage = builder.getBuildStage();
  1324. if ( buildStage === 'generate' ) {
  1325. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1326. const nodeData = builder.getDataFromNode( this );
  1327. if ( nodeData.propertyName !== undefined ) {
  1328. return builder.format( nodeData.propertyName, type, output );
  1329. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1330. const snippet = super.build( builder, type );
  1331. const nodeVar = builder.getVarFromNode( this, null, type );
  1332. const propertyName = builder.getPropertyName( nodeVar );
  1333. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1334. nodeData.snippet = snippet;
  1335. nodeData.propertyName = propertyName;
  1336. return builder.format( nodeData.propertyName, type, output );
  1337. }
  1338. }
  1339. return super.build( builder, output );
  1340. }
  1341. }
  1342. /**
  1343. * This module is part of the TSL core and usually not used in app level code.
  1344. * It represents a join operation during the shader generation process.
  1345. * For example in can compose/join two single floats into a `vec2` type.
  1346. *
  1347. * @augments TempNode
  1348. */
  1349. class JoinNode extends TempNode {
  1350. static get type() {
  1351. return 'JoinNode';
  1352. }
  1353. /**
  1354. * Constructs a new join node.
  1355. *
  1356. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1357. * @param {String?} [nodeType=null] - The node type.
  1358. */
  1359. constructor( nodes = [], nodeType = null ) {
  1360. super( nodeType );
  1361. /**
  1362. * An array of nodes that should be joined.
  1363. *
  1364. * @type {Array<Node>}
  1365. */
  1366. this.nodes = nodes;
  1367. }
  1368. /**
  1369. * This method is overwritten since the node type must be inferred from the
  1370. * joined data length if not explicitly defined.
  1371. *
  1372. * @param {NodeBuilder} builder - The current node builder.
  1373. * @return {String} The node type.
  1374. */
  1375. getNodeType( builder ) {
  1376. if ( this.nodeType !== null ) {
  1377. return builder.getVectorType( this.nodeType );
  1378. }
  1379. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1380. }
  1381. generate( builder, output ) {
  1382. const type = this.getNodeType( builder );
  1383. const nodes = this.nodes;
  1384. const primitiveType = builder.getComponentType( type );
  1385. const snippetValues = [];
  1386. for ( const input of nodes ) {
  1387. let inputSnippet = input.build( builder );
  1388. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1389. if ( inputPrimitiveType !== primitiveType ) {
  1390. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1391. }
  1392. snippetValues.push( inputSnippet );
  1393. }
  1394. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1395. return builder.format( snippet, type, output );
  1396. }
  1397. }
  1398. const _stringVectorComponents = vectorComponents.join( '' );
  1399. /**
  1400. * This module is part of the TSL core and usually not used in app level code.
  1401. * `SplitNode` represents a property access operation which means it is
  1402. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1403. * For example:
  1404. * ```js
  1405. * const redValue = color.r;
  1406. * ```
  1407. *
  1408. * @augments Node
  1409. */
  1410. class SplitNode extends Node {
  1411. static get type() {
  1412. return 'SplitNode';
  1413. }
  1414. /**
  1415. * Constructs a new split node.
  1416. *
  1417. * @param {Node} node - The node that should be accessed.
  1418. * @param {String} [components='x'] - The components that should be accessed.
  1419. */
  1420. constructor( node, components = 'x' ) {
  1421. super();
  1422. /**
  1423. * The node that should be accessed.
  1424. *
  1425. * @type {Node}
  1426. */
  1427. this.node = node;
  1428. /**
  1429. * The components that should be accessed.
  1430. *
  1431. * @type {string}
  1432. */
  1433. this.components = components;
  1434. /**
  1435. * This flag can be used for type testing.
  1436. *
  1437. * @type {Boolean}
  1438. * @readonly
  1439. * @default true
  1440. */
  1441. this.isSplitNode = true;
  1442. }
  1443. /**
  1444. * Returns the vector length which is computed based on the requested components.
  1445. *
  1446. * @return {Number} The vector length.
  1447. */
  1448. getVectorLength() {
  1449. let vectorLength = this.components.length;
  1450. for ( const c of this.components ) {
  1451. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1452. }
  1453. return vectorLength;
  1454. }
  1455. /**
  1456. * Returns the component type of the node's type.
  1457. *
  1458. * @param {NodeBuilder} builder - The current node builder.
  1459. * @return {String} The component type.
  1460. */
  1461. getComponentType( builder ) {
  1462. return builder.getComponentType( this.node.getNodeType( builder ) );
  1463. }
  1464. /**
  1465. * This method is overwritten since the node type is inferred from requested components.
  1466. *
  1467. * @param {NodeBuilder} builder - The current node builder.
  1468. * @return {String} The node type.
  1469. */
  1470. getNodeType( builder ) {
  1471. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1472. }
  1473. generate( builder, output ) {
  1474. const node = this.node;
  1475. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1476. let snippet = null;
  1477. if ( nodeTypeLength > 1 ) {
  1478. let type = null;
  1479. const componentsLength = this.getVectorLength();
  1480. if ( componentsLength >= nodeTypeLength ) {
  1481. // needed expand the input node
  1482. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1483. }
  1484. const nodeSnippet = node.build( builder, type );
  1485. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1486. // unnecessary swizzle
  1487. snippet = builder.format( nodeSnippet, type, output );
  1488. } else {
  1489. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1490. }
  1491. } else {
  1492. // ignore .components if .node returns float/integer
  1493. snippet = node.build( builder, output );
  1494. }
  1495. return snippet;
  1496. }
  1497. serialize( data ) {
  1498. super.serialize( data );
  1499. data.components = this.components;
  1500. }
  1501. deserialize( data ) {
  1502. super.deserialize( data );
  1503. this.components = data.components;
  1504. }
  1505. }
  1506. /**
  1507. * This module is part of the TSL core and usually not used in app level code.
  1508. * `SetNode` represents a set operation which means it is used to implement any
  1509. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1510. * For example:
  1511. * ```js
  1512. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1513. * ```
  1514. *
  1515. * @augments TempNode
  1516. */
  1517. class SetNode extends TempNode {
  1518. static get type() {
  1519. return 'SetNode';
  1520. }
  1521. /**
  1522. * Constructs a new set node.
  1523. *
  1524. * @param {Node} sourceNode - The node that should be updated.
  1525. * @param {String} components - The components that should be updated.
  1526. * @param {Node} targetNode - The value node.
  1527. */
  1528. constructor( sourceNode, components, targetNode ) {
  1529. super();
  1530. /**
  1531. * The node that should be updated.
  1532. *
  1533. * @type {Node}
  1534. */
  1535. this.sourceNode = sourceNode;
  1536. /**
  1537. * The components that should be updated.
  1538. *
  1539. * @type {String}
  1540. */
  1541. this.components = components;
  1542. /**
  1543. * The value node.
  1544. *
  1545. * @type {Node}
  1546. */
  1547. this.targetNode = targetNode;
  1548. }
  1549. /**
  1550. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1551. *
  1552. * @param {NodeBuilder} builder - The current node builder.
  1553. * @return {String} The node type.
  1554. */
  1555. getNodeType( builder ) {
  1556. return this.sourceNode.getNodeType( builder );
  1557. }
  1558. generate( builder ) {
  1559. const { sourceNode, components, targetNode } = this;
  1560. const sourceType = this.getNodeType( builder );
  1561. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1562. const targetType = builder.getTypeFromLength( components.length, componentType );
  1563. const targetSnippet = targetNode.build( builder, targetType );
  1564. const sourceSnippet = sourceNode.build( builder, sourceType );
  1565. const length = builder.getTypeLength( sourceType );
  1566. const snippetValues = [];
  1567. for ( let i = 0; i < length; i ++ ) {
  1568. const component = vectorComponents[ i ];
  1569. if ( component === components[ 0 ] ) {
  1570. snippetValues.push( targetSnippet );
  1571. i += components.length - 1;
  1572. } else {
  1573. snippetValues.push( sourceSnippet + '.' + component );
  1574. }
  1575. }
  1576. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1577. }
  1578. }
  1579. /**
  1580. * This module is part of the TSL core and usually not used in app level code.
  1581. * It represents a flip operation during the shader generation process
  1582. * meaning it flips normalized values with the following formula:
  1583. * ```
  1584. * x = 1 - x;
  1585. * ```
  1586. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1587. * `flipSTPQ()` method invocations on node objects. For example:
  1588. * ```js
  1589. * uvNode = uvNode.flipY();
  1590. * ```
  1591. *
  1592. * @augments TempNode
  1593. */
  1594. class FlipNode extends TempNode {
  1595. static get type() {
  1596. return 'FlipNode';
  1597. }
  1598. /**
  1599. * Constructs a new flip node.
  1600. *
  1601. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1602. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1603. */
  1604. constructor( sourceNode, components ) {
  1605. super();
  1606. /**
  1607. * The node which component(s) should be flipped.
  1608. *
  1609. * @type {Node}
  1610. */
  1611. this.sourceNode = sourceNode;
  1612. /**
  1613. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1614. *
  1615. * @type {String}
  1616. */
  1617. this.components = components;
  1618. }
  1619. /**
  1620. * This method is overwritten since the node type is inferred from the source node.
  1621. *
  1622. * @param {NodeBuilder} builder - The current node builder.
  1623. * @return {String} The node type.
  1624. */
  1625. getNodeType( builder ) {
  1626. return this.sourceNode.getNodeType( builder );
  1627. }
  1628. generate( builder ) {
  1629. const { components, sourceNode } = this;
  1630. const sourceType = this.getNodeType( builder );
  1631. const sourceSnippet = sourceNode.build( builder );
  1632. const sourceCache = builder.getVarFromNode( this );
  1633. const sourceProperty = builder.getPropertyName( sourceCache );
  1634. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1635. const length = builder.getTypeLength( sourceType );
  1636. const snippetValues = [];
  1637. let componentIndex = 0;
  1638. for ( let i = 0; i < length; i ++ ) {
  1639. const component = vectorComponents[ i ];
  1640. if ( component === components[ componentIndex ] ) {
  1641. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1642. componentIndex ++;
  1643. } else {
  1644. snippetValues.push( sourceProperty + '.' + component );
  1645. }
  1646. }
  1647. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1648. }
  1649. }
  1650. /**
  1651. * Base class for representing data input nodes.
  1652. *
  1653. * @augments Node
  1654. */
  1655. class InputNode extends Node {
  1656. static get type() {
  1657. return 'InputNode';
  1658. }
  1659. /**
  1660. * Constructs a new input node.
  1661. *
  1662. * @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).
  1663. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1664. */
  1665. constructor( value, nodeType = null ) {
  1666. super( nodeType );
  1667. /**
  1668. * This flag can be used for type testing.
  1669. *
  1670. * @type {Boolean}
  1671. * @readonly
  1672. * @default true
  1673. */
  1674. this.isInputNode = true;
  1675. /**
  1676. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1677. *
  1678. * @type {Any}
  1679. */
  1680. this.value = value;
  1681. /**
  1682. * The precision of the value in the shader.
  1683. *
  1684. * @type {('low'|'medium'|'high')?}
  1685. * @default null
  1686. */
  1687. this.precision = null;
  1688. }
  1689. getNodeType( /*builder*/ ) {
  1690. if ( this.nodeType === null ) {
  1691. return getValueType( this.value );
  1692. }
  1693. return this.nodeType;
  1694. }
  1695. /**
  1696. * Returns the input type of the node which is by default the node type. Derived modules
  1697. * might overwrite this method and use a fixed type or compute one analytically.
  1698. *
  1699. * A typical example for different input and node types are textures. The input type of a
  1700. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1701. *
  1702. * @param {NodeBuilder} builder - The current node builder.
  1703. * @return {String} The input type.
  1704. */
  1705. getInputType( builder ) {
  1706. return this.getNodeType( builder );
  1707. }
  1708. /**
  1709. * Sets the precision to the given value. The method can be
  1710. * overwritten in derived classes if the final precision must be computed
  1711. * analytically.
  1712. *
  1713. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1714. * @return {InputNode} A reference to this node.
  1715. */
  1716. setPrecision( precision ) {
  1717. this.precision = precision;
  1718. return this;
  1719. }
  1720. serialize( data ) {
  1721. super.serialize( data );
  1722. data.value = this.value;
  1723. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1724. data.valueType = getValueType( this.value );
  1725. data.nodeType = this.nodeType;
  1726. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1727. data.precision = this.precision;
  1728. }
  1729. deserialize( data ) {
  1730. super.deserialize( data );
  1731. this.nodeType = data.nodeType;
  1732. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1733. this.precision = data.precision || null;
  1734. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1735. }
  1736. generate( /*builder, output*/ ) {
  1737. console.warn( 'Abstract function.' );
  1738. }
  1739. }
  1740. /**
  1741. * Class for representing a constant value in the shader.
  1742. *
  1743. * @augments InputNode
  1744. */
  1745. class ConstNode extends InputNode {
  1746. static get type() {
  1747. return 'ConstNode';
  1748. }
  1749. /**
  1750. * Constructs a new input node.
  1751. *
  1752. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1753. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1754. */
  1755. constructor( value, nodeType = null ) {
  1756. super( value, nodeType );
  1757. /**
  1758. * This flag can be used for type testing.
  1759. *
  1760. * @type {Boolean}
  1761. * @readonly
  1762. * @default true
  1763. */
  1764. this.isConstNode = true;
  1765. }
  1766. /**
  1767. * Generates the shader string of the value with the current node builder.
  1768. *
  1769. * @param {NodeBuilder} builder - The current node builder.
  1770. * @return {String} The generated value as a shader string.
  1771. */
  1772. generateConst( builder ) {
  1773. return builder.generateConst( this.getNodeType( builder ), this.value );
  1774. }
  1775. generate( builder, output ) {
  1776. const type = this.getNodeType( builder );
  1777. return builder.format( this.generateConst( builder ), type, output );
  1778. }
  1779. }
  1780. //
  1781. let currentStack = null;
  1782. const NodeElements = new Map();
  1783. function addMethodChaining( name, nodeElement ) {
  1784. if ( NodeElements.has( name ) ) {
  1785. console.warn( `Redefinition of method chaining ${ name }` );
  1786. return;
  1787. }
  1788. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1789. NodeElements.set( name, nodeElement );
  1790. }
  1791. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1792. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1793. const shaderNodeHandler = {
  1794. setup( NodeClosure, params ) {
  1795. const inputs = params.shift();
  1796. return NodeClosure( nodeObjects( inputs ), ...params );
  1797. },
  1798. get( node, prop, nodeObj ) {
  1799. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1800. if ( node.isStackNode !== true && prop === 'assign' ) {
  1801. return ( ...params ) => {
  1802. currentStack.assign( nodeObj, ...params );
  1803. return nodeObj;
  1804. };
  1805. } else if ( NodeElements.has( prop ) ) {
  1806. const nodeElement = NodeElements.get( prop );
  1807. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1808. } else if ( prop === 'self' ) {
  1809. return node;
  1810. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1811. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1812. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1813. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1814. // accessing properties ( swizzle )
  1815. prop = parseSwizzle( prop );
  1816. return nodeObject( new SplitNode( nodeObj, prop ) );
  1817. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1818. // set properties ( swizzle ) and sort to xyzw sequence
  1819. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1820. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1821. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1822. // set properties ( swizzle ) and sort to xyzw sequence
  1823. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1824. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1825. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1826. // accessing property
  1827. if ( prop === 'width' ) prop = 'x';
  1828. else if ( prop === 'height' ) prop = 'y';
  1829. else if ( prop === 'depth' ) prop = 'z';
  1830. return nodeObject( new SplitNode( node, prop ) );
  1831. } else if ( /^\d+$/.test( prop ) === true ) {
  1832. // accessing array
  1833. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1834. }
  1835. }
  1836. return Reflect.get( node, prop, nodeObj );
  1837. },
  1838. set( node, prop, value, nodeObj ) {
  1839. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1840. // setting properties
  1841. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1842. nodeObj[ prop ].assign( value );
  1843. return true;
  1844. }
  1845. }
  1846. return Reflect.set( node, prop, value, nodeObj );
  1847. }
  1848. };
  1849. const nodeObjectsCacheMap = new WeakMap();
  1850. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1851. const ShaderNodeObject = function ( obj, altType = null ) {
  1852. const type = getValueType( obj );
  1853. if ( type === 'node' ) {
  1854. let nodeObject = nodeObjectsCacheMap.get( obj );
  1855. if ( nodeObject === undefined ) {
  1856. nodeObject = new Proxy( obj, shaderNodeHandler );
  1857. nodeObjectsCacheMap.set( obj, nodeObject );
  1858. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1859. }
  1860. return nodeObject;
  1861. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1862. return nodeObject( getConstNode( obj, altType ) );
  1863. } else if ( type === 'shader' ) {
  1864. return Fn( obj );
  1865. }
  1866. return obj;
  1867. };
  1868. const ShaderNodeObjects = function ( objects, altType = null ) {
  1869. for ( const name in objects ) {
  1870. objects[ name ] = nodeObject( objects[ name ], altType );
  1871. }
  1872. return objects;
  1873. };
  1874. const ShaderNodeArray = function ( array, altType = null ) {
  1875. const len = array.length;
  1876. for ( let i = 0; i < len; i ++ ) {
  1877. array[ i ] = nodeObject( array[ i ], altType );
  1878. }
  1879. return array;
  1880. };
  1881. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1882. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1883. if ( scope === null ) {
  1884. return ( ...params ) => {
  1885. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1886. };
  1887. } else if ( factor !== null ) {
  1888. factor = nodeObject( factor );
  1889. return ( ...params ) => {
  1890. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1891. };
  1892. } else {
  1893. return ( ...params ) => {
  1894. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1895. };
  1896. }
  1897. };
  1898. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1899. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1900. };
  1901. class ShaderCallNodeInternal extends Node {
  1902. constructor( shaderNode, inputNodes ) {
  1903. super();
  1904. this.shaderNode = shaderNode;
  1905. this.inputNodes = inputNodes;
  1906. }
  1907. getNodeType( builder ) {
  1908. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1909. }
  1910. call( builder ) {
  1911. const { shaderNode, inputNodes } = this;
  1912. const properties = builder.getNodeProperties( shaderNode );
  1913. if ( properties.onceOutput ) return properties.onceOutput;
  1914. //
  1915. let result = null;
  1916. if ( shaderNode.layout ) {
  1917. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1918. if ( functionNodesCacheMap === undefined ) {
  1919. functionNodesCacheMap = new WeakMap();
  1920. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1921. }
  1922. let functionNode = functionNodesCacheMap.get( shaderNode );
  1923. if ( functionNode === undefined ) {
  1924. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1925. functionNodesCacheMap.set( shaderNode, functionNode );
  1926. }
  1927. if ( builder.currentFunctionNode !== null ) {
  1928. builder.currentFunctionNode.includes.push( functionNode );
  1929. }
  1930. result = nodeObject( functionNode.call( inputNodes ) );
  1931. } else {
  1932. const jsFunc = shaderNode.jsFunc;
  1933. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1934. result = nodeObject( outputNode );
  1935. }
  1936. if ( shaderNode.once ) {
  1937. properties.onceOutput = result;
  1938. }
  1939. return result;
  1940. }
  1941. getOutputNode( builder ) {
  1942. const properties = builder.getNodeProperties( this );
  1943. if ( properties.outputNode === null ) {
  1944. properties.outputNode = this.setupOutput( builder );
  1945. }
  1946. return properties.outputNode;
  1947. }
  1948. setup( builder ) {
  1949. return this.getOutputNode( builder );
  1950. }
  1951. setupOutput( builder ) {
  1952. builder.addStack();
  1953. builder.stack.outputNode = this.call( builder );
  1954. return builder.removeStack();
  1955. }
  1956. generate( builder, output ) {
  1957. const outputNode = this.getOutputNode( builder );
  1958. return outputNode.build( builder, output );
  1959. }
  1960. }
  1961. class ShaderNodeInternal extends Node {
  1962. constructor( jsFunc, nodeType ) {
  1963. super( nodeType );
  1964. this.jsFunc = jsFunc;
  1965. this.layout = null;
  1966. this.global = true;
  1967. this.once = false;
  1968. }
  1969. setLayout( layout ) {
  1970. this.layout = layout;
  1971. return this;
  1972. }
  1973. call( inputs = null ) {
  1974. nodeObjects( inputs );
  1975. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1976. }
  1977. setup() {
  1978. return this.call();
  1979. }
  1980. }
  1981. const bools = [ false, true ];
  1982. const uints = [ 0, 1, 2, 3 ];
  1983. const ints = [ - 1, - 2 ];
  1984. 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 ];
  1985. const boolsCacheMap = new Map();
  1986. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1987. const uintsCacheMap = new Map();
  1988. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1989. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1990. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1991. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1992. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1993. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1994. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1995. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1996. const getConstNode = ( value, type ) => {
  1997. if ( constNodesCacheMap.has( value ) ) {
  1998. return constNodesCacheMap.get( value );
  1999. } else if ( value.isNode === true ) {
  2000. return value;
  2001. } else {
  2002. return new ConstNode( value, type );
  2003. }
  2004. };
  2005. const safeGetNodeType = ( node ) => {
  2006. try {
  2007. return node.getNodeType();
  2008. } catch ( _ ) {
  2009. return undefined;
  2010. }
  2011. };
  2012. const ConvertType = function ( type, cacheMap = null ) {
  2013. return ( ...params ) => {
  2014. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2015. params = [ getValueFromType( type, ...params ) ];
  2016. }
  2017. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2018. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2019. }
  2020. if ( params.length === 1 ) {
  2021. const node = getConstNode( params[ 0 ], type );
  2022. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2023. return nodeObject( new ConvertNode( node, type ) );
  2024. }
  2025. const nodes = params.map( param => getConstNode( param ) );
  2026. return nodeObject( new JoinNode( nodes, type ) );
  2027. };
  2028. };
  2029. // exports
  2030. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2031. // utils
  2032. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2033. // shader node base
  2034. function ShaderNode( jsFunc, nodeType ) {
  2035. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2036. }
  2037. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2038. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2039. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2040. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2041. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2042. const Fn = ( jsFunc, nodeType ) => {
  2043. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2044. const fn = ( ...params ) => {
  2045. let inputs;
  2046. nodeObjects( params );
  2047. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2048. inputs = [ ...params ];
  2049. } else {
  2050. inputs = params[ 0 ];
  2051. }
  2052. return shaderNode.call( inputs );
  2053. };
  2054. fn.shaderNode = shaderNode;
  2055. fn.setLayout = ( layout ) => {
  2056. shaderNode.setLayout( layout );
  2057. return fn;
  2058. };
  2059. fn.once = () => {
  2060. shaderNode.once = true;
  2061. return fn;
  2062. };
  2063. return fn;
  2064. };
  2065. const tslFn = ( ...params ) => { // @deprecated, r168
  2066. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2067. return Fn( ...params );
  2068. };
  2069. //
  2070. addMethodChaining( 'toGlobal', ( node ) => {
  2071. node.global = true;
  2072. return node;
  2073. } );
  2074. //
  2075. const setCurrentStack = ( stack ) => {
  2076. currentStack = stack;
  2077. };
  2078. const getCurrentStack = () => currentStack;
  2079. const If = ( ...params ) => currentStack.If( ...params );
  2080. function append( node ) {
  2081. if ( currentStack ) currentStack.add( node );
  2082. return node;
  2083. }
  2084. addMethodChaining( 'append', append );
  2085. // types
  2086. const color = new ConvertType( 'color' );
  2087. const float = new ConvertType( 'float', cacheMaps.float );
  2088. const int = new ConvertType( 'int', cacheMaps.ints );
  2089. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2090. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2091. const vec2 = new ConvertType( 'vec2' );
  2092. const ivec2 = new ConvertType( 'ivec2' );
  2093. const uvec2 = new ConvertType( 'uvec2' );
  2094. const bvec2 = new ConvertType( 'bvec2' );
  2095. const vec3 = new ConvertType( 'vec3' );
  2096. const ivec3 = new ConvertType( 'ivec3' );
  2097. const uvec3 = new ConvertType( 'uvec3' );
  2098. const bvec3 = new ConvertType( 'bvec3' );
  2099. const vec4 = new ConvertType( 'vec4' );
  2100. const ivec4 = new ConvertType( 'ivec4' );
  2101. const uvec4 = new ConvertType( 'uvec4' );
  2102. const bvec4 = new ConvertType( 'bvec4' );
  2103. const mat2 = new ConvertType( 'mat2' );
  2104. const mat3 = new ConvertType( 'mat3' );
  2105. const mat4 = new ConvertType( 'mat4' );
  2106. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2107. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2108. addMethodChaining( 'toColor', color );
  2109. addMethodChaining( 'toFloat', float );
  2110. addMethodChaining( 'toInt', int );
  2111. addMethodChaining( 'toUint', uint );
  2112. addMethodChaining( 'toBool', bool );
  2113. addMethodChaining( 'toVec2', vec2 );
  2114. addMethodChaining( 'toIVec2', ivec2 );
  2115. addMethodChaining( 'toUVec2', uvec2 );
  2116. addMethodChaining( 'toBVec2', bvec2 );
  2117. addMethodChaining( 'toVec3', vec3 );
  2118. addMethodChaining( 'toIVec3', ivec3 );
  2119. addMethodChaining( 'toUVec3', uvec3 );
  2120. addMethodChaining( 'toBVec3', bvec3 );
  2121. addMethodChaining( 'toVec4', vec4 );
  2122. addMethodChaining( 'toIVec4', ivec4 );
  2123. addMethodChaining( 'toUVec4', uvec4 );
  2124. addMethodChaining( 'toBVec4', bvec4 );
  2125. addMethodChaining( 'toMat2', mat2 );
  2126. addMethodChaining( 'toMat3', mat3 );
  2127. addMethodChaining( 'toMat4', mat4 );
  2128. // basic nodes
  2129. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2130. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2131. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2132. addMethodChaining( 'element', element );
  2133. addMethodChaining( 'convert', convert );
  2134. /**
  2135. * This node can be used to group single instances of {@link UniformNode}
  2136. * and manage them as a uniform buffer.
  2137. *
  2138. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2139. * will be used when defining the {@link UniformNode#groupNode} property.
  2140. *
  2141. * - `objectGroup`: Uniform buffer per object.
  2142. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2143. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2144. *
  2145. * @augments Node
  2146. */
  2147. class UniformGroupNode extends Node {
  2148. static get type() {
  2149. return 'UniformGroupNode';
  2150. }
  2151. /**
  2152. * Constructs a new uniform group node.
  2153. *
  2154. * @param {String} name - The name of the uniform group node.
  2155. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2156. * @param {Number} [order=1] - Influences the internal sorting.
  2157. */
  2158. constructor( name, shared = false, order = 1 ) {
  2159. super( 'string' );
  2160. /**
  2161. * The name of the uniform group node.
  2162. *
  2163. * @type {String}
  2164. */
  2165. this.name = name;
  2166. /**
  2167. * Whether this uniform group node is shared or not.
  2168. *
  2169. * @type {Boolean}
  2170. * @default false
  2171. */
  2172. this.shared = shared;
  2173. /**
  2174. * Influences the internal sorting.
  2175. * TODO: Add details when this property should be changed.
  2176. *
  2177. * @type {Number}
  2178. * @default 1
  2179. */
  2180. this.order = order;
  2181. /**
  2182. * This flag can be used for type testing.
  2183. *
  2184. * @type {Boolean}
  2185. * @readonly
  2186. * @default true
  2187. */
  2188. this.isUniformGroup = true;
  2189. }
  2190. serialize( data ) {
  2191. super.serialize( data );
  2192. data.name = this.name;
  2193. data.version = this.version;
  2194. data.shared = this.shared;
  2195. }
  2196. deserialize( data ) {
  2197. super.deserialize( data );
  2198. this.name = data.name;
  2199. this.version = data.version;
  2200. this.shared = data.shared;
  2201. }
  2202. }
  2203. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2204. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2205. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2206. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2207. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2208. /**
  2209. * Class for representing a uniform.
  2210. *
  2211. * @augments InputNode
  2212. */
  2213. class UniformNode extends InputNode {
  2214. static get type() {
  2215. return 'UniformNode';
  2216. }
  2217. /**
  2218. * Constructs a new uniform node.
  2219. *
  2220. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2221. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2222. */
  2223. constructor( value, nodeType = null ) {
  2224. super( value, nodeType );
  2225. /**
  2226. * This flag can be used for type testing.
  2227. *
  2228. * @type {Boolean}
  2229. * @readonly
  2230. * @default true
  2231. */
  2232. this.isUniformNode = true;
  2233. /**
  2234. * The name or label of the uniform.
  2235. *
  2236. * @type {String}
  2237. * @default ''
  2238. */
  2239. this.name = '';
  2240. /**
  2241. * The uniform group of this uniform. By default, uniforms are
  2242. * managed per object but they might belong to a shared group
  2243. * which is updated per frame or render call.
  2244. *
  2245. * @type {UniformGroupNode}
  2246. */
  2247. this.groupNode = objectGroup;
  2248. }
  2249. /**
  2250. * Sets the {@link UniformNode#name} property.
  2251. *
  2252. * @param {String} name - The name of the uniform.
  2253. * @return {UniformNode} A reference to this node.
  2254. */
  2255. label( name ) {
  2256. this.name = name;
  2257. return this;
  2258. }
  2259. /**
  2260. * Sets the {@link UniformNode#groupNode} property.
  2261. *
  2262. * @param {UniformGroupNode} group - The uniform group.
  2263. * @return {UniformNode} A reference to this node.
  2264. */
  2265. setGroup( group ) {
  2266. this.groupNode = group;
  2267. return this;
  2268. }
  2269. /**
  2270. * Returns the {@link UniformNode#groupNode}.
  2271. *
  2272. * @return {UniformGroupNode} The uniform group.
  2273. */
  2274. getGroup() {
  2275. return this.groupNode;
  2276. }
  2277. /**
  2278. * By default, this method returns the result of {@link Node#getHash} but derived
  2279. * classes might overwrite this method with a different implementation.
  2280. *
  2281. * @param {NodeBuilder} builder - The current node builder.
  2282. * @return {String} The uniform hash.
  2283. */
  2284. getUniformHash( builder ) {
  2285. return this.getHash( builder );
  2286. }
  2287. onUpdate( callback, updateType ) {
  2288. const self = this.getSelf();
  2289. callback = callback.bind( self );
  2290. return super.onUpdate( ( frame ) => {
  2291. const value = callback( frame, self );
  2292. if ( value !== undefined ) {
  2293. this.value = value;
  2294. }
  2295. }, updateType );
  2296. }
  2297. generate( builder, output ) {
  2298. const type = this.getNodeType( builder );
  2299. const hash = this.getUniformHash( builder );
  2300. let sharedNode = builder.getNodeFromHash( hash );
  2301. if ( sharedNode === undefined ) {
  2302. builder.setHashNode( this, hash );
  2303. sharedNode = this;
  2304. }
  2305. const sharedNodeType = sharedNode.getInputType( builder );
  2306. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2307. const propertyName = builder.getPropertyName( nodeUniform );
  2308. if ( builder.context.label !== undefined ) delete builder.context.label;
  2309. return builder.format( propertyName, type, output );
  2310. }
  2311. }
  2312. const uniform = ( arg1, arg2 ) => {
  2313. const nodeType = getConstNodeType( arg2 || arg1 );
  2314. // @TODO: get ConstNode from .traverse() in the future
  2315. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2316. return nodeObject( new UniformNode( value, nodeType ) );
  2317. };
  2318. /**
  2319. * This class represents a shader property. It can be used on
  2320. * to explicitly define a property and assign a value to it.
  2321. *
  2322. * ```js
  2323. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2324. *```
  2325. * `PropertyNode` is used by the engine to predefined common material properties
  2326. * for TSL code.
  2327. *
  2328. * @augments Node
  2329. */
  2330. class PropertyNode extends Node {
  2331. static get type() {
  2332. return 'PropertyNode';
  2333. }
  2334. /**
  2335. * Constructs a new property node.
  2336. *
  2337. * @param {String} nodeType - The type of the node.
  2338. * @param {String?} [name=null] - The name of the property in the shader.
  2339. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2340. */
  2341. constructor( nodeType, name = null, varying = false ) {
  2342. super( nodeType );
  2343. /**
  2344. * The name of the property in the shader. If no name is defined,
  2345. * the node system auto-generates one.
  2346. *
  2347. * @type {String?}
  2348. * @default null
  2349. */
  2350. this.name = name;
  2351. /**
  2352. * Whether this property is a varying or not.
  2353. *
  2354. * @type {Boolean}
  2355. * @default false
  2356. */
  2357. this.varying = varying;
  2358. /**
  2359. * This flag can be used for type testing.
  2360. *
  2361. * @type {Boolean}
  2362. * @readonly
  2363. * @default true
  2364. */
  2365. this.isPropertyNode = true;
  2366. }
  2367. getHash( builder ) {
  2368. return this.name || super.getHash( builder );
  2369. }
  2370. /**
  2371. * The method is overwritten so it always returns `true`.
  2372. *
  2373. * @param {NodeBuilder} builder - The current node builder.
  2374. * @return {Boolean} Whether this node is global or not.
  2375. */
  2376. isGlobal( /*builder*/ ) {
  2377. return true;
  2378. }
  2379. generate( builder ) {
  2380. let nodeVar;
  2381. if ( this.varying === true ) {
  2382. nodeVar = builder.getVaryingFromNode( this, this.name );
  2383. nodeVar.needsInterpolation = true;
  2384. } else {
  2385. nodeVar = builder.getVarFromNode( this, this.name );
  2386. }
  2387. return builder.getPropertyName( nodeVar );
  2388. }
  2389. }
  2390. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2391. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2392. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2393. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2394. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2395. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2396. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2397. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2398. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2399. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2400. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2401. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2402. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2403. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2404. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2405. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2406. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2407. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2408. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2409. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2410. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2411. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2412. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2413. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2414. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2415. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2416. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2417. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2418. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2419. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2420. /**
  2421. * These node represents an assign operation. Meaning a node is assigned
  2422. * to another node.
  2423. *
  2424. * @augments TempNode
  2425. */
  2426. class AssignNode extends TempNode {
  2427. static get type() {
  2428. return 'AssignNode';
  2429. }
  2430. /**
  2431. * Constructs a new assign node.
  2432. *
  2433. * @param {Node} targetNode - The target node.
  2434. * @param {Node} sourceNode - The source type.
  2435. */
  2436. constructor( targetNode, sourceNode ) {
  2437. super();
  2438. /**
  2439. * The target node.
  2440. *
  2441. * @type {Node}
  2442. */
  2443. this.targetNode = targetNode;
  2444. /**
  2445. * The source node.
  2446. *
  2447. * @type {Node}
  2448. */
  2449. this.sourceNode = sourceNode;
  2450. }
  2451. /**
  2452. * Whether this node is used more than once in context of other nodes. This method
  2453. * is overwritten since it always returns `false` (assigns are unique).
  2454. *
  2455. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2456. */
  2457. hasDependencies() {
  2458. return false;
  2459. }
  2460. getNodeType( builder, output ) {
  2461. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2462. }
  2463. /**
  2464. * Whether a split is required when assigning source to target. This can happen when the component length of
  2465. * target and source data type does not match.
  2466. *
  2467. * @param {NodeBuilder} builder - The current node builder.
  2468. * @return {Boolean} Whether a split is required when assigning source to target.
  2469. */
  2470. needsSplitAssign( builder ) {
  2471. const { targetNode } = this;
  2472. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2473. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2474. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2475. return assignDifferentVector;
  2476. }
  2477. return false;
  2478. }
  2479. generate( builder, output ) {
  2480. const { targetNode, sourceNode } = this;
  2481. const needsSplitAssign = this.needsSplitAssign( builder );
  2482. const targetType = targetNode.getNodeType( builder );
  2483. const target = targetNode.context( { assign: true } ).build( builder );
  2484. const source = sourceNode.build( builder, targetType );
  2485. const sourceType = sourceNode.getNodeType( builder );
  2486. const nodeData = builder.getDataFromNode( this );
  2487. //
  2488. let snippet;
  2489. if ( nodeData.initialized === true ) {
  2490. if ( output !== 'void' ) {
  2491. snippet = target;
  2492. }
  2493. } else if ( needsSplitAssign ) {
  2494. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2495. const sourceProperty = builder.getPropertyName( sourceVar );
  2496. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2497. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2498. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2499. const component = targetNode.components[ i ];
  2500. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2501. }
  2502. if ( output !== 'void' ) {
  2503. snippet = target;
  2504. }
  2505. } else {
  2506. snippet = `${ target } = ${ source }`;
  2507. if ( output === 'void' || sourceType === 'void' ) {
  2508. builder.addLineFlowCode( snippet, this );
  2509. if ( output !== 'void' ) {
  2510. snippet = target;
  2511. }
  2512. }
  2513. }
  2514. nodeData.initialized = true;
  2515. return builder.format( snippet, targetType, output );
  2516. }
  2517. }
  2518. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2519. addMethodChaining( 'assign', assign );
  2520. /**
  2521. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2522. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2523. * this logic.
  2524. *
  2525. * @augments TempNode
  2526. */
  2527. class FunctionCallNode extends TempNode {
  2528. static get type() {
  2529. return 'FunctionCallNode';
  2530. }
  2531. /**
  2532. * Constructs a new function call node.
  2533. *
  2534. * @param {FunctionNode?} functionNode - The function node.
  2535. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2536. */
  2537. constructor( functionNode = null, parameters = {} ) {
  2538. super();
  2539. /**
  2540. * The function node.
  2541. *
  2542. * @type {FunctionNode}
  2543. * @default null
  2544. */
  2545. this.functionNode = functionNode;
  2546. /**
  2547. * The parameters of the function call.
  2548. *
  2549. * @type {Object<String, Node>}
  2550. * @default {}
  2551. */
  2552. this.parameters = parameters;
  2553. }
  2554. /**
  2555. * Sets the parameters of the function call node.
  2556. *
  2557. * @param {Object<String, Node>} parameters - The parameters to set.
  2558. * @return {FunctionCallNode} A reference to this node.
  2559. */
  2560. setParameters( parameters ) {
  2561. this.parameters = parameters;
  2562. return this;
  2563. }
  2564. /**
  2565. * Returns the parameters of the function call node.
  2566. *
  2567. * @return {Object<String, Node>} The parameters of this node.
  2568. */
  2569. getParameters() {
  2570. return this.parameters;
  2571. }
  2572. getNodeType( builder ) {
  2573. return this.functionNode.getNodeType( builder );
  2574. }
  2575. generate( builder ) {
  2576. const params = [];
  2577. const functionNode = this.functionNode;
  2578. const inputs = functionNode.getInputs( builder );
  2579. const parameters = this.parameters;
  2580. const generateInput = ( node, inputNode ) => {
  2581. const type = inputNode.type;
  2582. const pointer = type === 'pointer';
  2583. let output;
  2584. if ( pointer ) output = '&' + node.build( builder );
  2585. else output = node.build( builder, type );
  2586. return output;
  2587. };
  2588. if ( Array.isArray( parameters ) ) {
  2589. for ( let i = 0; i < parameters.length; i ++ ) {
  2590. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2591. }
  2592. } else {
  2593. for ( const inputNode of inputs ) {
  2594. const node = parameters[ inputNode.name ];
  2595. if ( node !== undefined ) {
  2596. params.push( generateInput( node, inputNode ) );
  2597. } else {
  2598. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2599. }
  2600. }
  2601. }
  2602. const functionName = functionNode.build( builder, 'property' );
  2603. return `${functionName}( ${params.join( ', ' )} )`;
  2604. }
  2605. }
  2606. const call = ( func, ...params ) => {
  2607. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2608. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2609. };
  2610. addMethodChaining( 'call', call );
  2611. /**
  2612. * This node represents basic mathematical and logical operations like addition,
  2613. * subtraction or comparisons (e.g. `equal()`).
  2614. *
  2615. * @augments TempNode
  2616. */
  2617. class OperatorNode extends TempNode {
  2618. static get type() {
  2619. return 'OperatorNode';
  2620. }
  2621. /**
  2622. * Constructs a new operator node.
  2623. *
  2624. * @param {String} op - The operator.
  2625. * @param {Node} aNode - The first input.
  2626. * @param {Node} bNode - The second input.
  2627. * @param {...Node} params - Additional input parameters.
  2628. */
  2629. constructor( op, aNode, bNode, ...params ) {
  2630. super();
  2631. if ( params.length > 0 ) {
  2632. let finalOp = new OperatorNode( op, aNode, bNode );
  2633. for ( let i = 0; i < params.length - 1; i ++ ) {
  2634. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2635. }
  2636. aNode = finalOp;
  2637. bNode = params[ params.length - 1 ];
  2638. }
  2639. /**
  2640. * The operator.
  2641. *
  2642. * @type {String}
  2643. */
  2644. this.op = op;
  2645. /**
  2646. * The first input.
  2647. *
  2648. * @type {Node}
  2649. */
  2650. this.aNode = aNode;
  2651. /**
  2652. * The second input.
  2653. *
  2654. * @type {Node}
  2655. */
  2656. this.bNode = bNode;
  2657. }
  2658. /**
  2659. * This method is overwritten since the node type is inferred from the operator
  2660. * and the input node types.
  2661. *
  2662. * @param {NodeBuilder} builder - The current node builder.
  2663. * @param {String} output - The current output string.
  2664. * @return {String} The node type.
  2665. */
  2666. getNodeType( builder, output ) {
  2667. const op = this.op;
  2668. const aNode = this.aNode;
  2669. const bNode = this.bNode;
  2670. const typeA = aNode.getNodeType( builder );
  2671. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2672. if ( typeA === 'void' || typeB === 'void' ) {
  2673. return 'void';
  2674. } else if ( op === '%' ) {
  2675. return typeA;
  2676. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2677. return builder.getIntegerType( typeA );
  2678. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2679. return 'bool';
  2680. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2681. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2682. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2683. } else {
  2684. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2685. return typeB;
  2686. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2687. // matrix x vector
  2688. return builder.getVectorFromMatrix( typeA );
  2689. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2690. // vector x matrix
  2691. return builder.getVectorFromMatrix( typeB );
  2692. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  2693. // anytype x anytype: use the greater length vector
  2694. return typeB;
  2695. }
  2696. return typeA;
  2697. }
  2698. }
  2699. generate( builder, output ) {
  2700. const op = this.op;
  2701. const aNode = this.aNode;
  2702. const bNode = this.bNode;
  2703. const type = this.getNodeType( builder, output );
  2704. let typeA = null;
  2705. let typeB = null;
  2706. if ( type !== 'void' ) {
  2707. typeA = aNode.getNodeType( builder );
  2708. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2709. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  2710. if ( builder.isVector( typeA ) ) {
  2711. typeB = typeA;
  2712. } else if ( typeA !== typeB ) {
  2713. typeA = typeB = 'float';
  2714. }
  2715. } else if ( op === '>>' || op === '<<' ) {
  2716. typeA = type;
  2717. typeB = builder.changeComponentType( typeB, 'uint' );
  2718. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2719. // matrix x vector
  2720. typeB = builder.getVectorFromMatrix( typeA );
  2721. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2722. // vector x matrix
  2723. typeA = builder.getVectorFromMatrix( typeB );
  2724. } else {
  2725. // anytype x anytype
  2726. typeA = typeB = type;
  2727. }
  2728. } else {
  2729. typeA = typeB = type;
  2730. }
  2731. const a = aNode.build( builder, typeA );
  2732. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  2733. const outputLength = builder.getTypeLength( output );
  2734. const fnOpSnippet = builder.getFunctionOperator( op );
  2735. if ( output !== 'void' ) {
  2736. if ( op === '<' && outputLength > 1 ) {
  2737. if ( builder.useComparisonMethod ) {
  2738. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  2739. } else {
  2740. return builder.format( `( ${ a } < ${ b } )`, type, output );
  2741. }
  2742. } else if ( op === '<=' && outputLength > 1 ) {
  2743. if ( builder.useComparisonMethod ) {
  2744. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2745. } else {
  2746. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  2747. }
  2748. } else if ( op === '>' && outputLength > 1 ) {
  2749. if ( builder.useComparisonMethod ) {
  2750. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  2751. } else {
  2752. return builder.format( `( ${ a } > ${ b } )`, type, output );
  2753. }
  2754. } else if ( op === '>=' && outputLength > 1 ) {
  2755. if ( builder.useComparisonMethod ) {
  2756. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2757. } else {
  2758. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  2759. }
  2760. } else if ( op === '!' || op === '~' ) {
  2761. return builder.format( `(${op}${a})`, typeA, output );
  2762. } else if ( fnOpSnippet ) {
  2763. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2764. } else {
  2765. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  2766. }
  2767. } else if ( typeA !== 'void' ) {
  2768. if ( fnOpSnippet ) {
  2769. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2770. } else {
  2771. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  2772. }
  2773. }
  2774. }
  2775. serialize( data ) {
  2776. super.serialize( data );
  2777. data.op = this.op;
  2778. }
  2779. deserialize( data ) {
  2780. super.deserialize( data );
  2781. this.op = data.op;
  2782. }
  2783. }
  2784. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  2785. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  2786. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  2787. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  2788. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  2789. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  2790. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  2791. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  2792. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  2793. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  2794. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  2795. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  2796. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  2797. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  2798. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  2799. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  2800. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  2801. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  2802. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  2803. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  2804. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  2805. addMethodChaining( 'add', add );
  2806. addMethodChaining( 'sub', sub );
  2807. addMethodChaining( 'mul', mul );
  2808. addMethodChaining( 'div', div );
  2809. addMethodChaining( 'modInt', modInt );
  2810. addMethodChaining( 'equal', equal );
  2811. addMethodChaining( 'notEqual', notEqual );
  2812. addMethodChaining( 'lessThan', lessThan );
  2813. addMethodChaining( 'greaterThan', greaterThan );
  2814. addMethodChaining( 'lessThanEqual', lessThanEqual );
  2815. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  2816. addMethodChaining( 'and', and );
  2817. addMethodChaining( 'or', or );
  2818. addMethodChaining( 'not', not );
  2819. addMethodChaining( 'xor', xor );
  2820. addMethodChaining( 'bitAnd', bitAnd );
  2821. addMethodChaining( 'bitNot', bitNot );
  2822. addMethodChaining( 'bitOr', bitOr );
  2823. addMethodChaining( 'bitXor', bitXor );
  2824. addMethodChaining( 'shiftLeft', shiftLeft );
  2825. addMethodChaining( 'shiftRight', shiftRight );
  2826. const remainder = ( ...params ) => { // @deprecated, r168
  2827. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  2828. return modInt( ...params );
  2829. };
  2830. addMethodChaining( 'remainder', remainder );
  2831. /**
  2832. * This node represents a variety of mathematical methods available in shaders.
  2833. * They are divided into three categories:
  2834. *
  2835. * - Methods with one input like `sin`, `cos` or `normalize`.
  2836. * - Methods with two inputs like `dot`, `cross` or `pow`.
  2837. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  2838. *
  2839. * @augments TempNode
  2840. */
  2841. class MathNode extends TempNode {
  2842. static get type() {
  2843. return 'MathNode';
  2844. }
  2845. /**
  2846. * Constructs a new math node.
  2847. *
  2848. * @param {String} method - The method name.
  2849. * @param {Node} aNode - The first input.
  2850. * @param {Node?} [bNode=null] - The second input.
  2851. * @param {Node?} [cNode=null] - The third input.
  2852. */
  2853. constructor( method, aNode, bNode = null, cNode = null ) {
  2854. super();
  2855. /**
  2856. * This flag can be used for type testing.
  2857. *
  2858. * @type {Boolean}
  2859. * @readonly
  2860. * @default true
  2861. */
  2862. this.method = method;
  2863. /**
  2864. * The first input.
  2865. *
  2866. * @type {Node}
  2867. */
  2868. this.aNode = aNode;
  2869. /**
  2870. * The second input.
  2871. *
  2872. * @type {Node?}
  2873. * @default null
  2874. */
  2875. this.bNode = bNode;
  2876. /**
  2877. * The third input.
  2878. *
  2879. * @type {Node?}
  2880. * @default null
  2881. */
  2882. this.cNode = cNode;
  2883. }
  2884. /**
  2885. * The input type is inferred from the node types of the input nodes.
  2886. *
  2887. * @param {NodeBuilder} builder - The current node builder.
  2888. * @return {String} The input type.
  2889. */
  2890. getInputType( builder ) {
  2891. const aType = this.aNode.getNodeType( builder );
  2892. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  2893. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  2894. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  2895. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  2896. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  2897. if ( aLen > bLen && aLen > cLen ) {
  2898. return aType;
  2899. } else if ( bLen > cLen ) {
  2900. return bType;
  2901. } else if ( cLen > aLen ) {
  2902. return cType;
  2903. }
  2904. return aType;
  2905. }
  2906. /**
  2907. * The selected method as well as the input type determine the node type of this node.
  2908. *
  2909. * @param {NodeBuilder} builder - The current node builder.
  2910. * @return {String} The node type.
  2911. */
  2912. getNodeType( builder ) {
  2913. const method = this.method;
  2914. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  2915. return 'float';
  2916. } else if ( method === MathNode.CROSS ) {
  2917. return 'vec3';
  2918. } else if ( method === MathNode.ALL ) {
  2919. return 'bool';
  2920. } else if ( method === MathNode.EQUALS ) {
  2921. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  2922. } else if ( method === MathNode.MOD ) {
  2923. return this.aNode.getNodeType( builder );
  2924. } else {
  2925. return this.getInputType( builder );
  2926. }
  2927. }
  2928. generate( builder, output ) {
  2929. const method = this.method;
  2930. const type = this.getNodeType( builder );
  2931. const inputType = this.getInputType( builder );
  2932. const a = this.aNode;
  2933. const b = this.bNode;
  2934. const c = this.cNode;
  2935. const isWebGL = builder.renderer.isWebGLRenderer === true;
  2936. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  2937. // dir can be either a direction vector or a normal vector
  2938. // upper-left 3x3 of matrix is assumed to be orthogonal
  2939. let tA = a;
  2940. let tB = b;
  2941. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  2942. tB = vec4( vec3( tB ), 0.0 );
  2943. } else {
  2944. tA = vec4( vec3( tA ), 0.0 );
  2945. }
  2946. const mulNode = mul( tA, tB ).xyz;
  2947. return normalize( mulNode ).build( builder, output );
  2948. } else if ( method === MathNode.NEGATE ) {
  2949. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  2950. } else if ( method === MathNode.ONE_MINUS ) {
  2951. return sub( 1.0, a ).build( builder, output );
  2952. } else if ( method === MathNode.RECIPROCAL ) {
  2953. return div( 1.0, a ).build( builder, output );
  2954. } else if ( method === MathNode.DIFFERENCE ) {
  2955. return abs( sub( a, b ) ).build( builder, output );
  2956. } else {
  2957. const params = [];
  2958. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  2959. params.push(
  2960. a.build( builder, type ),
  2961. b.build( builder, type )
  2962. );
  2963. } else if ( isWebGL && method === MathNode.STEP ) {
  2964. params.push(
  2965. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  2966. b.build( builder, inputType )
  2967. );
  2968. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  2969. params.push(
  2970. a.build( builder, inputType ),
  2971. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2972. );
  2973. } else if ( method === MathNode.REFRACT ) {
  2974. params.push(
  2975. a.build( builder, inputType ),
  2976. b.build( builder, inputType ),
  2977. c.build( builder, 'float' )
  2978. );
  2979. } else if ( method === MathNode.MIX ) {
  2980. params.push(
  2981. a.build( builder, inputType ),
  2982. b.build( builder, inputType ),
  2983. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2984. );
  2985. } else {
  2986. params.push( a.build( builder, inputType ) );
  2987. if ( b !== null ) params.push( b.build( builder, inputType ) );
  2988. if ( c !== null ) params.push( c.build( builder, inputType ) );
  2989. }
  2990. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  2991. }
  2992. }
  2993. serialize( data ) {
  2994. super.serialize( data );
  2995. data.method = this.method;
  2996. }
  2997. deserialize( data ) {
  2998. super.deserialize( data );
  2999. this.method = data.method;
  3000. }
  3001. }
  3002. // 1 input
  3003. MathNode.ALL = 'all';
  3004. MathNode.ANY = 'any';
  3005. MathNode.EQUALS = 'equals';
  3006. MathNode.RADIANS = 'radians';
  3007. MathNode.DEGREES = 'degrees';
  3008. MathNode.EXP = 'exp';
  3009. MathNode.EXP2 = 'exp2';
  3010. MathNode.LOG = 'log';
  3011. MathNode.LOG2 = 'log2';
  3012. MathNode.SQRT = 'sqrt';
  3013. MathNode.INVERSE_SQRT = 'inversesqrt';
  3014. MathNode.FLOOR = 'floor';
  3015. MathNode.CEIL = 'ceil';
  3016. MathNode.NORMALIZE = 'normalize';
  3017. MathNode.FRACT = 'fract';
  3018. MathNode.SIN = 'sin';
  3019. MathNode.COS = 'cos';
  3020. MathNode.TAN = 'tan';
  3021. MathNode.ASIN = 'asin';
  3022. MathNode.ACOS = 'acos';
  3023. MathNode.ATAN = 'atan';
  3024. MathNode.ABS = 'abs';
  3025. MathNode.SIGN = 'sign';
  3026. MathNode.LENGTH = 'length';
  3027. MathNode.NEGATE = 'negate';
  3028. MathNode.ONE_MINUS = 'oneMinus';
  3029. MathNode.DFDX = 'dFdx';
  3030. MathNode.DFDY = 'dFdy';
  3031. MathNode.ROUND = 'round';
  3032. MathNode.RECIPROCAL = 'reciprocal';
  3033. MathNode.TRUNC = 'trunc';
  3034. MathNode.FWIDTH = 'fwidth';
  3035. MathNode.BITCAST = 'bitcast';
  3036. MathNode.TRANSPOSE = 'transpose';
  3037. // 2 inputs
  3038. MathNode.ATAN2 = 'atan2';
  3039. MathNode.MIN = 'min';
  3040. MathNode.MAX = 'max';
  3041. MathNode.MOD = 'mod';
  3042. MathNode.STEP = 'step';
  3043. MathNode.REFLECT = 'reflect';
  3044. MathNode.DISTANCE = 'distance';
  3045. MathNode.DIFFERENCE = 'difference';
  3046. MathNode.DOT = 'dot';
  3047. MathNode.CROSS = 'cross';
  3048. MathNode.POW = 'pow';
  3049. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3050. // 3 inputs
  3051. MathNode.MIX = 'mix';
  3052. MathNode.CLAMP = 'clamp';
  3053. MathNode.REFRACT = 'refract';
  3054. MathNode.SMOOTHSTEP = 'smoothstep';
  3055. MathNode.FACEFORWARD = 'faceforward';
  3056. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3057. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3058. const PI = /*@__PURE__*/ float( Math.PI );
  3059. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3060. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3061. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3062. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3063. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3064. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3065. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3066. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3067. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3068. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3069. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3070. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3071. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3072. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3073. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3074. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3075. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3076. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3077. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3078. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3079. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3080. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3081. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3082. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3083. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3084. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3085. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3086. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3087. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3088. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3089. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3090. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3091. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3092. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3093. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3094. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  3095. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3096. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3097. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3098. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3099. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3100. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3101. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3102. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3103. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3104. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3105. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3106. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3107. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3108. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3109. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  3110. const lengthSq = ( a ) => dot( a, a );
  3111. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  3112. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  3113. const saturate = ( value ) => clamp( value );
  3114. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  3115. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  3116. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  3117. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  3118. const a = 12.9898, b = 78.233, c = 43758.5453;
  3119. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  3120. return fract( sin( sn ).mul( c ) );
  3121. } );
  3122. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  3123. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  3124. addMethodChaining( 'all', all );
  3125. addMethodChaining( 'any', any );
  3126. addMethodChaining( 'equals', equals );
  3127. addMethodChaining( 'radians', radians );
  3128. addMethodChaining( 'degrees', degrees );
  3129. addMethodChaining( 'exp', exp );
  3130. addMethodChaining( 'exp2', exp2 );
  3131. addMethodChaining( 'log', log );
  3132. addMethodChaining( 'log2', log2 );
  3133. addMethodChaining( 'sqrt', sqrt );
  3134. addMethodChaining( 'inverseSqrt', inverseSqrt );
  3135. addMethodChaining( 'floor', floor );
  3136. addMethodChaining( 'ceil', ceil );
  3137. addMethodChaining( 'normalize', normalize );
  3138. addMethodChaining( 'fract', fract );
  3139. addMethodChaining( 'sin', sin );
  3140. addMethodChaining( 'cos', cos );
  3141. addMethodChaining( 'tan', tan );
  3142. addMethodChaining( 'asin', asin );
  3143. addMethodChaining( 'acos', acos );
  3144. addMethodChaining( 'atan', atan );
  3145. addMethodChaining( 'abs', abs );
  3146. addMethodChaining( 'sign', sign );
  3147. addMethodChaining( 'length', length );
  3148. addMethodChaining( 'lengthSq', lengthSq );
  3149. addMethodChaining( 'negate', negate );
  3150. addMethodChaining( 'oneMinus', oneMinus );
  3151. addMethodChaining( 'dFdx', dFdx );
  3152. addMethodChaining( 'dFdy', dFdy );
  3153. addMethodChaining( 'round', round );
  3154. addMethodChaining( 'reciprocal', reciprocal );
  3155. addMethodChaining( 'trunc', trunc );
  3156. addMethodChaining( 'fwidth', fwidth );
  3157. addMethodChaining( 'atan2', atan2 );
  3158. addMethodChaining( 'min', min$1 );
  3159. addMethodChaining( 'max', max$1 );
  3160. addMethodChaining( 'mod', mod );
  3161. addMethodChaining( 'step', step );
  3162. addMethodChaining( 'reflect', reflect );
  3163. addMethodChaining( 'distance', distance );
  3164. addMethodChaining( 'dot', dot );
  3165. addMethodChaining( 'cross', cross );
  3166. addMethodChaining( 'pow', pow );
  3167. addMethodChaining( 'pow2', pow2 );
  3168. addMethodChaining( 'pow3', pow3 );
  3169. addMethodChaining( 'pow4', pow4 );
  3170. addMethodChaining( 'transformDirection', transformDirection );
  3171. addMethodChaining( 'mix', mixElement );
  3172. addMethodChaining( 'clamp', clamp );
  3173. addMethodChaining( 'refract', refract );
  3174. addMethodChaining( 'smoothstep', smoothstepElement );
  3175. addMethodChaining( 'faceForward', faceForward );
  3176. addMethodChaining( 'difference', difference );
  3177. addMethodChaining( 'saturate', saturate );
  3178. addMethodChaining( 'cbrt', cbrt );
  3179. addMethodChaining( 'transpose', transpose );
  3180. addMethodChaining( 'rand', rand );
  3181. /**
  3182. * Represents a logical `if/else` statement. Can be used as an alternative
  3183. * to the `If()`/`Else()` syntax.
  3184. *
  3185. * The corresponding TSL `select()` looks like so:
  3186. * ```js
  3187. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  3188. * ```
  3189. * The `select()` method is called in a chaining fashion on a codition. The parameter nodes of `select()`
  3190. * determine the outcome of the entire statement.
  3191. *
  3192. * @augments Node
  3193. */
  3194. class ConditionalNode extends Node {
  3195. static get type() {
  3196. return 'ConditionalNode';
  3197. }
  3198. /**
  3199. * Constructs a new conditional node.
  3200. *
  3201. * @param {Node} condNode - The node that defines the condition.
  3202. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  3203. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  3204. */
  3205. constructor( condNode, ifNode, elseNode = null ) {
  3206. super();
  3207. /**
  3208. * The node that defines the condition.
  3209. *
  3210. * @type {Node}
  3211. */
  3212. this.condNode = condNode;
  3213. /**
  3214. * The node that is evaluate when the condition ends up `true`.
  3215. *
  3216. * @type {Node}
  3217. */
  3218. this.ifNode = ifNode;
  3219. /**
  3220. * The node that is evaluate when the condition ends up `false`.
  3221. *
  3222. * @type {Node}
  3223. */
  3224. this.elseNode = elseNode;
  3225. }
  3226. /**
  3227. * This method is overwritten since the node type is inferred from the if/else
  3228. * nodes.
  3229. *
  3230. * @param {NodeBuilder} builder - The current node builder.
  3231. * @return {String} The node type.
  3232. */
  3233. getNodeType( builder ) {
  3234. const ifType = this.ifNode.getNodeType( builder );
  3235. if ( this.elseNode !== null ) {
  3236. const elseType = this.elseNode.getNodeType( builder );
  3237. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  3238. return elseType;
  3239. }
  3240. }
  3241. return ifType;
  3242. }
  3243. setup( builder ) {
  3244. const condNode = this.condNode.cache();
  3245. const ifNode = this.ifNode.cache();
  3246. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  3247. //
  3248. const currentNodeBlock = builder.context.nodeBlock;
  3249. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  3250. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  3251. //
  3252. const properties = builder.getNodeProperties( this );
  3253. properties.condNode = condNode;
  3254. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  3255. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  3256. }
  3257. generate( builder, output ) {
  3258. const type = this.getNodeType( builder );
  3259. const nodeData = builder.getDataFromNode( this );
  3260. if ( nodeData.nodeProperty !== undefined ) {
  3261. return nodeData.nodeProperty;
  3262. }
  3263. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  3264. const needsOutput = output !== 'void';
  3265. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  3266. nodeData.nodeProperty = nodeProperty;
  3267. const nodeSnippet = condNode.build( builder, 'bool' );
  3268. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  3269. let ifSnippet = ifNode.build( builder, type );
  3270. if ( ifSnippet ) {
  3271. if ( needsOutput ) {
  3272. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  3273. } else {
  3274. ifSnippet = 'return ' + ifSnippet + ';';
  3275. }
  3276. }
  3277. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  3278. if ( elseNode !== null ) {
  3279. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  3280. let elseSnippet = elseNode.build( builder, type );
  3281. if ( elseSnippet ) {
  3282. if ( needsOutput ) {
  3283. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  3284. } else {
  3285. elseSnippet = 'return ' + elseSnippet + ';';
  3286. }
  3287. }
  3288. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  3289. } else {
  3290. builder.addFlowCode( '\n\n' );
  3291. }
  3292. return builder.format( nodeProperty, type, output );
  3293. }
  3294. }
  3295. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  3296. addMethodChaining( 'select', select );
  3297. //
  3298. const cond = ( ...params ) => { // @deprecated, r168
  3299. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  3300. return select( ...params );
  3301. };
  3302. addMethodChaining( 'cond', cond );
  3303. /**
  3304. * This node can be used as a context management component for another node.
  3305. * {@link NodeBuilder} performs its node building process in a specific context and
  3306. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  3307. *
  3308. * ```js
  3309. *node.context( { getUV: () => customCoord } );
  3310. *```
  3311. * @augments Node
  3312. */
  3313. class ContextNode extends Node {
  3314. static get type() {
  3315. return 'ContextNode';
  3316. }
  3317. /**
  3318. * Constructs a new context node.
  3319. *
  3320. * @param {Node} node - The node whose context should be modified.
  3321. * @param {Object} [value={}] - The modified context data.
  3322. */
  3323. constructor( node, value = {} ) {
  3324. super();
  3325. /**
  3326. * This flag can be used for type testing.
  3327. *
  3328. * @type {Boolean}
  3329. * @readonly
  3330. * @default true
  3331. */
  3332. this.isContextNode = true;
  3333. /**
  3334. * The node whose context should be modified.
  3335. *
  3336. * @type {Node}
  3337. */
  3338. this.node = node;
  3339. /**
  3340. * The modified context data.
  3341. *
  3342. * @type {Object}
  3343. * @default {}
  3344. */
  3345. this.value = value;
  3346. }
  3347. /**
  3348. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  3349. *
  3350. * @return {Node} A reference to {@link ContextNode#node}.
  3351. */
  3352. getScope() {
  3353. return this.node.getScope();
  3354. }
  3355. /**
  3356. * This method is overwritten to ensure it returns the type to {@link ContextNode#node}.
  3357. *
  3358. * @param {NodeBuilder} builder - The current node builder.
  3359. * @return {String} The type of {@link ContextNode#node}.
  3360. */
  3361. getNodeType( builder ) {
  3362. return this.node.getNodeType( builder );
  3363. }
  3364. analyze( builder ) {
  3365. this.node.build( builder );
  3366. }
  3367. setup( builder ) {
  3368. const previousContext = builder.getContext();
  3369. builder.setContext( { ...builder.context, ...this.value } );
  3370. const node = this.node.build( builder );
  3371. builder.setContext( previousContext );
  3372. return node;
  3373. }
  3374. generate( builder, output ) {
  3375. const previousContext = builder.getContext();
  3376. builder.setContext( { ...builder.context, ...this.value } );
  3377. const snippet = this.node.build( builder, output );
  3378. builder.setContext( previousContext );
  3379. return snippet;
  3380. }
  3381. }
  3382. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  3383. const label = ( node, name ) => context( node, { label: name } );
  3384. addMethodChaining( 'context', context );
  3385. addMethodChaining( 'label', label );
  3386. /**
  3387. * Class for representing shader variables as nodes. Variables are created from
  3388. * existing nodes like the following:
  3389. *
  3390. * ```js
  3391. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  3392. * ```
  3393. *
  3394. * @augments Node
  3395. */
  3396. class VarNode extends Node {
  3397. static get type() {
  3398. return 'VarNode';
  3399. }
  3400. /**
  3401. * Constructs a new variable node.
  3402. *
  3403. * @param {Node} node - The node for which a variable should be created.
  3404. * @param {String?} name - The name of the variable in the shader.
  3405. */
  3406. constructor( node, name = null ) {
  3407. super();
  3408. /**
  3409. * The node for which a variable should be created.
  3410. *
  3411. * @type {Node}
  3412. */
  3413. this.node = node;
  3414. /**
  3415. * The name of the variable in the shader. If no name is defined,
  3416. * the node system auto-generates one.
  3417. *
  3418. * @type {String?}
  3419. * @default null
  3420. */
  3421. this.name = name;
  3422. /**
  3423. * `VarNode` sets this property to `true` by default.
  3424. *
  3425. * @type {Boolean}
  3426. * @default true
  3427. */
  3428. this.global = true;
  3429. /**
  3430. * This flag can be used for type testing.
  3431. *
  3432. * @type {Boolean}
  3433. * @readonly
  3434. * @default true
  3435. */
  3436. this.isVarNode = true;
  3437. }
  3438. getHash( builder ) {
  3439. return this.name || super.getHash( builder );
  3440. }
  3441. getNodeType( builder ) {
  3442. return this.node.getNodeType( builder );
  3443. }
  3444. generate( builder ) {
  3445. const { node, name } = this;
  3446. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  3447. const propertyName = builder.getPropertyName( nodeVar );
  3448. const snippet = node.build( builder, nodeVar.type );
  3449. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3450. return propertyName;
  3451. }
  3452. }
  3453. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  3454. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  3455. // Deprecated
  3456. const temp = ( node ) => { // @deprecated, r170
  3457. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  3458. return createVar( node );
  3459. };
  3460. addMethodChaining( 'temp', temp );
  3461. /**
  3462. * Class for representing shader varyings as nodes. Varyings are create from
  3463. * existing nodes like the following:
  3464. *
  3465. * ```js
  3466. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  3467. * ```
  3468. *
  3469. * @augments Node
  3470. */
  3471. class VaryingNode extends Node {
  3472. static get type() {
  3473. return 'VaryingNode';
  3474. }
  3475. /**
  3476. * Constructs a new varying node.
  3477. *
  3478. * @param {Node} node - The node for which a varying should be created.
  3479. * @param {String?} name - The name of the varying in the shader.
  3480. */
  3481. constructor( node, name = null ) {
  3482. super();
  3483. /**
  3484. * The node for which a varying should be created.
  3485. *
  3486. * @type {Node}
  3487. */
  3488. this.node = node;
  3489. /**
  3490. * The name of the varying in the shader. If no name is defined,
  3491. * the node system auto-generates one.
  3492. *
  3493. * @type {String?}
  3494. * @default null
  3495. */
  3496. this.name = name;
  3497. /**
  3498. * This flag can be used for type testing.
  3499. *
  3500. * @type {Boolean}
  3501. * @readonly
  3502. * @default true
  3503. */
  3504. this.isVaryingNode = true;
  3505. }
  3506. /**
  3507. * The method is overwritten so it always returns `true`.
  3508. *
  3509. * @param {NodeBuilder} builder - The current node builder.
  3510. * @return {Boolean} Whether this node is global or not.
  3511. */
  3512. isGlobal( /*builder*/ ) {
  3513. return true;
  3514. }
  3515. getHash( builder ) {
  3516. return this.name || super.getHash( builder );
  3517. }
  3518. getNodeType( builder ) {
  3519. // VaryingNode is auto type
  3520. return this.node.getNodeType( builder );
  3521. }
  3522. /**
  3523. * This method performs the setup of a varying node with the current node builder.
  3524. *
  3525. * @param {NodeBuilder} builder - The current node builder.
  3526. * @return {NodeVarying} The node varying from the node builder.
  3527. */
  3528. setupVarying( builder ) {
  3529. const properties = builder.getNodeProperties( this );
  3530. let varying = properties.varying;
  3531. if ( varying === undefined ) {
  3532. const name = this.name;
  3533. const type = this.getNodeType( builder );
  3534. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  3535. properties.node = this.node;
  3536. }
  3537. // this property can be used to check if the varying can be optimized for a variable
  3538. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  3539. return varying;
  3540. }
  3541. setup( builder ) {
  3542. this.setupVarying( builder );
  3543. }
  3544. analyze( builder ) {
  3545. this.setupVarying( builder );
  3546. return this.node.analyze( builder );
  3547. }
  3548. generate( builder ) {
  3549. const properties = builder.getNodeProperties( this );
  3550. const varying = this.setupVarying( builder );
  3551. if ( properties.propertyName === undefined ) {
  3552. const type = this.getNodeType( builder );
  3553. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  3554. // force node run in vertex stage
  3555. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  3556. properties.propertyName = propertyName;
  3557. }
  3558. return builder.getPropertyName( varying );
  3559. }
  3560. }
  3561. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  3562. addMethodChaining( 'varying', varying );
  3563. /** @module ColorSpaceFunctions **/
  3564. /**
  3565. * Converts the given color value from sRGB to linear-sRGB color space.
  3566. *
  3567. * @method
  3568. * @param {Node<vec3>} color - The sRGB color.
  3569. * @return {Node<vec3>} The linear-sRGB color.
  3570. */
  3571. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3572. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  3573. const b = color.mul( 0.0773993808 );
  3574. const factor = color.lessThanEqual( 0.04045 );
  3575. const rgbResult = mix( a, b, factor );
  3576. return rgbResult;
  3577. } ).setLayout( {
  3578. name: 'sRGBTransferEOTF',
  3579. type: 'vec3',
  3580. inputs: [
  3581. { name: 'color', type: 'vec3' }
  3582. ]
  3583. } );
  3584. /**
  3585. * Converts the given color value from linear-sRGB to sRGB color space.
  3586. *
  3587. * @method
  3588. * @param {Node<vec3>} color - The linear-sRGB color.
  3589. * @return {Node<vec3>} The sRGB color.
  3590. */
  3591. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3592. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  3593. const b = color.mul( 12.92 );
  3594. const factor = color.lessThanEqual( 0.0031308 );
  3595. const rgbResult = mix( a, b, factor );
  3596. return rgbResult;
  3597. } ).setLayout( {
  3598. name: 'sRGBTransferOETF',
  3599. type: 'vec3',
  3600. inputs: [
  3601. { name: 'color', type: 'vec3' }
  3602. ]
  3603. } );
  3604. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  3605. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  3606. /**
  3607. * This node represents a color space conversion. Meaning it converts
  3608. * a color value from a source to a target color space.
  3609. *
  3610. * @augments TempNode
  3611. */
  3612. class ColorSpaceNode extends TempNode {
  3613. static get type() {
  3614. return 'ColorSpaceNode';
  3615. }
  3616. /**
  3617. * Constructs a new color space node.
  3618. *
  3619. * @param {Node} colorNode - Represents the color to convert.
  3620. * @param {String} source - The source color space.
  3621. * @param {String} target - The target color space.
  3622. */
  3623. constructor( colorNode, source, target ) {
  3624. super( 'vec4' );
  3625. /**
  3626. * Represents the color to convert.
  3627. *
  3628. * @type {Node}
  3629. */
  3630. this.colorNode = colorNode;
  3631. /**
  3632. * The source color space.
  3633. *
  3634. * @type {Node}
  3635. */
  3636. this.source = source;
  3637. /**
  3638. * The target color space.
  3639. *
  3640. * @type {Node}
  3641. */
  3642. this.target = target;
  3643. }
  3644. /**
  3645. * This method resolves the constants `WORKING_COLOR_SPACE` and
  3646. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  3647. * color management and renderer.
  3648. *
  3649. * @param {NodeBuilder} builder - The current node builder.
  3650. * @param {String} colorSpace - The color space to resolve.
  3651. * @return {String} The resolved color space.
  3652. */
  3653. resolveColorSpace( builder, colorSpace ) {
  3654. if ( colorSpace === WORKING_COLOR_SPACE ) {
  3655. return ColorManagement.workingColorSpace;
  3656. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  3657. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  3658. }
  3659. return colorSpace;
  3660. }
  3661. setup( builder ) {
  3662. const { colorNode } = this;
  3663. const source = this.resolveColorSpace( builder, this.source );
  3664. const target = this.resolveColorSpace( builder, this.target );
  3665. let outputNode = colorNode;
  3666. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  3667. return outputNode;
  3668. }
  3669. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  3670. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  3671. }
  3672. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  3673. outputNode = vec4(
  3674. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  3675. outputNode.a
  3676. );
  3677. }
  3678. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  3679. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  3680. }
  3681. return outputNode;
  3682. }
  3683. }
  3684. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  3685. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  3686. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  3687. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  3688. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  3689. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  3690. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  3691. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  3692. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  3693. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  3694. static get type() {
  3695. return 'ReferenceElementNode';
  3696. }
  3697. constructor( referenceNode, indexNode ) {
  3698. super( referenceNode, indexNode );
  3699. this.referenceNode = referenceNode;
  3700. this.isReferenceElementNode = true;
  3701. }
  3702. getNodeType() {
  3703. return this.referenceNode.uniformType;
  3704. }
  3705. generate( builder ) {
  3706. const snippet = super.generate( builder );
  3707. const arrayType = this.referenceNode.getNodeType();
  3708. const elementType = this.getNodeType();
  3709. return builder.format( snippet, arrayType, elementType );
  3710. }
  3711. };
  3712. class ReferenceBaseNode extends Node {
  3713. static get type() {
  3714. return 'ReferenceBaseNode';
  3715. }
  3716. constructor( property, uniformType, object = null, count = null ) {
  3717. super();
  3718. this.property = property;
  3719. this.uniformType = uniformType;
  3720. this.object = object;
  3721. this.count = count;
  3722. this.properties = property.split( '.' );
  3723. this.reference = object;
  3724. this.node = null;
  3725. this.group = null;
  3726. this.updateType = NodeUpdateType.OBJECT;
  3727. }
  3728. setGroup( group ) {
  3729. this.group = group;
  3730. return this;
  3731. }
  3732. element( indexNode ) {
  3733. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  3734. }
  3735. setNodeType( uniformType ) {
  3736. const node = uniform( null, uniformType ).getSelf();
  3737. if ( this.group !== null ) {
  3738. node.setGroup( this.group );
  3739. }
  3740. this.node = node;
  3741. }
  3742. getNodeType( builder ) {
  3743. if ( this.node === null ) {
  3744. this.updateReference( builder );
  3745. this.updateValue();
  3746. }
  3747. return this.node.getNodeType( builder );
  3748. }
  3749. getValueFromReference( object = this.reference ) {
  3750. const { properties } = this;
  3751. let value = object[ properties[ 0 ] ];
  3752. for ( let i = 1; i < properties.length; i ++ ) {
  3753. value = value[ properties[ i ] ];
  3754. }
  3755. return value;
  3756. }
  3757. updateReference( state ) {
  3758. this.reference = this.object !== null ? this.object : state.object;
  3759. return this.reference;
  3760. }
  3761. setup() {
  3762. this.updateValue();
  3763. return this.node;
  3764. }
  3765. update( /*frame*/ ) {
  3766. this.updateValue();
  3767. }
  3768. updateValue() {
  3769. if ( this.node === null ) this.setNodeType( this.uniformType );
  3770. const value = this.getValueFromReference();
  3771. if ( Array.isArray( value ) ) {
  3772. this.node.array = value;
  3773. } else {
  3774. this.node.value = value;
  3775. }
  3776. }
  3777. }
  3778. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  3779. class RendererReferenceNode extends ReferenceBaseNode {
  3780. static get type() {
  3781. return 'RendererReferenceNode';
  3782. }
  3783. constructor( property, inputType, renderer = null ) {
  3784. super( property, inputType, renderer );
  3785. this.renderer = renderer;
  3786. this.setGroup( renderGroup );
  3787. }
  3788. updateReference( state ) {
  3789. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  3790. return this.reference;
  3791. }
  3792. }
  3793. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  3794. /**
  3795. * This node represents a tone mapping operation.
  3796. *
  3797. * @augments TempNode
  3798. */
  3799. class ToneMappingNode extends TempNode {
  3800. static get type() {
  3801. return 'ToneMappingNode';
  3802. }
  3803. /**
  3804. * Constructs a new tone mapping node.
  3805. *
  3806. * @param {Number} toneMapping - The tone mapping type.
  3807. * @param {Node} exposureNode - The tone mapping exposure.
  3808. * @param {Node} [colorNode=null] - The color node to process.
  3809. */
  3810. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  3811. super( 'vec3' );
  3812. /**
  3813. * The tone mapping type.
  3814. *
  3815. * @type {Number}
  3816. */
  3817. this.toneMapping = toneMapping;
  3818. /**
  3819. * The tone mapping exposure.
  3820. *
  3821. * @type {Node}
  3822. * @default null
  3823. */
  3824. this.exposureNode = exposureNode;
  3825. /**
  3826. * Represents the color to process.
  3827. *
  3828. * @type {Node}
  3829. * @default null
  3830. */
  3831. this.colorNode = colorNode;
  3832. }
  3833. /**
  3834. * Overwrites the default `customCacheKey()` implementation by including the tone
  3835. * mapping type into the cache key.
  3836. *
  3837. * @return {Number} The hash.
  3838. */
  3839. customCacheKey() {
  3840. return hash$1( this.toneMapping );
  3841. }
  3842. setup( builder ) {
  3843. const colorNode = this.colorNode || builder.context.color;
  3844. const toneMapping = this.toneMapping;
  3845. if ( toneMapping === NoToneMapping ) return colorNode;
  3846. let outputNode = null;
  3847. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  3848. if ( toneMappingFn !== null ) {
  3849. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  3850. } else {
  3851. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  3852. outputNode = colorNode;
  3853. }
  3854. return outputNode;
  3855. }
  3856. }
  3857. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  3858. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  3859. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  3860. class BufferAttributeNode extends InputNode {
  3861. static get type() {
  3862. return 'BufferAttributeNode';
  3863. }
  3864. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  3865. super( value, bufferType );
  3866. this.isBufferNode = true;
  3867. this.bufferType = bufferType;
  3868. this.bufferStride = bufferStride;
  3869. this.bufferOffset = bufferOffset;
  3870. this.usage = StaticDrawUsage;
  3871. this.instanced = false;
  3872. this.attribute = null;
  3873. this.global = true;
  3874. if ( value && value.isBufferAttribute === true ) {
  3875. this.attribute = value;
  3876. this.usage = value.usage;
  3877. this.instanced = value.isInstancedBufferAttribute;
  3878. }
  3879. }
  3880. getHash( builder ) {
  3881. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  3882. let bufferData = builder.globalCache.getData( this.value );
  3883. if ( bufferData === undefined ) {
  3884. bufferData = {
  3885. node: this
  3886. };
  3887. builder.globalCache.setData( this.value, bufferData );
  3888. }
  3889. return bufferData.node.uuid;
  3890. }
  3891. return this.uuid;
  3892. }
  3893. getNodeType( builder ) {
  3894. if ( this.bufferType === null ) {
  3895. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  3896. }
  3897. return this.bufferType;
  3898. }
  3899. setup( builder ) {
  3900. if ( this.attribute !== null ) return;
  3901. const type = this.getNodeType( builder );
  3902. const array = this.value;
  3903. const itemSize = builder.getTypeLength( type );
  3904. const stride = this.bufferStride || itemSize;
  3905. const offset = this.bufferOffset;
  3906. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  3907. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  3908. buffer.setUsage( this.usage );
  3909. this.attribute = bufferAttribute;
  3910. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  3911. }
  3912. generate( builder ) {
  3913. const nodeType = this.getNodeType( builder );
  3914. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  3915. const propertyName = builder.getPropertyName( nodeAttribute );
  3916. let output = null;
  3917. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  3918. this.name = propertyName;
  3919. output = propertyName;
  3920. } else {
  3921. const nodeVarying = varying( this );
  3922. output = nodeVarying.build( builder, nodeType );
  3923. }
  3924. return output;
  3925. }
  3926. getInputType( /*builder*/ ) {
  3927. return 'bufferAttribute';
  3928. }
  3929. setUsage( value ) {
  3930. this.usage = value;
  3931. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  3932. this.attribute.usage = value;
  3933. }
  3934. return this;
  3935. }
  3936. setInstanced( value ) {
  3937. this.instanced = value;
  3938. return this;
  3939. }
  3940. }
  3941. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  3942. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  3943. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  3944. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  3945. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  3946. class ComputeNode extends Node {
  3947. static get type() {
  3948. return 'ComputeNode';
  3949. }
  3950. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  3951. super( 'void' );
  3952. this.isComputeNode = true;
  3953. this.computeNode = computeNode;
  3954. this.count = count;
  3955. this.workgroupSize = workgroupSize;
  3956. this.dispatchCount = 0;
  3957. this.version = 1;
  3958. this.updateBeforeType = NodeUpdateType.OBJECT;
  3959. this.onInitFunction = null;
  3960. this.updateDispatchCount();
  3961. }
  3962. dispose() {
  3963. this.dispatchEvent( { type: 'dispose' } );
  3964. }
  3965. set needsUpdate( value ) {
  3966. if ( value === true ) this.version ++;
  3967. }
  3968. updateDispatchCount() {
  3969. const { count, workgroupSize } = this;
  3970. let size = workgroupSize[ 0 ];
  3971. for ( let i = 1; i < workgroupSize.length; i ++ )
  3972. size *= workgroupSize[ i ];
  3973. this.dispatchCount = Math.ceil( count / size );
  3974. }
  3975. onInit( callback ) {
  3976. this.onInitFunction = callback;
  3977. return this;
  3978. }
  3979. updateBefore( { renderer } ) {
  3980. renderer.compute( this );
  3981. }
  3982. generate( builder ) {
  3983. const { shaderStage } = builder;
  3984. if ( shaderStage === 'compute' ) {
  3985. const snippet = this.computeNode.build( builder, 'void' );
  3986. if ( snippet !== '' ) {
  3987. builder.addLineFlowCode( snippet, this );
  3988. }
  3989. }
  3990. }
  3991. }
  3992. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  3993. addMethodChaining( 'compute', compute );
  3994. /**
  3995. * This node can be used as a cache management component for another node.
  3996. * Caching is in general used by default in {@link NodeBuilder} but this node
  3997. * allows the usage of a shared parent cache during the build process.
  3998. *
  3999. * @augments Node
  4000. */
  4001. class CacheNode extends Node {
  4002. static get type() {
  4003. return 'CacheNode';
  4004. }
  4005. /**
  4006. * Constructs a new cache node.
  4007. *
  4008. * @param {Node} node - The node that should be cached.
  4009. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  4010. */
  4011. constructor( node, parent = true ) {
  4012. super();
  4013. /**
  4014. * The node that should be cached.
  4015. *
  4016. * @type {Node}
  4017. */
  4018. this.node = node;
  4019. /**
  4020. * Whether this node refers to a shared parent cache or not.
  4021. *
  4022. * @type {Boolean}
  4023. * @default true
  4024. */
  4025. this.parent = parent;
  4026. /**
  4027. * This flag can be used for type testing.
  4028. *
  4029. * @type {Boolean}
  4030. * @readonly
  4031. * @default true
  4032. */
  4033. this.isCacheNode = true;
  4034. }
  4035. getNodeType( builder ) {
  4036. return this.node.getNodeType( builder );
  4037. }
  4038. build( builder, ...params ) {
  4039. const previousCache = builder.getCache();
  4040. const cache = builder.getCacheFromNode( this, this.parent );
  4041. builder.setCache( cache );
  4042. const data = this.node.build( builder, ...params );
  4043. builder.setCache( previousCache );
  4044. return data;
  4045. }
  4046. }
  4047. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  4048. addMethodChaining( 'cache', cache );
  4049. /**
  4050. * The class generates the code of a given node but returns another node in the output.
  4051. * This can be used to call a method or node that does not return a value, i.e.
  4052. * type `void` on an input where returning a value is required. Example:
  4053. *
  4054. * ```js
  4055. * material.colorNode = myColor.bypass( runVoidFn() )
  4056. *```
  4057. *
  4058. * @augments Node
  4059. */
  4060. class BypassNode extends Node {
  4061. static get type() {
  4062. return 'BypassNode';
  4063. }
  4064. /**
  4065. * Constructs a new bypass node.
  4066. *
  4067. * @param {Node} outputNode - The output node.
  4068. * @param {Node} callNode - The call node.
  4069. */
  4070. constructor( outputNode, callNode ) {
  4071. super();
  4072. /**
  4073. * This flag can be used for type testing.
  4074. *
  4075. * @type {Boolean}
  4076. * @readonly
  4077. * @default true
  4078. */
  4079. this.isBypassNode = true;
  4080. /**
  4081. * The output node.
  4082. *
  4083. * @type {Node}
  4084. */
  4085. this.outputNode = outputNode;
  4086. /**
  4087. * The call node.
  4088. *
  4089. * @type {Node}
  4090. */
  4091. this.callNode = callNode;
  4092. }
  4093. getNodeType( builder ) {
  4094. return this.outputNode.getNodeType( builder );
  4095. }
  4096. generate( builder ) {
  4097. const snippet = this.callNode.build( builder, 'void' );
  4098. if ( snippet !== '' ) {
  4099. builder.addLineFlowCode( snippet, this );
  4100. }
  4101. return this.outputNode.build( builder );
  4102. }
  4103. }
  4104. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  4105. addMethodChaining( 'bypass', bypass );
  4106. /**
  4107. * This node allows to remap a node value from one range into another. E.g a value of
  4108. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  4109. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  4110. *
  4111. * @augments Node
  4112. */
  4113. class RemapNode extends Node {
  4114. static get type() {
  4115. return 'RemapNode';
  4116. }
  4117. /**
  4118. * Constructs a new remap node.
  4119. *
  4120. * @param {Node} node - The node that should be remapped.
  4121. * @param {Node} inLowNode - The source or current lower bound of the range.
  4122. * @param {Node} inHighNode - The source or current upper bound of the range.
  4123. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  4124. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  4125. */
  4126. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  4127. super();
  4128. /**
  4129. * The node that should be remapped.
  4130. *
  4131. * @type {Node}
  4132. */
  4133. this.node = node;
  4134. /**
  4135. * The source or current lower bound of the range.
  4136. *
  4137. * @type {Node}
  4138. */
  4139. this.inLowNode = inLowNode;
  4140. /**
  4141. * The source or current upper bound of the range.
  4142. *
  4143. * @type {Node}
  4144. */
  4145. this.inHighNode = inHighNode;
  4146. /**
  4147. * The target lower bound of the range.
  4148. *
  4149. * @type {Node}
  4150. * @default float(0)
  4151. */
  4152. this.outLowNode = outLowNode;
  4153. /**
  4154. * The target upper bound of the range.
  4155. *
  4156. * @type {Node}
  4157. * @default float(1)
  4158. */
  4159. this.outHighNode = outHighNode;
  4160. /**
  4161. * Whether the node value should be clamped before
  4162. * remapping it to the target range.
  4163. *
  4164. * @type {Boolean}
  4165. * @default true
  4166. */
  4167. this.doClamp = true;
  4168. }
  4169. setup() {
  4170. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  4171. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  4172. if ( doClamp === true ) t = t.clamp();
  4173. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  4174. }
  4175. }
  4176. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  4177. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  4178. addMethodChaining( 'remap', remap );
  4179. addMethodChaining( 'remapClamp', remapClamp );
  4180. /**
  4181. * This class can be used to implement basic expressions in shader code.
  4182. * Basic examples for that are `return`, `continue` or `discard` statements.
  4183. *
  4184. * @augments Node
  4185. */
  4186. class ExpressionNode extends Node {
  4187. static get type() {
  4188. return 'ExpressionNode';
  4189. }
  4190. /**
  4191. * Constructs a new expression node.
  4192. *
  4193. * @param {String} [snippet=''] - The native code snippet.
  4194. * @param {String} [nodeType='void'] - The node type.
  4195. */
  4196. constructor( snippet = '', nodeType = 'void' ) {
  4197. super( nodeType );
  4198. /**
  4199. * The native code snippet.
  4200. *
  4201. * @type {String}
  4202. * @default ''
  4203. */
  4204. this.snippet = snippet;
  4205. }
  4206. generate( builder, output ) {
  4207. const type = this.getNodeType( builder );
  4208. const snippet = this.snippet;
  4209. if ( type === 'void' ) {
  4210. builder.addLineFlowCode( snippet, this );
  4211. } else {
  4212. return builder.format( `( ${ snippet } )`, type, output );
  4213. }
  4214. }
  4215. }
  4216. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  4217. /** @module Discard **/
  4218. /**
  4219. * Represents a `discard` shader operation in TSL.
  4220. *
  4221. * @method
  4222. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  4223. * @return {Node} The `discard` expression.
  4224. */
  4225. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  4226. /**
  4227. * Represents a `return` shader operation in TSL.
  4228. *
  4229. * @method
  4230. * @return {ExpressionNode} The `return` expression.
  4231. */
  4232. const Return = () => expression( 'return' ).append();
  4233. addMethodChaining( 'discard', Discard );
  4234. /**
  4235. * Normally, tone mapping and color conversion happens automatically
  4236. * before outputting pixel too the default (screen) framebuffer. In certain
  4237. * post processing setups this happens to late because certain effects
  4238. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  4239. * to apply tone mapping and color space conversion at an arbitrary point
  4240. * in the effect chain.
  4241. *
  4242. * When applying tone mapping and color space conversion manually with this node,
  4243. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  4244. *
  4245. * ```js
  4246. * const postProcessing = new PostProcessing( renderer );
  4247. * postProcessing.outputColorTransform = false;
  4248. *
  4249. * const scenePass = pass( scene, camera );
  4250. * const outputPass = renderOutput( scenePass );
  4251. *
  4252. * postProcessing.outputNode = outputPass;
  4253. * ```
  4254. *
  4255. * @augments TempNode
  4256. */
  4257. class RenderOutputNode extends TempNode {
  4258. static get type() {
  4259. return 'RenderOutputNode';
  4260. }
  4261. /**
  4262. * Constructs a new render output node.
  4263. *
  4264. * @param {Node} colorNode - The color node to process.
  4265. * @param {String} toneMapping - The tone mapping type.
  4266. * @param {String} outputColorSpace - The output color space.
  4267. */
  4268. constructor( colorNode, toneMapping, outputColorSpace ) {
  4269. super( 'vec4' );
  4270. /**
  4271. * The color node to process.
  4272. *
  4273. * @type {Node}
  4274. */
  4275. this.colorNode = colorNode;
  4276. /**
  4277. * The tone mapping type.
  4278. *
  4279. * @type {Number?}
  4280. */
  4281. this.toneMapping = toneMapping;
  4282. /**
  4283. * The output color space.
  4284. *
  4285. * @type {String?}
  4286. */
  4287. this.outputColorSpace = outputColorSpace;
  4288. /**
  4289. * This flag can be used for type testing.
  4290. *
  4291. * @type {Boolean}
  4292. * @readonly
  4293. * @default true
  4294. */
  4295. this.isRenderOutputNode = true;
  4296. }
  4297. setup( { context } ) {
  4298. let outputNode = this.colorNode || context.color;
  4299. // tone mapping
  4300. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  4301. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  4302. if ( toneMapping !== NoToneMapping ) {
  4303. outputNode = outputNode.toneMapping( toneMapping );
  4304. }
  4305. // working to output color space
  4306. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  4307. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  4308. }
  4309. return outputNode;
  4310. }
  4311. }
  4312. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  4313. addMethodChaining( 'renderOutput', renderOutput );
  4314. // Non-PURE exports list, side-effects are required here.
  4315. // TSL Base Syntax
  4316. function addNodeElement( name/*, nodeElement*/ ) {
  4317. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  4318. }
  4319. /**
  4320. * Base class for representing shader attributes as nodes.
  4321. *
  4322. * @augments Node
  4323. */
  4324. class AttributeNode extends Node {
  4325. static get type() {
  4326. return 'AttributeNode';
  4327. }
  4328. /**
  4329. * Constructs a new attribute node.
  4330. *
  4331. * @param {String} attributeName - The name of the attribute.
  4332. * @param {String?} nodeType - The node type.
  4333. */
  4334. constructor( attributeName, nodeType = null ) {
  4335. super( nodeType );
  4336. /**
  4337. * `AttributeNode` sets this property to `true` by default.
  4338. *
  4339. * @type {Boolean}
  4340. * @default true
  4341. */
  4342. this.global = true;
  4343. this._attributeName = attributeName;
  4344. }
  4345. getHash( builder ) {
  4346. return this.getAttributeName( builder );
  4347. }
  4348. getNodeType( builder ) {
  4349. let nodeType = this.nodeType;
  4350. if ( nodeType === null ) {
  4351. const attributeName = this.getAttributeName( builder );
  4352. if ( builder.hasGeometryAttribute( attributeName ) ) {
  4353. const attribute = builder.geometry.getAttribute( attributeName );
  4354. nodeType = builder.getTypeFromAttribute( attribute );
  4355. } else {
  4356. nodeType = 'float';
  4357. }
  4358. }
  4359. return nodeType;
  4360. }
  4361. /**
  4362. * Sets the attribute name to the given value. The method can be
  4363. * overwritten in derived classes if the final name must be computed
  4364. * analytically.
  4365. *
  4366. * @param {String} attributeName - The name of the attribute.
  4367. * @return {AttributeNode} A reference to this node.
  4368. */
  4369. setAttributeName( attributeName ) {
  4370. this._attributeName = attributeName;
  4371. return this;
  4372. }
  4373. /**
  4374. * Returns the attribute name of this node. The method can be
  4375. * overwritten in derived classes if the final name must be computed
  4376. * analytically.
  4377. *
  4378. * @param {NodeBuilder} builder - The current node builder.
  4379. * @return {String} The attribute name.
  4380. */
  4381. getAttributeName( /*builder*/ ) {
  4382. return this._attributeName;
  4383. }
  4384. generate( builder ) {
  4385. const attributeName = this.getAttributeName( builder );
  4386. const nodeType = this.getNodeType( builder );
  4387. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  4388. if ( geometryAttribute === true ) {
  4389. const attribute = builder.geometry.getAttribute( attributeName );
  4390. const attributeType = builder.getTypeFromAttribute( attribute );
  4391. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  4392. if ( builder.shaderStage === 'vertex' ) {
  4393. return builder.format( nodeAttribute.name, attributeType, nodeType );
  4394. } else {
  4395. const nodeVarying = varying( this );
  4396. return nodeVarying.build( builder, nodeType );
  4397. }
  4398. } else {
  4399. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  4400. return builder.generateConst( nodeType );
  4401. }
  4402. }
  4403. serialize( data ) {
  4404. super.serialize( data );
  4405. data.global = this.global;
  4406. data._attributeName = this._attributeName;
  4407. }
  4408. deserialize( data ) {
  4409. super.deserialize( data );
  4410. this.global = data.global;
  4411. this._attributeName = data._attributeName;
  4412. }
  4413. }
  4414. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  4415. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  4416. class TextureSizeNode extends Node {
  4417. static get type() {
  4418. return 'TextureSizeNode';
  4419. }
  4420. constructor( textureNode, levelNode = null ) {
  4421. super( 'uvec2' );
  4422. this.isTextureSizeNode = true;
  4423. this.textureNode = textureNode;
  4424. this.levelNode = levelNode;
  4425. }
  4426. generate( builder, output ) {
  4427. const textureProperty = this.textureNode.build( builder, 'property' );
  4428. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  4429. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  4430. }
  4431. }
  4432. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  4433. /**
  4434. * A special type of uniform node that computes the
  4435. * maximum mipmap level for a given texture node.
  4436. *
  4437. * ```js
  4438. * const level = maxMipLevel( textureNode );
  4439. * ```
  4440. *
  4441. * @augments UniformNode
  4442. */
  4443. class MaxMipLevelNode extends UniformNode {
  4444. static get type() {
  4445. return 'MaxMipLevelNode';
  4446. }
  4447. /**
  4448. * Constructs a new max mip level node.
  4449. *
  4450. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  4451. */
  4452. constructor( textureNode ) {
  4453. super( 0 );
  4454. /**
  4455. * The texture node to compute the max mip level for.
  4456. *
  4457. * @private
  4458. * @type {TextureNode}
  4459. */
  4460. this._textureNode = textureNode;
  4461. /**
  4462. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  4463. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  4464. *
  4465. * @type {String}
  4466. * @default 'frame'
  4467. */
  4468. this.updateType = NodeUpdateType.FRAME;
  4469. }
  4470. /**
  4471. * The texture node to compute the max mip level for.
  4472. *
  4473. * @readonly
  4474. * @type {TextureNode}
  4475. */
  4476. get textureNode() {
  4477. return this._textureNode;
  4478. }
  4479. /**
  4480. * The texture.
  4481. *
  4482. * @readonly
  4483. * @type {Texture}
  4484. */
  4485. get texture() {
  4486. return this._textureNode.value;
  4487. }
  4488. update() {
  4489. const texture = this.texture;
  4490. const images = texture.images;
  4491. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  4492. if ( image && image.width !== undefined ) {
  4493. const { width, height } = image;
  4494. this.value = Math.log2( Math.max( width, height ) );
  4495. }
  4496. }
  4497. }
  4498. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  4499. class TextureNode extends UniformNode {
  4500. static get type() {
  4501. return 'TextureNode';
  4502. }
  4503. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4504. super( value );
  4505. this.isTextureNode = true;
  4506. this.uvNode = uvNode;
  4507. this.levelNode = levelNode;
  4508. this.biasNode = biasNode;
  4509. this.compareNode = null;
  4510. this.depthNode = null;
  4511. this.gradNode = null;
  4512. this.sampler = true;
  4513. this.updateMatrix = false;
  4514. this.updateType = NodeUpdateType.NONE;
  4515. this.referenceNode = null;
  4516. this._value = value;
  4517. this._matrixUniform = null;
  4518. this.setUpdateMatrix( uvNode === null );
  4519. }
  4520. set value( value ) {
  4521. if ( this.referenceNode ) {
  4522. this.referenceNode.value = value;
  4523. } else {
  4524. this._value = value;
  4525. }
  4526. }
  4527. get value() {
  4528. return this.referenceNode ? this.referenceNode.value : this._value;
  4529. }
  4530. getUniformHash( /*builder*/ ) {
  4531. return this.value.uuid;
  4532. }
  4533. getNodeType( /*builder*/ ) {
  4534. if ( this.value.isDepthTexture === true ) return 'float';
  4535. if ( this.value.type === UnsignedIntType ) {
  4536. return 'uvec4';
  4537. } else if ( this.value.type === IntType ) {
  4538. return 'ivec4';
  4539. }
  4540. return 'vec4';
  4541. }
  4542. getInputType( /*builder*/ ) {
  4543. return 'texture';
  4544. }
  4545. getDefaultUV() {
  4546. return uv( this.value.channel );
  4547. }
  4548. updateReference( /*state*/ ) {
  4549. return this.value;
  4550. }
  4551. getTransformedUV( uvNode ) {
  4552. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  4553. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  4554. }
  4555. setUpdateMatrix( value ) {
  4556. this.updateMatrix = value;
  4557. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  4558. return this;
  4559. }
  4560. setupUV( builder, uvNode ) {
  4561. const texture = this.value;
  4562. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  4563. if ( this.sampler ) {
  4564. uvNode = uvNode.flipY();
  4565. } else {
  4566. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  4567. }
  4568. }
  4569. return uvNode;
  4570. }
  4571. setup( builder ) {
  4572. const properties = builder.getNodeProperties( this );
  4573. properties.referenceNode = this.referenceNode;
  4574. //
  4575. let uvNode = this.uvNode;
  4576. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  4577. uvNode = builder.context.getUV( this );
  4578. }
  4579. if ( ! uvNode ) uvNode = this.getDefaultUV();
  4580. if ( this.updateMatrix === true ) {
  4581. uvNode = this.getTransformedUV( uvNode );
  4582. }
  4583. uvNode = this.setupUV( builder, uvNode );
  4584. //
  4585. let levelNode = this.levelNode;
  4586. if ( levelNode === null && builder.context.getTextureLevel ) {
  4587. levelNode = builder.context.getTextureLevel( this );
  4588. }
  4589. //
  4590. properties.uvNode = uvNode;
  4591. properties.levelNode = levelNode;
  4592. properties.biasNode = this.biasNode;
  4593. properties.compareNode = this.compareNode;
  4594. properties.gradNode = this.gradNode;
  4595. properties.depthNode = this.depthNode;
  4596. }
  4597. generateUV( builder, uvNode ) {
  4598. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  4599. }
  4600. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  4601. const texture = this.value;
  4602. let snippet;
  4603. if ( levelSnippet ) {
  4604. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  4605. } else if ( biasSnippet ) {
  4606. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  4607. } else if ( gradSnippet ) {
  4608. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  4609. } else if ( compareSnippet ) {
  4610. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  4611. } else if ( this.sampler === false ) {
  4612. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  4613. } else {
  4614. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  4615. }
  4616. return snippet;
  4617. }
  4618. generate( builder, output ) {
  4619. const properties = builder.getNodeProperties( this );
  4620. const texture = this.value;
  4621. if ( ! texture || texture.isTexture !== true ) {
  4622. throw new Error( 'TextureNode: Need a three.js texture.' );
  4623. }
  4624. const textureProperty = super.generate( builder, 'property' );
  4625. if ( output === 'sampler' ) {
  4626. return textureProperty + '_sampler';
  4627. } else if ( builder.isReference( output ) ) {
  4628. return textureProperty;
  4629. } else {
  4630. const nodeData = builder.getDataFromNode( this );
  4631. let propertyName = nodeData.propertyName;
  4632. if ( propertyName === undefined ) {
  4633. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  4634. const uvSnippet = this.generateUV( builder, uvNode );
  4635. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  4636. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  4637. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  4638. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  4639. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  4640. const nodeVar = builder.getVarFromNode( this );
  4641. propertyName = builder.getPropertyName( nodeVar );
  4642. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  4643. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4644. nodeData.snippet = snippet;
  4645. nodeData.propertyName = propertyName;
  4646. }
  4647. let snippet = propertyName;
  4648. const nodeType = this.getNodeType( builder );
  4649. if ( builder.needsToWorkingColorSpace( texture ) ) {
  4650. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  4651. }
  4652. return builder.format( snippet, nodeType, output );
  4653. }
  4654. }
  4655. setSampler( value ) {
  4656. this.sampler = value;
  4657. return this;
  4658. }
  4659. getSampler() {
  4660. return this.sampler;
  4661. }
  4662. // @TODO: Move to TSL
  4663. uv( uvNode ) { // @deprecated, r172
  4664. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  4665. return this.sample( uvNode );
  4666. }
  4667. sample( uvNode ) {
  4668. const textureNode = this.clone();
  4669. textureNode.uvNode = nodeObject( uvNode );
  4670. textureNode.referenceNode = this.getSelf();
  4671. return nodeObject( textureNode );
  4672. }
  4673. blur( amountNode ) {
  4674. const textureNode = this.clone();
  4675. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  4676. textureNode.referenceNode = this.getSelf();
  4677. return nodeObject( textureNode );
  4678. }
  4679. level( levelNode ) {
  4680. const textureNode = this.clone();
  4681. textureNode.levelNode = nodeObject( levelNode );
  4682. textureNode.referenceNode = this.getSelf();
  4683. return nodeObject( textureNode );
  4684. }
  4685. size( levelNode ) {
  4686. return textureSize( this, levelNode );
  4687. }
  4688. bias( biasNode ) {
  4689. const textureNode = this.clone();
  4690. textureNode.biasNode = nodeObject( biasNode );
  4691. textureNode.referenceNode = this.getSelf();
  4692. return nodeObject( textureNode );
  4693. }
  4694. compare( compareNode ) {
  4695. const textureNode = this.clone();
  4696. textureNode.compareNode = nodeObject( compareNode );
  4697. textureNode.referenceNode = this.getSelf();
  4698. return nodeObject( textureNode );
  4699. }
  4700. grad( gradNodeX, gradNodeY ) {
  4701. const textureNode = this.clone();
  4702. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  4703. textureNode.referenceNode = this.getSelf();
  4704. return nodeObject( textureNode );
  4705. }
  4706. depth( depthNode ) {
  4707. const textureNode = this.clone();
  4708. textureNode.depthNode = nodeObject( depthNode );
  4709. textureNode.referenceNode = this.getSelf();
  4710. return nodeObject( textureNode );
  4711. }
  4712. // --
  4713. serialize( data ) {
  4714. super.serialize( data );
  4715. data.value = this.value.toJSON( data.meta ).uuid;
  4716. data.sampler = this.sampler;
  4717. data.updateMatrix = this.updateMatrix;
  4718. data.updateType = this.updateType;
  4719. }
  4720. deserialize( data ) {
  4721. super.deserialize( data );
  4722. this.value = data.meta.textures[ data.value ];
  4723. this.sampler = data.sampler;
  4724. this.updateMatrix = data.updateMatrix;
  4725. this.updateType = data.updateType;
  4726. }
  4727. update() {
  4728. const texture = this.value;
  4729. const matrixUniform = this._matrixUniform;
  4730. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  4731. if ( texture.matrixAutoUpdate === true ) {
  4732. texture.updateMatrix();
  4733. }
  4734. }
  4735. clone() {
  4736. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  4737. newNode.sampler = this.sampler;
  4738. return newNode;
  4739. }
  4740. }
  4741. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  4742. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  4743. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  4744. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  4745. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  4746. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  4747. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  4748. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  4749. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  4750. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  4751. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  4752. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  4753. class Object3DNode extends Node {
  4754. static get type() {
  4755. return 'Object3DNode';
  4756. }
  4757. constructor( scope, object3d = null ) {
  4758. super();
  4759. this.scope = scope;
  4760. this.object3d = object3d;
  4761. this.updateType = NodeUpdateType.OBJECT;
  4762. this._uniformNode = new UniformNode( null );
  4763. }
  4764. getNodeType() {
  4765. const scope = this.scope;
  4766. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4767. return 'mat4';
  4768. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4769. return 'vec3';
  4770. }
  4771. }
  4772. update( frame ) {
  4773. const object = this.object3d;
  4774. const uniformNode = this._uniformNode;
  4775. const scope = this.scope;
  4776. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4777. uniformNode.value = object.matrixWorld;
  4778. } else if ( scope === Object3DNode.POSITION ) {
  4779. uniformNode.value = uniformNode.value || new Vector3();
  4780. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4781. } else if ( scope === Object3DNode.SCALE ) {
  4782. uniformNode.value = uniformNode.value || new Vector3();
  4783. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  4784. } else if ( scope === Object3DNode.DIRECTION ) {
  4785. uniformNode.value = uniformNode.value || new Vector3();
  4786. object.getWorldDirection( uniformNode.value );
  4787. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  4788. const camera = frame.camera;
  4789. uniformNode.value = uniformNode.value || new Vector3();
  4790. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4791. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  4792. }
  4793. }
  4794. generate( builder ) {
  4795. const scope = this.scope;
  4796. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4797. this._uniformNode.nodeType = 'mat4';
  4798. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4799. this._uniformNode.nodeType = 'vec3';
  4800. }
  4801. return this._uniformNode.build( builder );
  4802. }
  4803. serialize( data ) {
  4804. super.serialize( data );
  4805. data.scope = this.scope;
  4806. }
  4807. deserialize( data ) {
  4808. super.deserialize( data );
  4809. this.scope = data.scope;
  4810. }
  4811. }
  4812. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  4813. Object3DNode.POSITION = 'position';
  4814. Object3DNode.SCALE = 'scale';
  4815. Object3DNode.VIEW_POSITION = 'viewPosition';
  4816. Object3DNode.DIRECTION = 'direction';
  4817. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  4818. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  4819. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  4820. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  4821. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  4822. class ModelNode extends Object3DNode {
  4823. static get type() {
  4824. return 'ModelNode';
  4825. }
  4826. constructor( scope ) {
  4827. super( scope );
  4828. }
  4829. update( frame ) {
  4830. this.object3d = frame.object;
  4831. super.update( frame );
  4832. }
  4833. }
  4834. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  4835. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  4836. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  4837. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  4838. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  4839. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  4840. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  4841. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  4842. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4843. builder.context.isHighPrecisionModelViewMatrix = true;
  4844. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  4845. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4846. } );
  4847. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  4848. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4849. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  4850. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  4851. if ( isHighPrecisionModelViewMatrix !== true ) {
  4852. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4853. }
  4854. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  4855. } );
  4856. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  4857. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  4858. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  4859. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  4860. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  4861. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  4862. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  4863. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  4864. /**
  4865. * This node can be used to evaluate whether a primitive is front or back facing.
  4866. *
  4867. * @augments Node
  4868. */
  4869. class FrontFacingNode extends Node {
  4870. static get type() {
  4871. return 'FrontFacingNode';
  4872. }
  4873. /**
  4874. * Constructs a new front facing node.
  4875. */
  4876. constructor() {
  4877. super( 'bool' );
  4878. /**
  4879. * This flag can be used for type testing.
  4880. *
  4881. * @type {Boolean}
  4882. * @readonly
  4883. * @default true
  4884. */
  4885. this.isFrontFacingNode = true;
  4886. }
  4887. generate( builder ) {
  4888. const { renderer, material } = builder;
  4889. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  4890. if ( material.side === BackSide ) {
  4891. return 'false';
  4892. }
  4893. }
  4894. return builder.getFrontFacing();
  4895. }
  4896. }
  4897. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  4898. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  4899. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  4900. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  4901. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  4902. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  4903. return vec3( 0, 1, 0 );
  4904. }
  4905. return normalGeometry;
  4906. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  4907. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  4908. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4909. let node;
  4910. if ( builder.material.flatShading === true ) {
  4911. node = normalFlat;
  4912. } else {
  4913. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  4914. }
  4915. return node;
  4916. }, 'vec3' ).once() )().toVar( 'normalView' );
  4917. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  4918. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4919. return builder.context.setupNormal();
  4920. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  4921. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  4922. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4923. return builder.context.setupClearcoatNormal();
  4924. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  4925. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  4926. const m = mat3( matrix );
  4927. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  4928. return m.mul( transformedNormal ).xyz;
  4929. } );
  4930. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  4931. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  4932. if ( modelNormalViewMatrix !== null ) {
  4933. return modelNormalViewMatrix.transformDirection( normal );
  4934. }
  4935. //
  4936. const transformedNormal = modelNormalMatrix.mul( normal );
  4937. return cameraViewMatrix.transformDirection( transformedNormal );
  4938. } );
  4939. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  4940. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  4941. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  4942. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4943. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4944. class CubeTextureNode extends TextureNode {
  4945. static get type() {
  4946. return 'CubeTextureNode';
  4947. }
  4948. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4949. super( value, uvNode, levelNode, biasNode );
  4950. this.isCubeTextureNode = true;
  4951. }
  4952. getInputType( /*builder*/ ) {
  4953. return 'cubeTexture';
  4954. }
  4955. getDefaultUV() {
  4956. const texture = this.value;
  4957. if ( texture.mapping === CubeReflectionMapping ) {
  4958. return reflectVector;
  4959. } else if ( texture.mapping === CubeRefractionMapping ) {
  4960. return refractVector;
  4961. } else {
  4962. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  4963. return vec3( 0, 0, 0 );
  4964. }
  4965. }
  4966. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  4967. setupUV( builder, uvNode ) {
  4968. const texture = this.value;
  4969. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  4970. return vec3( uvNode.x.negate(), uvNode.yz );
  4971. } else {
  4972. return uvNode;
  4973. }
  4974. }
  4975. generateUV( builder, cubeUV ) {
  4976. return cubeUV.build( builder, 'vec3' );
  4977. }
  4978. }
  4979. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  4980. class BufferNode extends UniformNode {
  4981. static get type() {
  4982. return 'BufferNode';
  4983. }
  4984. constructor( value, bufferType, bufferCount = 0 ) {
  4985. super( value, bufferType );
  4986. this.isBufferNode = true;
  4987. this.bufferType = bufferType;
  4988. this.bufferCount = bufferCount;
  4989. }
  4990. getElementType( builder ) {
  4991. return this.getNodeType( builder );
  4992. }
  4993. getInputType( /*builder*/ ) {
  4994. return 'buffer';
  4995. }
  4996. }
  4997. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  4998. class UniformArrayElementNode extends ArrayElementNode {
  4999. static get type() {
  5000. return 'UniformArrayElementNode';
  5001. }
  5002. constructor( arrayBuffer, indexNode ) {
  5003. super( arrayBuffer, indexNode );
  5004. this.isArrayBufferElementNode = true;
  5005. }
  5006. generate( builder ) {
  5007. const snippet = super.generate( builder );
  5008. const type = this.getNodeType();
  5009. const paddedType = this.node.getPaddedType();
  5010. return builder.format( snippet, paddedType, type );
  5011. }
  5012. }
  5013. class UniformArrayNode extends BufferNode {
  5014. static get type() {
  5015. return 'UniformArrayNode';
  5016. }
  5017. constructor( value, elementType = null ) {
  5018. super( null );
  5019. this.array = value;
  5020. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  5021. this.paddedType = this.getPaddedType();
  5022. this.updateType = NodeUpdateType.RENDER;
  5023. this.isArrayBufferNode = true;
  5024. }
  5025. getNodeType() {
  5026. return this.paddedType;
  5027. }
  5028. getElementType() {
  5029. return this.elementType;
  5030. }
  5031. getPaddedType() {
  5032. const elementType = this.elementType;
  5033. let paddedType = 'vec4';
  5034. if ( elementType === 'mat2' ) {
  5035. paddedType = 'mat2';
  5036. } else if ( /mat/.test( elementType ) === true ) {
  5037. paddedType = 'mat4';
  5038. } else if ( elementType.charAt( 0 ) === 'i' ) {
  5039. paddedType = 'ivec4';
  5040. } else if ( elementType.charAt( 0 ) === 'u' ) {
  5041. paddedType = 'uvec4';
  5042. }
  5043. return paddedType;
  5044. }
  5045. update( /*frame*/ ) {
  5046. const { array, value } = this;
  5047. const elementType = this.elementType;
  5048. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  5049. for ( let i = 0; i < array.length; i ++ ) {
  5050. const index = i * 4;
  5051. value[ index ] = array[ i ];
  5052. }
  5053. } else if ( elementType === 'color' ) {
  5054. for ( let i = 0; i < array.length; i ++ ) {
  5055. const index = i * 4;
  5056. const vector = array[ i ];
  5057. value[ index ] = vector.r;
  5058. value[ index + 1 ] = vector.g;
  5059. value[ index + 2 ] = vector.b || 0;
  5060. //value[ index + 3 ] = vector.a || 0;
  5061. }
  5062. } else if ( elementType === 'mat2' ) {
  5063. for ( let i = 0; i < array.length; i ++ ) {
  5064. const index = i * 4;
  5065. const matrix = array[ i ];
  5066. value[ index ] = matrix.elements[ 0 ];
  5067. value[ index + 1 ] = matrix.elements[ 1 ];
  5068. value[ index + 2 ] = matrix.elements[ 2 ];
  5069. value[ index + 3 ] = matrix.elements[ 3 ];
  5070. }
  5071. } else if ( elementType === 'mat3' ) {
  5072. for ( let i = 0; i < array.length; i ++ ) {
  5073. const index = i * 16;
  5074. const matrix = array[ i ];
  5075. value[ index ] = matrix.elements[ 0 ];
  5076. value[ index + 1 ] = matrix.elements[ 1 ];
  5077. value[ index + 2 ] = matrix.elements[ 2 ];
  5078. value[ index + 4 ] = matrix.elements[ 3 ];
  5079. value[ index + 5 ] = matrix.elements[ 4 ];
  5080. value[ index + 6 ] = matrix.elements[ 5 ];
  5081. value[ index + 8 ] = matrix.elements[ 6 ];
  5082. value[ index + 9 ] = matrix.elements[ 7 ];
  5083. value[ index + 10 ] = matrix.elements[ 8 ];
  5084. value[ index + 15 ] = 1;
  5085. }
  5086. } else if ( elementType === 'mat4' ) {
  5087. for ( let i = 0; i < array.length; i ++ ) {
  5088. const index = i * 16;
  5089. const matrix = array[ i ];
  5090. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  5091. value[ index + i ] = matrix.elements[ i ];
  5092. }
  5093. }
  5094. } else {
  5095. for ( let i = 0; i < array.length; i ++ ) {
  5096. const index = i * 4;
  5097. const vector = array[ i ];
  5098. value[ index ] = vector.x;
  5099. value[ index + 1 ] = vector.y;
  5100. value[ index + 2 ] = vector.z || 0;
  5101. value[ index + 3 ] = vector.w || 0;
  5102. }
  5103. }
  5104. }
  5105. setup( builder ) {
  5106. const length = this.array.length;
  5107. const elementType = this.elementType;
  5108. let arrayType = Float32Array;
  5109. const paddedType = this.paddedType;
  5110. const paddedElementLength = builder.getTypeLength( paddedType );
  5111. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  5112. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  5113. this.value = new arrayType( length * paddedElementLength );
  5114. this.bufferCount = length;
  5115. this.bufferType = paddedType;
  5116. return super.setup( builder );
  5117. }
  5118. element( indexNode ) {
  5119. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  5120. }
  5121. }
  5122. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  5123. //
  5124. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  5125. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  5126. return nodeObject( new UniformArrayNode( values, nodeType ) );
  5127. };
  5128. class ReferenceElementNode extends ArrayElementNode {
  5129. static get type() {
  5130. return 'ReferenceElementNode';
  5131. }
  5132. constructor( referenceNode, indexNode ) {
  5133. super( referenceNode, indexNode );
  5134. this.referenceNode = referenceNode;
  5135. this.isReferenceElementNode = true;
  5136. }
  5137. getNodeType() {
  5138. return this.referenceNode.uniformType;
  5139. }
  5140. generate( builder ) {
  5141. const snippet = super.generate( builder );
  5142. const arrayType = this.referenceNode.getNodeType();
  5143. const elementType = this.getNodeType();
  5144. return builder.format( snippet, arrayType, elementType );
  5145. }
  5146. }
  5147. // TODO: Extends this from ReferenceBaseNode
  5148. class ReferenceNode extends Node {
  5149. static get type() {
  5150. return 'ReferenceNode';
  5151. }
  5152. constructor( property, uniformType, object = null, count = null ) {
  5153. super();
  5154. this.property = property;
  5155. this.uniformType = uniformType;
  5156. this.object = object;
  5157. this.count = count;
  5158. this.properties = property.split( '.' );
  5159. this.reference = object;
  5160. this.node = null;
  5161. this.group = null;
  5162. this.name = null;
  5163. this.updateType = NodeUpdateType.OBJECT;
  5164. }
  5165. element( indexNode ) {
  5166. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  5167. }
  5168. setGroup( group ) {
  5169. this.group = group;
  5170. return this;
  5171. }
  5172. label( name ) {
  5173. this.name = name;
  5174. return this;
  5175. }
  5176. setNodeType( uniformType ) {
  5177. let node = null;
  5178. if ( this.count !== null ) {
  5179. node = buffer( null, uniformType, this.count );
  5180. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  5181. node = uniformArray( null, uniformType );
  5182. } else if ( uniformType === 'texture' ) {
  5183. node = texture( null );
  5184. } else if ( uniformType === 'cubeTexture' ) {
  5185. node = cubeTexture( null );
  5186. } else {
  5187. node = uniform( null, uniformType );
  5188. }
  5189. if ( this.group !== null ) {
  5190. node.setGroup( this.group );
  5191. }
  5192. if ( this.name !== null ) node.label( this.name );
  5193. this.node = node.getSelf();
  5194. }
  5195. getNodeType( builder ) {
  5196. if ( this.node === null ) {
  5197. this.updateReference( builder );
  5198. this.updateValue();
  5199. }
  5200. return this.node.getNodeType( builder );
  5201. }
  5202. getValueFromReference( object = this.reference ) {
  5203. const { properties } = this;
  5204. let value = object[ properties[ 0 ] ];
  5205. for ( let i = 1; i < properties.length; i ++ ) {
  5206. value = value[ properties[ i ] ];
  5207. }
  5208. return value;
  5209. }
  5210. updateReference( state ) {
  5211. this.reference = this.object !== null ? this.object : state.object;
  5212. return this.reference;
  5213. }
  5214. setup() {
  5215. this.updateValue();
  5216. return this.node;
  5217. }
  5218. update( /*frame*/ ) {
  5219. this.updateValue();
  5220. }
  5221. updateValue() {
  5222. if ( this.node === null ) this.setNodeType( this.uniformType );
  5223. const value = this.getValueFromReference();
  5224. if ( Array.isArray( value ) ) {
  5225. this.node.array = value;
  5226. } else {
  5227. this.node.value = value;
  5228. }
  5229. }
  5230. }
  5231. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  5232. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  5233. class MaterialReferenceNode extends ReferenceNode {
  5234. static get type() {
  5235. return 'MaterialReferenceNode';
  5236. }
  5237. constructor( property, inputType, material = null ) {
  5238. super( property, inputType, material );
  5239. this.material = material;
  5240. //this.updateType = NodeUpdateType.RENDER;
  5241. this.isMaterialReferenceNode = true;
  5242. }
  5243. /*setNodeType( node ) {
  5244. super.setNodeType( node );
  5245. this.node.groupNode = renderGroup;
  5246. }*/
  5247. updateReference( state ) {
  5248. this.reference = this.material !== null ? this.material : state.material;
  5249. return this.reference;
  5250. }
  5251. }
  5252. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  5253. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  5254. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  5255. builder.geometry.computeTangents();
  5256. }
  5257. return attribute( 'tangent', 'vec4' );
  5258. } )();
  5259. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  5260. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  5261. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  5262. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  5263. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  5264. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  5265. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  5266. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  5267. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  5268. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  5269. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  5270. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  5271. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  5272. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  5273. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  5274. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  5275. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  5276. let bentNormal = anisotropyB.cross( positionViewDirection );
  5277. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  5278. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  5279. return bentNormal;
  5280. } )();
  5281. // Normal Mapping Without Precomputed Tangents
  5282. // http://www.thetenthplanet.de/archives/1180
  5283. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  5284. const { eye_pos, surf_norm, mapN, uv } = inputs;
  5285. const q0 = eye_pos.dFdx();
  5286. const q1 = eye_pos.dFdy();
  5287. const st0 = uv.dFdx();
  5288. const st1 = uv.dFdy();
  5289. const N = surf_norm; // normalized
  5290. const q1perp = q1.cross( N );
  5291. const q0perp = N.cross( q0 );
  5292. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  5293. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  5294. const det = T.dot( T ).max( B.dot( B ) );
  5295. const scale = faceDirection.mul( det.inverseSqrt() );
  5296. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  5297. } );
  5298. /**
  5299. * This class can be used for applying normals maps to materials.
  5300. *
  5301. * ```js
  5302. * material.normalNode = normalMap( texture( normalTex ) );
  5303. * ```
  5304. *
  5305. * @augments TempNode
  5306. */
  5307. class NormalMapNode extends TempNode {
  5308. static get type() {
  5309. return 'NormalMapNode';
  5310. }
  5311. /**
  5312. * Constructs a new normal map node.
  5313. *
  5314. * @param {Node} node - Represents the normal map data.
  5315. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  5316. */
  5317. constructor( node, scaleNode = null ) {
  5318. super( 'vec3' );
  5319. /**
  5320. * Represents the normal map data.
  5321. *
  5322. * @type {Node}
  5323. */
  5324. this.node = node;
  5325. /**
  5326. * Controls the intensity of the effect.
  5327. *
  5328. * @type {Node?}
  5329. * @default null
  5330. */
  5331. this.scaleNode = scaleNode;
  5332. /**
  5333. * The normal map type.
  5334. *
  5335. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  5336. * @default TangentSpaceNormalMap
  5337. */
  5338. this.normalMapType = TangentSpaceNormalMap;
  5339. }
  5340. setup( builder ) {
  5341. const { normalMapType, scaleNode } = this;
  5342. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  5343. if ( scaleNode !== null ) {
  5344. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  5345. }
  5346. let outputNode = null;
  5347. if ( normalMapType === ObjectSpaceNormalMap ) {
  5348. outputNode = transformNormalToView( normalMap );
  5349. } else if ( normalMapType === TangentSpaceNormalMap ) {
  5350. const tangent = builder.hasGeometryAttribute( 'tangent' );
  5351. if ( tangent === true ) {
  5352. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  5353. } else {
  5354. outputNode = perturbNormal2Arb( {
  5355. eye_pos: positionView,
  5356. surf_norm: normalView,
  5357. mapN: normalMap,
  5358. uv: uv()
  5359. } );
  5360. }
  5361. }
  5362. return outputNode;
  5363. }
  5364. }
  5365. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  5366. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  5367. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  5368. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  5369. // It's used to preserve the same TextureNode instance
  5370. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  5371. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  5372. return vec2(
  5373. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  5374. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  5375. ).mul( bumpScale );
  5376. } );
  5377. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  5378. const perturbNormalArb = Fn( ( inputs ) => {
  5379. const { surf_pos, surf_norm, dHdxy } = inputs;
  5380. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  5381. const vSigmaX = surf_pos.dFdx().normalize();
  5382. const vSigmaY = surf_pos.dFdy().normalize();
  5383. const vN = surf_norm; // normalized
  5384. const R1 = vSigmaY.cross( vN );
  5385. const R2 = vN.cross( vSigmaX );
  5386. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  5387. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  5388. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  5389. } );
  5390. /**
  5391. * This class can be used for applying bump maps to materials.
  5392. *
  5393. * ```js
  5394. * material.normalNode = bumpMap( texture( bumpTex ) );
  5395. * ```
  5396. *
  5397. * @augments TempNode
  5398. */
  5399. class BumpMapNode extends TempNode {
  5400. static get type() {
  5401. return 'BumpMapNode';
  5402. }
  5403. /**
  5404. * Constructs a new bump map node.
  5405. *
  5406. * @param {Node} textureNode - Represents the bump map data.
  5407. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  5408. */
  5409. constructor( textureNode, scaleNode = null ) {
  5410. super( 'vec3' );
  5411. /**
  5412. * Represents the bump map data.
  5413. *
  5414. * @type {Node}
  5415. */
  5416. this.textureNode = textureNode;
  5417. /**
  5418. * Controls the intensity of the bump effect.
  5419. *
  5420. * @type {Node?}
  5421. * @default null
  5422. */
  5423. this.scaleNode = scaleNode;
  5424. }
  5425. setup() {
  5426. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  5427. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  5428. return perturbNormalArb( {
  5429. surf_pos: positionView,
  5430. surf_norm: normalView,
  5431. dHdxy
  5432. } );
  5433. }
  5434. }
  5435. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  5436. const _propertyCache = new Map();
  5437. class MaterialNode extends Node {
  5438. static get type() {
  5439. return 'MaterialNode';
  5440. }
  5441. constructor( scope ) {
  5442. super();
  5443. this.scope = scope;
  5444. }
  5445. getCache( property, type ) {
  5446. let node = _propertyCache.get( property );
  5447. if ( node === undefined ) {
  5448. node = materialReference( property, type );
  5449. _propertyCache.set( property, node );
  5450. }
  5451. return node;
  5452. }
  5453. getFloat( property ) {
  5454. return this.getCache( property, 'float' );
  5455. }
  5456. getColor( property ) {
  5457. return this.getCache( property, 'color' );
  5458. }
  5459. getTexture( property ) {
  5460. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  5461. }
  5462. setup( builder ) {
  5463. const material = builder.context.material;
  5464. const scope = this.scope;
  5465. let node = null;
  5466. if ( scope === MaterialNode.COLOR ) {
  5467. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  5468. if ( material.map && material.map.isTexture === true ) {
  5469. node = colorNode.mul( this.getTexture( 'map' ) );
  5470. } else {
  5471. node = colorNode;
  5472. }
  5473. } else if ( scope === MaterialNode.OPACITY ) {
  5474. const opacityNode = this.getFloat( scope );
  5475. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  5476. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  5477. } else {
  5478. node = opacityNode;
  5479. }
  5480. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  5481. if ( material.specularMap && material.specularMap.isTexture === true ) {
  5482. node = this.getTexture( 'specular' ).r;
  5483. } else {
  5484. node = float( 1 );
  5485. }
  5486. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  5487. const specularIntensity = this.getFloat( scope );
  5488. if ( material.specularMap ) {
  5489. node = specularIntensity.mul( this.getTexture( scope ).a );
  5490. } else {
  5491. node = specularIntensity;
  5492. }
  5493. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  5494. const specularColorNode = this.getColor( scope );
  5495. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  5496. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  5497. } else {
  5498. node = specularColorNode;
  5499. }
  5500. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  5501. const roughnessNode = this.getFloat( scope );
  5502. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  5503. node = roughnessNode.mul( this.getTexture( scope ).g );
  5504. } else {
  5505. node = roughnessNode;
  5506. }
  5507. } else if ( scope === MaterialNode.METALNESS ) {
  5508. const metalnessNode = this.getFloat( scope );
  5509. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  5510. node = metalnessNode.mul( this.getTexture( scope ).b );
  5511. } else {
  5512. node = metalnessNode;
  5513. }
  5514. } else if ( scope === MaterialNode.EMISSIVE ) {
  5515. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  5516. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  5517. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  5518. node = emissiveNode.mul( this.getTexture( scope ) );
  5519. } else {
  5520. node = emissiveNode;
  5521. }
  5522. } else if ( scope === MaterialNode.NORMAL ) {
  5523. if ( material.normalMap ) {
  5524. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  5525. node.normalMapType = material.normalMapType;
  5526. } else if ( material.bumpMap ) {
  5527. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  5528. } else {
  5529. node = normalView;
  5530. }
  5531. } else if ( scope === MaterialNode.CLEARCOAT ) {
  5532. const clearcoatNode = this.getFloat( scope );
  5533. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  5534. node = clearcoatNode.mul( this.getTexture( scope ).r );
  5535. } else {
  5536. node = clearcoatNode;
  5537. }
  5538. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  5539. const clearcoatRoughnessNode = this.getFloat( scope );
  5540. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  5541. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  5542. } else {
  5543. node = clearcoatRoughnessNode;
  5544. }
  5545. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  5546. if ( material.clearcoatNormalMap ) {
  5547. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  5548. } else {
  5549. node = normalView;
  5550. }
  5551. } else if ( scope === MaterialNode.SHEEN ) {
  5552. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  5553. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  5554. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  5555. } else {
  5556. node = sheenNode;
  5557. }
  5558. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  5559. const sheenRoughnessNode = this.getFloat( scope );
  5560. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  5561. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  5562. } else {
  5563. node = sheenRoughnessNode;
  5564. }
  5565. node = node.clamp( 0.07, 1.0 );
  5566. } else if ( scope === MaterialNode.ANISOTROPY ) {
  5567. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  5568. const anisotropyPolar = this.getTexture( scope );
  5569. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  5570. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  5571. } else {
  5572. node = materialAnisotropyVector;
  5573. }
  5574. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  5575. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  5576. if ( material.iridescenceThicknessMap ) {
  5577. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  5578. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  5579. } else {
  5580. node = iridescenceThicknessMaximum;
  5581. }
  5582. } else if ( scope === MaterialNode.TRANSMISSION ) {
  5583. const transmissionNode = this.getFloat( scope );
  5584. if ( material.transmissionMap ) {
  5585. node = transmissionNode.mul( this.getTexture( scope ).r );
  5586. } else {
  5587. node = transmissionNode;
  5588. }
  5589. } else if ( scope === MaterialNode.THICKNESS ) {
  5590. const thicknessNode = this.getFloat( scope );
  5591. if ( material.thicknessMap ) {
  5592. node = thicknessNode.mul( this.getTexture( scope ).g );
  5593. } else {
  5594. node = thicknessNode;
  5595. }
  5596. } else if ( scope === MaterialNode.IOR ) {
  5597. node = this.getFloat( scope );
  5598. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  5599. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  5600. } else if ( scope === MaterialNode.AO_MAP ) {
  5601. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  5602. } else {
  5603. const outputType = this.getNodeType( builder );
  5604. node = this.getCache( scope, outputType );
  5605. }
  5606. return node;
  5607. }
  5608. }
  5609. MaterialNode.ALPHA_TEST = 'alphaTest';
  5610. MaterialNode.COLOR = 'color';
  5611. MaterialNode.OPACITY = 'opacity';
  5612. MaterialNode.SHININESS = 'shininess';
  5613. MaterialNode.SPECULAR = 'specular';
  5614. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  5615. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  5616. MaterialNode.SPECULAR_COLOR = 'specularColor';
  5617. MaterialNode.REFLECTIVITY = 'reflectivity';
  5618. MaterialNode.ROUGHNESS = 'roughness';
  5619. MaterialNode.METALNESS = 'metalness';
  5620. MaterialNode.NORMAL = 'normal';
  5621. MaterialNode.CLEARCOAT = 'clearcoat';
  5622. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  5623. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  5624. MaterialNode.EMISSIVE = 'emissive';
  5625. MaterialNode.ROTATION = 'rotation';
  5626. MaterialNode.SHEEN = 'sheen';
  5627. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  5628. MaterialNode.ANISOTROPY = 'anisotropy';
  5629. MaterialNode.IRIDESCENCE = 'iridescence';
  5630. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  5631. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  5632. MaterialNode.IOR = 'ior';
  5633. MaterialNode.TRANSMISSION = 'transmission';
  5634. MaterialNode.THICKNESS = 'thickness';
  5635. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  5636. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  5637. MaterialNode.LINE_SCALE = 'scale';
  5638. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  5639. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  5640. MaterialNode.LINE_WIDTH = 'linewidth';
  5641. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  5642. MaterialNode.POINT_WIDTH = 'pointWidth';
  5643. MaterialNode.DISPERSION = 'dispersion';
  5644. MaterialNode.LIGHT_MAP = 'light';
  5645. MaterialNode.AO_MAP = 'ao';
  5646. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  5647. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  5648. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  5649. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  5650. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  5651. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  5652. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  5653. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  5654. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  5655. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  5656. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  5657. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  5658. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  5659. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  5660. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  5661. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  5662. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  5663. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  5664. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  5665. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  5666. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  5667. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  5668. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  5669. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  5670. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  5671. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  5672. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  5673. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  5674. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  5675. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  5676. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  5677. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  5678. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  5679. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  5680. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  5681. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  5682. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  5683. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  5684. return frame.material;
  5685. } ).onRenderUpdate( function ( { material } ) {
  5686. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  5687. } );
  5688. class ModelViewProjectionNode extends TempNode {
  5689. static get type() {
  5690. return 'ModelViewProjectionNode';
  5691. }
  5692. constructor( positionNode = null ) {
  5693. super( 'vec4' );
  5694. this.positionNode = positionNode;
  5695. }
  5696. setup( builder ) {
  5697. if ( builder.shaderStage === 'fragment' ) {
  5698. return varying( builder.context.mvp );
  5699. }
  5700. const position = this.positionNode || positionLocal;
  5701. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  5702. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  5703. }
  5704. }
  5705. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  5706. /**
  5707. * This class represents shader indices of different types. The following predefined node
  5708. * objects cover frequent use cases:
  5709. *
  5710. * - `vertexIndex`: The index of a vertex within a mesh.
  5711. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  5712. * - `drawIndex`: The index of a draw call.
  5713. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  5714. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  5715. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  5716. *
  5717. * @augments Node
  5718. */
  5719. class IndexNode extends Node {
  5720. static get type() {
  5721. return 'IndexNode';
  5722. }
  5723. /**
  5724. * Constructs a new index node.
  5725. *
  5726. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  5727. */
  5728. constructor( scope ) {
  5729. super( 'uint' );
  5730. /**
  5731. * The scope of the index node.
  5732. *
  5733. * @type {String}
  5734. */
  5735. this.scope = scope;
  5736. /**
  5737. * This flag can be used for type testing.
  5738. *
  5739. * @type {Boolean}
  5740. * @readonly
  5741. * @default true
  5742. */
  5743. this.isIndexNode = true;
  5744. }
  5745. generate( builder ) {
  5746. const nodeType = this.getNodeType( builder );
  5747. const scope = this.scope;
  5748. let propertyName;
  5749. if ( scope === IndexNode.VERTEX ) {
  5750. propertyName = builder.getVertexIndex();
  5751. } else if ( scope === IndexNode.INSTANCE ) {
  5752. propertyName = builder.getInstanceIndex();
  5753. } else if ( scope === IndexNode.DRAW ) {
  5754. propertyName = builder.getDrawIndex();
  5755. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  5756. propertyName = builder.getInvocationLocalIndex();
  5757. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  5758. propertyName = builder.getInvocationSubgroupIndex();
  5759. } else if ( scope === IndexNode.SUBGROUP ) {
  5760. propertyName = builder.getSubgroupIndex();
  5761. } else {
  5762. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  5763. }
  5764. let output;
  5765. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5766. output = propertyName;
  5767. } else {
  5768. const nodeVarying = varying( this );
  5769. output = nodeVarying.build( builder, nodeType );
  5770. }
  5771. return output;
  5772. }
  5773. }
  5774. IndexNode.VERTEX = 'vertex';
  5775. IndexNode.INSTANCE = 'instance';
  5776. IndexNode.SUBGROUP = 'subgroup';
  5777. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  5778. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  5779. IndexNode.DRAW = 'draw';
  5780. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  5781. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  5782. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  5783. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  5784. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  5785. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  5786. class InstanceNode extends Node {
  5787. static get type() {
  5788. return 'InstanceNode';
  5789. }
  5790. constructor( count, instanceMatrix, instanceColor ) {
  5791. super( 'void' );
  5792. this.count = count;
  5793. this.instanceMatrix = instanceMatrix;
  5794. this.instanceColor = instanceColor;
  5795. this.instanceMatrixNode = null;
  5796. this.instanceColorNode = null;
  5797. this.updateType = NodeUpdateType.FRAME;
  5798. this.buffer = null;
  5799. this.bufferColor = null;
  5800. }
  5801. setup( builder ) {
  5802. const { count, instanceMatrix, instanceColor } = this;
  5803. let { instanceMatrixNode, instanceColorNode } = this;
  5804. if ( instanceMatrixNode === null ) {
  5805. // 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.
  5806. if ( count <= 1000 ) {
  5807. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  5808. } else {
  5809. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  5810. this.buffer = buffer;
  5811. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5812. const instanceBuffers = [
  5813. // F.Signature -> bufferAttribute( array, type, stride, offset )
  5814. bufferFn( buffer, 'vec4', 16, 0 ),
  5815. bufferFn( buffer, 'vec4', 16, 4 ),
  5816. bufferFn( buffer, 'vec4', 16, 8 ),
  5817. bufferFn( buffer, 'vec4', 16, 12 )
  5818. ];
  5819. instanceMatrixNode = mat4( ...instanceBuffers );
  5820. }
  5821. this.instanceMatrixNode = instanceMatrixNode;
  5822. }
  5823. if ( instanceColor && instanceColorNode === null ) {
  5824. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  5825. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5826. this.bufferColor = buffer;
  5827. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  5828. this.instanceColorNode = instanceColorNode;
  5829. }
  5830. // POSITION
  5831. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  5832. positionLocal.assign( instancePosition );
  5833. // NORMAL
  5834. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5835. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  5836. // ASSIGNS
  5837. normalLocal.assign( instanceNormal );
  5838. }
  5839. // COLOR
  5840. if ( this.instanceColorNode !== null ) {
  5841. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  5842. }
  5843. }
  5844. update( /*frame*/ ) {
  5845. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  5846. this.buffer.version = this.instanceMatrix.version;
  5847. }
  5848. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  5849. this.bufferColor.version = this.instanceColor.version;
  5850. }
  5851. }
  5852. }
  5853. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  5854. class InstancedMeshNode extends InstanceNode {
  5855. static get type() {
  5856. return 'InstancedMeshNode';
  5857. }
  5858. constructor( instanceMesh ) {
  5859. const { count, instanceMatrix, instanceColor } = instanceMesh;
  5860. super( count, instanceMatrix, instanceColor );
  5861. this.instanceMesh = instanceMesh;
  5862. }
  5863. }
  5864. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  5865. class BatchNode extends Node {
  5866. static get type() {
  5867. return 'BatchNode';
  5868. }
  5869. constructor( batchMesh ) {
  5870. super( 'void' );
  5871. this.batchMesh = batchMesh;
  5872. this.batchingIdNode = null;
  5873. }
  5874. setup( builder ) {
  5875. // POSITION
  5876. if ( this.batchingIdNode === null ) {
  5877. if ( builder.getDrawIndex() === null ) {
  5878. this.batchingIdNode = instanceIndex;
  5879. } else {
  5880. this.batchingIdNode = drawIndex;
  5881. }
  5882. }
  5883. const getIndirectIndex = Fn( ( [ id ] ) => {
  5884. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  5885. const x = int( id ).modInt( int( size ) );
  5886. const y = int( id ).div( int( size ) );
  5887. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  5888. } ).setLayout( {
  5889. name: 'getIndirectIndex',
  5890. type: 'uint',
  5891. inputs: [
  5892. { name: 'id', type: 'int' }
  5893. ]
  5894. } );
  5895. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  5896. const matricesTexture = this.batchMesh._matricesTexture;
  5897. const size = textureSize( textureLoad( matricesTexture ), 0 );
  5898. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  5899. const x = j.modInt( size );
  5900. const y = j.div( int( size ) );
  5901. const batchingMatrix = mat4(
  5902. textureLoad( matricesTexture, ivec2( x, y ) ),
  5903. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  5904. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  5905. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  5906. );
  5907. const colorsTexture = this.batchMesh._colorsTexture;
  5908. if ( colorsTexture !== null ) {
  5909. const getBatchingColor = Fn( ( [ id ] ) => {
  5910. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  5911. const j = id;
  5912. const x = j.modInt( size );
  5913. const y = j.div( size );
  5914. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  5915. } ).setLayout( {
  5916. name: 'getBatchingColor',
  5917. type: 'vec3',
  5918. inputs: [
  5919. { name: 'id', type: 'int' }
  5920. ]
  5921. } );
  5922. const color = getBatchingColor( indirectId );
  5923. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  5924. }
  5925. const bm = mat3( batchingMatrix );
  5926. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  5927. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  5928. const batchingNormal = bm.mul( transformedNormal ).xyz;
  5929. normalLocal.assign( batchingNormal );
  5930. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5931. tangentLocal.mulAssign( bm );
  5932. }
  5933. }
  5934. }
  5935. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  5936. const _frameId = new WeakMap();
  5937. class SkinningNode extends Node {
  5938. static get type() {
  5939. return 'SkinningNode';
  5940. }
  5941. constructor( skinnedMesh, useReference = false ) {
  5942. super( 'void' );
  5943. this.skinnedMesh = skinnedMesh;
  5944. this.useReference = useReference;
  5945. this.updateType = NodeUpdateType.OBJECT;
  5946. //
  5947. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  5948. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  5949. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  5950. if ( useReference ) {
  5951. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  5952. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  5953. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5954. } else {
  5955. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  5956. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  5957. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  5958. }
  5959. this.bindMatrixNode = bindMatrixNode;
  5960. this.bindMatrixInverseNode = bindMatrixInverseNode;
  5961. this.boneMatricesNode = boneMatricesNode;
  5962. this.previousBoneMatricesNode = null;
  5963. }
  5964. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  5965. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5966. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5967. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5968. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5969. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5970. // POSITION
  5971. const skinVertex = bindMatrixNode.mul( position );
  5972. const skinned = add(
  5973. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  5974. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  5975. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  5976. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  5977. );
  5978. return bindMatrixInverseNode.mul( skinned ).xyz;
  5979. }
  5980. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  5981. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5982. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5983. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5984. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5985. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5986. // NORMAL
  5987. let skinMatrix = add(
  5988. skinWeightNode.x.mul( boneMatX ),
  5989. skinWeightNode.y.mul( boneMatY ),
  5990. skinWeightNode.z.mul( boneMatZ ),
  5991. skinWeightNode.w.mul( boneMatW )
  5992. );
  5993. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  5994. return skinMatrix.transformDirection( normal ).xyz;
  5995. }
  5996. getPreviousSkinnedPosition( builder ) {
  5997. const skinnedMesh = builder.object;
  5998. if ( this.previousBoneMatricesNode === null ) {
  5999. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  6000. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  6001. }
  6002. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  6003. }
  6004. needsPreviousBoneMatrices( builder ) {
  6005. const mrt = builder.renderer.getMRT();
  6006. return mrt && mrt.has( 'velocity' );
  6007. }
  6008. setup( builder ) {
  6009. if ( this.needsPreviousBoneMatrices( builder ) ) {
  6010. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  6011. }
  6012. const skinPosition = this.getSkinnedPosition();
  6013. positionLocal.assign( skinPosition );
  6014. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  6015. const skinNormal = this.getSkinnedNormal();
  6016. normalLocal.assign( skinNormal );
  6017. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  6018. tangentLocal.assign( skinNormal );
  6019. }
  6020. }
  6021. }
  6022. generate( builder, output ) {
  6023. if ( output !== 'void' ) {
  6024. return positionLocal.build( builder, output );
  6025. }
  6026. }
  6027. update( frame ) {
  6028. const object = this.useReference ? frame.object : this.skinnedMesh;
  6029. const skeleton = object.skeleton;
  6030. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  6031. _frameId.set( skeleton, frame.frameId );
  6032. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  6033. skeleton.update();
  6034. }
  6035. }
  6036. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  6037. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  6038. /**
  6039. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  6040. * ```js
  6041. * Loop( count, ( { i } ) => {
  6042. *
  6043. * } );
  6044. * ```
  6045. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  6046. * ```js
  6047. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  6048. *
  6049. * } );
  6050. *```
  6051. * Nested loops can be definde in a compacted form:
  6052. * ```js
  6053. * Loop( 10, 5, ( { i, j } ) => {
  6054. *
  6055. * } );
  6056. * ```
  6057. * Loops that should run backwards can be defined like so:
  6058. * ```js
  6059. * Loop( { start: 10 }, () => {} );
  6060. * ```
  6061. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  6062. * @augments Node
  6063. */
  6064. class LoopNode extends Node {
  6065. static get type() {
  6066. return 'LoopNode';
  6067. }
  6068. /**
  6069. * Constructs a new loop node.
  6070. *
  6071. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  6072. */
  6073. constructor( params = [] ) {
  6074. super();
  6075. this.params = params;
  6076. }
  6077. /**
  6078. * Returns a loop variable name based on an index. The pattern is
  6079. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  6080. *
  6081. * @param {Number} index - The index.
  6082. * @return {String} The loop variable name.
  6083. */
  6084. getVarName( index ) {
  6085. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  6086. }
  6087. /**
  6088. * Returns properties about this node.
  6089. *
  6090. * @param {NodeBuilder} builder - The current node builder.
  6091. * @return {Object} The node properties.
  6092. */
  6093. getProperties( builder ) {
  6094. const properties = builder.getNodeProperties( this );
  6095. if ( properties.stackNode !== undefined ) return properties;
  6096. //
  6097. const inputs = {};
  6098. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  6099. const param = this.params[ i ];
  6100. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  6101. const type = ( param.isNode !== true && param.type ) || 'int';
  6102. inputs[ name ] = expression( name, type );
  6103. }
  6104. const stack = builder.addStack(); // TODO: cache() it
  6105. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  6106. properties.stackNode = stack;
  6107. builder.removeStack();
  6108. return properties;
  6109. }
  6110. /**
  6111. * This method is overwritten since the node type is inferred based on the loop configuration.
  6112. *
  6113. * @param {NodeBuilder} builder - The current node builder.
  6114. * @return {String} The node type.
  6115. */
  6116. getNodeType( builder ) {
  6117. const { returnsNode } = this.getProperties( builder );
  6118. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  6119. }
  6120. setup( builder ) {
  6121. // setup properties
  6122. this.getProperties( builder );
  6123. }
  6124. generate( builder ) {
  6125. const properties = this.getProperties( builder );
  6126. const params = this.params;
  6127. const stackNode = properties.stackNode;
  6128. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  6129. const param = params[ i ];
  6130. let start = null, end = null, name = null, type = null, condition = null, update = null;
  6131. if ( param.isNode ) {
  6132. type = 'int';
  6133. name = this.getVarName( i );
  6134. start = '0';
  6135. end = param.build( builder, type );
  6136. condition = '<';
  6137. } else {
  6138. type = param.type || 'int';
  6139. name = param.name || this.getVarName( i );
  6140. start = param.start;
  6141. end = param.end;
  6142. condition = param.condition;
  6143. update = param.update;
  6144. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  6145. else if ( start && start.isNode ) start = start.build( builder, type );
  6146. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  6147. else if ( end && end.isNode ) end = end.build( builder, type );
  6148. if ( start !== undefined && end === undefined ) {
  6149. start = start + ' - 1';
  6150. end = '0';
  6151. condition = '>=';
  6152. } else if ( end !== undefined && start === undefined ) {
  6153. start = '0';
  6154. condition = '<';
  6155. }
  6156. if ( condition === undefined ) {
  6157. if ( Number( start ) > Number( end ) ) {
  6158. condition = '>=';
  6159. } else {
  6160. condition = '<';
  6161. }
  6162. }
  6163. }
  6164. const internalParam = { start, end, condition };
  6165. //
  6166. const startSnippet = internalParam.start;
  6167. const endSnippet = internalParam.end;
  6168. let declarationSnippet = '';
  6169. let conditionalSnippet = '';
  6170. let updateSnippet = '';
  6171. if ( ! update ) {
  6172. if ( type === 'int' || type === 'uint' ) {
  6173. if ( condition.includes( '<' ) ) update = '++';
  6174. else update = '--';
  6175. } else {
  6176. if ( condition.includes( '<' ) ) update = '+= 1.';
  6177. else update = '-= 1.';
  6178. }
  6179. }
  6180. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  6181. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  6182. updateSnippet += name + ' ' + update;
  6183. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  6184. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  6185. }
  6186. const stackSnippet = stackNode.build( builder, 'void' );
  6187. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  6188. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  6189. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  6190. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  6191. }
  6192. builder.addFlowTab();
  6193. return returnsSnippet;
  6194. }
  6195. }
  6196. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  6197. const Continue = () => expression( 'continue' ).append();
  6198. const Break = () => expression( 'break' ).append();
  6199. //
  6200. const loop = ( ...params ) => { // @deprecated, r168
  6201. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  6202. return Loop( ...params );
  6203. };
  6204. const _morphTextures = /*@__PURE__*/ new WeakMap();
  6205. const _morphVec4 = /*@__PURE__*/ new Vector4();
  6206. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  6207. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  6208. const y = texelIndex.div( width );
  6209. const x = texelIndex.sub( y.mul( width ) );
  6210. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  6211. return bufferAttrib.mul( influence );
  6212. } );
  6213. function getEntry( geometry ) {
  6214. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6215. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  6216. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  6217. // instead of using attributes, the WebGL 2 code path encodes morph targets
  6218. // into an array of data textures. Each layer represents a single morph target.
  6219. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6220. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6221. let entry = _morphTextures.get( geometry );
  6222. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  6223. if ( entry !== undefined ) entry.texture.dispose();
  6224. const morphTargets = geometry.morphAttributes.position || [];
  6225. const morphNormals = geometry.morphAttributes.normal || [];
  6226. const morphColors = geometry.morphAttributes.color || [];
  6227. let vertexDataCount = 0;
  6228. if ( hasMorphPosition === true ) vertexDataCount = 1;
  6229. if ( hasMorphNormals === true ) vertexDataCount = 2;
  6230. if ( hasMorphColors === true ) vertexDataCount = 3;
  6231. let width = geometry.attributes.position.count * vertexDataCount;
  6232. let height = 1;
  6233. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  6234. if ( width > maxTextureSize ) {
  6235. height = Math.ceil( width / maxTextureSize );
  6236. width = maxTextureSize;
  6237. }
  6238. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  6239. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  6240. bufferTexture.type = FloatType;
  6241. bufferTexture.needsUpdate = true;
  6242. // fill buffer
  6243. const vertexDataStride = vertexDataCount * 4;
  6244. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  6245. const morphTarget = morphTargets[ i ];
  6246. const morphNormal = morphNormals[ i ];
  6247. const morphColor = morphColors[ i ];
  6248. const offset = width * height * 4 * i;
  6249. for ( let j = 0; j < morphTarget.count; j ++ ) {
  6250. const stride = j * vertexDataStride;
  6251. if ( hasMorphPosition === true ) {
  6252. _morphVec4.fromBufferAttribute( morphTarget, j );
  6253. buffer[ offset + stride + 0 ] = _morphVec4.x;
  6254. buffer[ offset + stride + 1 ] = _morphVec4.y;
  6255. buffer[ offset + stride + 2 ] = _morphVec4.z;
  6256. buffer[ offset + stride + 3 ] = 0;
  6257. }
  6258. if ( hasMorphNormals === true ) {
  6259. _morphVec4.fromBufferAttribute( morphNormal, j );
  6260. buffer[ offset + stride + 4 ] = _morphVec4.x;
  6261. buffer[ offset + stride + 5 ] = _morphVec4.y;
  6262. buffer[ offset + stride + 6 ] = _morphVec4.z;
  6263. buffer[ offset + stride + 7 ] = 0;
  6264. }
  6265. if ( hasMorphColors === true ) {
  6266. _morphVec4.fromBufferAttribute( morphColor, j );
  6267. buffer[ offset + stride + 8 ] = _morphVec4.x;
  6268. buffer[ offset + stride + 9 ] = _morphVec4.y;
  6269. buffer[ offset + stride + 10 ] = _morphVec4.z;
  6270. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  6271. }
  6272. }
  6273. }
  6274. entry = {
  6275. count: morphTargetsCount,
  6276. texture: bufferTexture,
  6277. stride: vertexDataCount,
  6278. size: new Vector2( width, height )
  6279. };
  6280. _morphTextures.set( geometry, entry );
  6281. function disposeTexture() {
  6282. bufferTexture.dispose();
  6283. _morphTextures.delete( geometry );
  6284. geometry.removeEventListener( 'dispose', disposeTexture );
  6285. }
  6286. geometry.addEventListener( 'dispose', disposeTexture );
  6287. }
  6288. return entry;
  6289. }
  6290. class MorphNode extends Node {
  6291. static get type() {
  6292. return 'MorphNode';
  6293. }
  6294. constructor( mesh ) {
  6295. super( 'void' );
  6296. this.mesh = mesh;
  6297. this.morphBaseInfluence = uniform( 1 );
  6298. this.updateType = NodeUpdateType.OBJECT;
  6299. }
  6300. setup( builder ) {
  6301. const { geometry } = builder;
  6302. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6303. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  6304. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6305. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6306. // nodes
  6307. const { texture: bufferMap, stride, size } = getEntry( geometry );
  6308. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  6309. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  6310. const width = int( size.width );
  6311. Loop( morphTargetsCount, ( { i } ) => {
  6312. const influence = float( 0 ).toVar();
  6313. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  6314. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  6315. } else {
  6316. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  6317. }
  6318. if ( hasMorphPosition === true ) {
  6319. positionLocal.addAssign( getMorph( {
  6320. bufferMap,
  6321. influence,
  6322. stride,
  6323. width,
  6324. depth: i,
  6325. offset: int( 0 )
  6326. } ) );
  6327. }
  6328. if ( hasMorphNormals === true ) {
  6329. normalLocal.addAssign( getMorph( {
  6330. bufferMap,
  6331. influence,
  6332. stride,
  6333. width,
  6334. depth: i,
  6335. offset: int( 1 )
  6336. } ) );
  6337. }
  6338. } );
  6339. }
  6340. update() {
  6341. const morphBaseInfluence = this.morphBaseInfluence;
  6342. if ( this.mesh.geometry.morphTargetsRelative ) {
  6343. morphBaseInfluence.value = 1;
  6344. } else {
  6345. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  6346. }
  6347. }
  6348. }
  6349. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  6350. /**
  6351. * Base class for lighting nodes.
  6352. *
  6353. * @augments Node
  6354. */
  6355. class LightingNode extends Node {
  6356. static get type() {
  6357. return 'LightingNode';
  6358. }
  6359. /**
  6360. * Constructs a new lighting node.
  6361. */
  6362. constructor() {
  6363. super( 'vec3' );
  6364. /**
  6365. * This flag can be used for type testing.
  6366. *
  6367. * @type {Boolean}
  6368. * @readonly
  6369. * @default true
  6370. */
  6371. this.isLightingNode = true;
  6372. }
  6373. }
  6374. /**
  6375. * A generic class that can be used by nodes which contribute
  6376. * ambient occlusion to the scene. E.g. an ambient occlusion map
  6377. * node can be used as input for this module. Used in {@link NodeMaterial}.
  6378. *
  6379. * @augments LightingNode
  6380. */
  6381. class AONode extends LightingNode {
  6382. static get type() {
  6383. return 'AONode';
  6384. }
  6385. /**
  6386. * Constructs a new AO node.
  6387. *
  6388. * @param {Node<float>} aoNode - The ambient occlusion node.
  6389. */
  6390. constructor( aoNode = null ) {
  6391. super();
  6392. /**
  6393. * The ambient occlusion node.
  6394. *
  6395. * @type {Node<float>}
  6396. */
  6397. this.aoNode = aoNode;
  6398. }
  6399. setup( builder ) {
  6400. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  6401. }
  6402. }
  6403. /**
  6404. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  6405. * by adding lighting specific context data. It represents the runtime context of
  6406. * {@link LightsNode}.
  6407. *
  6408. * @augments ContextNode
  6409. */
  6410. class LightingContextNode extends ContextNode {
  6411. static get type() {
  6412. return 'LightingContextNode';
  6413. }
  6414. /**
  6415. * Constructs a new lighting context node.
  6416. *
  6417. * @param {LightsNode} node - The lights node.
  6418. * @param {LightingModel} [lightingModel=null] - The current lighting model.
  6419. * @param {Node<vec3>} [backdropNode=null] - A backdrop node.
  6420. * @param {Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  6421. */
  6422. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  6423. super( node );
  6424. /**
  6425. * The current lighting model.
  6426. *
  6427. * @type {LightingModel}
  6428. * @default null
  6429. */
  6430. this.lightingModel = lightingModel;
  6431. /**
  6432. * A backdrop node.
  6433. *
  6434. * @type {Node<vec3>}
  6435. * @default null
  6436. */
  6437. this.backdropNode = backdropNode;
  6438. /**
  6439. * A backdrop alpha node.
  6440. *
  6441. * @type {Node<float>}
  6442. * @default null
  6443. */
  6444. this.backdropAlphaNode = backdropAlphaNode;
  6445. this._value = null;
  6446. }
  6447. /**
  6448. * Returns a lighting context object.
  6449. *
  6450. * @return {{
  6451. * radiance: Node<vec3>,
  6452. * irradiance: Node<vec3>,
  6453. * iblIrradiance: Node<vec3>,
  6454. * ambientOcclusion: Node<float>,
  6455. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  6456. * backdrop: Node<vec3>,
  6457. * backdropAlpha: Node<float>
  6458. * }} The lighting context object.
  6459. */
  6460. getContext() {
  6461. const { backdropNode, backdropAlphaNode } = this;
  6462. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  6463. directSpecular = vec3().toVar( 'directSpecular' ),
  6464. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  6465. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  6466. const reflectedLight = {
  6467. directDiffuse,
  6468. directSpecular,
  6469. indirectDiffuse,
  6470. indirectSpecular
  6471. };
  6472. const context = {
  6473. radiance: vec3().toVar( 'radiance' ),
  6474. irradiance: vec3().toVar( 'irradiance' ),
  6475. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  6476. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  6477. reflectedLight,
  6478. backdrop: backdropNode,
  6479. backdropAlpha: backdropAlphaNode
  6480. };
  6481. return context;
  6482. }
  6483. setup( builder ) {
  6484. this.value = this._value || ( this._value = this.getContext() );
  6485. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  6486. return super.setup( builder );
  6487. }
  6488. }
  6489. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  6490. /**
  6491. * A generic class that can be used by nodes which contribute
  6492. * irradiance to the scene. E.g. a light map node can be used
  6493. * as input for this module. Used in {@link NodeMaterial}.
  6494. *
  6495. * @augments LightingNode
  6496. */
  6497. class IrradianceNode extends LightingNode {
  6498. static get type() {
  6499. return 'IrradianceNode';
  6500. }
  6501. /**
  6502. * Constructs a new irradiance node.
  6503. *
  6504. * @param {Node<vec3>} node - A node contributing irradiance.
  6505. */
  6506. constructor( node ) {
  6507. super();
  6508. /**
  6509. * A node contributing irradiance.
  6510. *
  6511. * @type {Node<vec3>}
  6512. */
  6513. this.node = node;
  6514. }
  6515. setup( builder ) {
  6516. builder.context.irradiance.addAssign( this.node );
  6517. }
  6518. }
  6519. let screenSizeVec, viewportVec;
  6520. /**
  6521. * This node provides a collection of screen related metrics.
  6522. * Depending on {@link ScreenNode#scope}, the nodes can represent
  6523. * resolution or viewport data as well as fragment or uv coordinates.
  6524. *
  6525. * @augments Node
  6526. */
  6527. class ScreenNode extends Node {
  6528. static get type() {
  6529. return 'ScreenNode';
  6530. }
  6531. /**
  6532. * Constructs a new screen node.
  6533. *
  6534. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  6535. */
  6536. constructor( scope ) {
  6537. super();
  6538. /**
  6539. * The node represents different metric depending on which scope is selected.
  6540. *
  6541. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  6542. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  6543. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  6544. * - `ScreenNode.UV`: Normalized screen coordinates.
  6545. *
  6546. * @type {('coordinate'|'viewport'|'size'|'uv')}
  6547. */
  6548. this.scope = scope;
  6549. /**
  6550. * This flag can be used for type testing.
  6551. *
  6552. * @type {Boolean}
  6553. * @readonly
  6554. * @default true
  6555. */
  6556. this.isViewportNode = true;
  6557. }
  6558. /**
  6559. * This method is overwritten since the node type depends on the selected scope.
  6560. *
  6561. * @return {('vec2'|'vec4')} The node type.
  6562. */
  6563. getNodeType() {
  6564. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  6565. else return 'vec2';
  6566. }
  6567. /**
  6568. * This method is overwritten since the node's update type depends on the selected scope.
  6569. *
  6570. * @return {NodeUpdateType} The update type.
  6571. */
  6572. getUpdateType() {
  6573. let updateType = NodeUpdateType.NONE;
  6574. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  6575. updateType = NodeUpdateType.RENDER;
  6576. }
  6577. this.updateType = updateType;
  6578. return updateType;
  6579. }
  6580. /**
  6581. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  6582. * from the current renderer.
  6583. *
  6584. * @param {NodeFrame} frame - A reference to the current node frame.
  6585. */
  6586. update( { renderer } ) {
  6587. const renderTarget = renderer.getRenderTarget();
  6588. if ( this.scope === ScreenNode.VIEWPORT ) {
  6589. if ( renderTarget !== null ) {
  6590. viewportVec.copy( renderTarget.viewport );
  6591. } else {
  6592. renderer.getViewport( viewportVec );
  6593. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  6594. }
  6595. } else {
  6596. if ( renderTarget !== null ) {
  6597. screenSizeVec.width = renderTarget.width;
  6598. screenSizeVec.height = renderTarget.height;
  6599. } else {
  6600. renderer.getDrawingBufferSize( screenSizeVec );
  6601. }
  6602. }
  6603. }
  6604. setup( /*builder*/ ) {
  6605. const scope = this.scope;
  6606. let output = null;
  6607. if ( scope === ScreenNode.SIZE ) {
  6608. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  6609. } else if ( scope === ScreenNode.VIEWPORT ) {
  6610. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  6611. } else {
  6612. output = vec2( screenCoordinate.div( screenSize ) );
  6613. }
  6614. return output;
  6615. }
  6616. generate( builder ) {
  6617. if ( this.scope === ScreenNode.COORDINATE ) {
  6618. let coord = builder.getFragCoord();
  6619. if ( builder.isFlipY() ) {
  6620. // follow webgpu standards
  6621. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  6622. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  6623. }
  6624. return coord;
  6625. }
  6626. return super.generate( builder );
  6627. }
  6628. }
  6629. ScreenNode.COORDINATE = 'coordinate';
  6630. ScreenNode.VIEWPORT = 'viewport';
  6631. ScreenNode.SIZE = 'size';
  6632. ScreenNode.UV = 'uv';
  6633. // Screen
  6634. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  6635. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  6636. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  6637. // Viewport
  6638. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  6639. const viewportSize = viewport.zw;
  6640. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  6641. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  6642. // Deprecated
  6643. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  6644. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  6645. return screenSize;
  6646. }, 'vec2' ).once() )();
  6647. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6648. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  6649. return screenUV;
  6650. }, 'vec2' ).once() )();
  6651. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6652. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  6653. return screenUV.flipY();
  6654. }, 'vec2' ).once() )();
  6655. const _size$4 = /*@__PURE__*/ new Vector2();
  6656. /**
  6657. * A special type of texture node which represents the data of the current viewport
  6658. * as a texture. The module extracts data from the current bound framebuffer with
  6659. * a copy operation so no extra render pass is required to produce the texture data
  6660. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  6661. * variety of effects like refractive or transmissive materials.
  6662. *
  6663. * @augments TextureNode
  6664. */
  6665. class ViewportTextureNode extends TextureNode {
  6666. static get type() {
  6667. return 'ViewportTextureNode';
  6668. }
  6669. /**
  6670. * Constructs a new viewport texture node.
  6671. *
  6672. * @param {Node} [uvNode=screenUV] - The uv node.
  6673. * @param {Node?} [levelNode=null] - The level node.
  6674. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  6675. */
  6676. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  6677. if ( framebufferTexture === null ) {
  6678. framebufferTexture = new FramebufferTexture();
  6679. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  6680. }
  6681. super( framebufferTexture, uvNode, levelNode );
  6682. /**
  6683. * Whether to generate mipmaps or not.
  6684. *
  6685. * @type {Boolean}
  6686. * @default false
  6687. */
  6688. this.generateMipmaps = false;
  6689. /**
  6690. * This flag can be used for type testing.
  6691. *
  6692. * @type {Boolean}
  6693. * @readonly
  6694. * @default true
  6695. */
  6696. this.isOutputTextureNode = true;
  6697. /**
  6698. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  6699. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  6700. *
  6701. * @type {String}
  6702. * @default 'frame'
  6703. */
  6704. this.updateBeforeType = NodeUpdateType.FRAME;
  6705. }
  6706. updateBefore( frame ) {
  6707. const renderer = frame.renderer;
  6708. renderer.getDrawingBufferSize( _size$4 );
  6709. //
  6710. const framebufferTexture = this.value;
  6711. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  6712. framebufferTexture.image.width = _size$4.width;
  6713. framebufferTexture.image.height = _size$4.height;
  6714. framebufferTexture.needsUpdate = true;
  6715. }
  6716. //
  6717. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  6718. framebufferTexture.generateMipmaps = this.generateMipmaps;
  6719. renderer.copyFramebufferToTexture( framebufferTexture );
  6720. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  6721. }
  6722. clone() {
  6723. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  6724. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  6725. return viewportTextureNode;
  6726. }
  6727. }
  6728. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  6729. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  6730. let sharedDepthbuffer = null;
  6731. /**
  6732. * Represents the depth of the current viewport as a texture. This module
  6733. * can be used in combination with viewport texture to achieve effects
  6734. * that require depth evaluation.
  6735. *
  6736. * @augments ViewportTextureNode
  6737. */
  6738. class ViewportDepthTextureNode extends ViewportTextureNode {
  6739. static get type() {
  6740. return 'ViewportDepthTextureNode';
  6741. }
  6742. /**
  6743. * Constructs a new viewport shared texture node.
  6744. *
  6745. * @param {Node} [uvNode=screenUV] - The uv node.
  6746. * @param {Node?} [levelNode=null] - The level node.
  6747. */
  6748. constructor( uvNode = screenUV, levelNode = null ) {
  6749. if ( sharedDepthbuffer === null ) {
  6750. sharedDepthbuffer = new DepthTexture();
  6751. }
  6752. super( uvNode, levelNode, sharedDepthbuffer );
  6753. }
  6754. }
  6755. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  6756. /**
  6757. * This node offers a collection of features in context of the depth logic in the fragment shader.
  6758. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  6759. * fragment or for depth evaluation purposes.
  6760. *
  6761. * @augments Node
  6762. */
  6763. class ViewportDepthNode extends Node {
  6764. static get type() {
  6765. return 'ViewportDepthNode';
  6766. }
  6767. /**
  6768. * Constructs a new viewport depth node.
  6769. *
  6770. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  6771. * @param {Node?} [valueNode=null] - The value node.
  6772. */
  6773. constructor( scope, valueNode = null ) {
  6774. super( 'float' );
  6775. /**
  6776. * The node behaves differently depending on which scope is selected.
  6777. *
  6778. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  6779. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  6780. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  6781. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  6782. *
  6783. * @type {('depth'|'depthBase'|'linearDepth')}
  6784. */
  6785. this.scope = scope;
  6786. /**
  6787. * Can be used to define a custom depth value.
  6788. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  6789. *
  6790. * @type {Node}
  6791. * @default null
  6792. */
  6793. this.valueNode = valueNode;
  6794. /**
  6795. * This flag can be used for type testing.
  6796. *
  6797. * @type {Boolean}
  6798. * @readonly
  6799. * @default true
  6800. */
  6801. this.isViewportDepthNode = true;
  6802. }
  6803. generate( builder ) {
  6804. const { scope } = this;
  6805. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6806. return builder.getFragDepth();
  6807. }
  6808. return super.generate( builder );
  6809. }
  6810. setup( { camera } ) {
  6811. const { scope } = this;
  6812. const value = this.valueNode;
  6813. let node = null;
  6814. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6815. if ( value !== null ) {
  6816. node = depthBase().assign( value );
  6817. }
  6818. } else if ( scope === ViewportDepthNode.DEPTH ) {
  6819. if ( camera.isPerspectiveCamera ) {
  6820. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  6821. } else {
  6822. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6823. }
  6824. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  6825. if ( value !== null ) {
  6826. if ( camera.isPerspectiveCamera ) {
  6827. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  6828. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  6829. } else {
  6830. node = value;
  6831. }
  6832. } else {
  6833. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6834. }
  6835. }
  6836. return node;
  6837. }
  6838. }
  6839. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  6840. ViewportDepthNode.DEPTH = 'depth';
  6841. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  6842. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  6843. // -near maps to 0; -far maps to 1
  6844. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  6845. // maps orthographic depth in [ 0, 1 ] to viewZ
  6846. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  6847. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  6848. // -near maps to 0; -far maps to 1
  6849. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  6850. // maps perspective depth in [ 0, 1 ] to viewZ
  6851. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  6852. // -near maps to 0; -far maps to 1
  6853. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  6854. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  6855. // The final logarithmic depth formula used here is adapted from one described in an
  6856. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  6857. // which was an improvement upon an earlier formula one described in an
  6858. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  6859. // Ulrich's formula is the following:
  6860. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  6861. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  6862. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  6863. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  6864. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  6865. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  6866. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  6867. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  6868. // be used, and ultimately Ulrich's "near plane" version was chosen.
  6869. // Outerra eventually made another improvement to their original "C-constant" variant,
  6870. // but it still does not incorporate the camera near plane (for this version,
  6871. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  6872. // Here we make 4 changes to Ulrich's formula:
  6873. // 1. Clamp the camera near plane so we don't divide by 0.
  6874. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  6875. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  6876. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  6877. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  6878. // so we do the same here, hence the 'viewZ.negate()' call.
  6879. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  6880. near = near.max( 1e-6 ).toVar();
  6881. const numerator = log2( viewZ.negate().div( near ) );
  6882. const denominator = log2( far.div( near ) );
  6883. return numerator.div( denominator );
  6884. };
  6885. // maps logarithmic depth in [ 0, 1 ] to viewZ
  6886. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  6887. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  6888. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  6889. // a negative viewZ).
  6890. const exponent = depth.mul( log( far.div( near ) ) );
  6891. return float( Math.E ).pow( exponent ).mul( near ).negate();
  6892. };
  6893. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  6894. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  6895. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  6896. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  6897. depth.assign = ( value ) => depthBase( value );
  6898. class BuiltinNode extends Node {
  6899. constructor( name ) {
  6900. super( 'float' );
  6901. this.name = name;
  6902. this.isBuiltinNode = true;
  6903. }
  6904. generate( /* builder */ ) {
  6905. return this.name;
  6906. }
  6907. }
  6908. const builtin = nodeProxy( BuiltinNode );
  6909. class ClippingNode extends Node {
  6910. static get type() {
  6911. return 'ClippingNode';
  6912. }
  6913. constructor( scope = ClippingNode.DEFAULT ) {
  6914. super();
  6915. this.scope = scope;
  6916. }
  6917. setup( builder ) {
  6918. super.setup( builder );
  6919. const clippingContext = builder.clippingContext;
  6920. const { intersectionPlanes, unionPlanes } = clippingContext;
  6921. this.hardwareClipping = builder.material.hardwareClipping;
  6922. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  6923. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  6924. } else if ( this.scope === ClippingNode.HARDWARE ) {
  6925. return this.setupHardwareClipping( unionPlanes, builder );
  6926. } else {
  6927. return this.setupDefault( intersectionPlanes, unionPlanes );
  6928. }
  6929. }
  6930. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  6931. return Fn( () => {
  6932. const distanceToPlane = float().toVar( 'distanceToPlane' );
  6933. const distanceGradient = float().toVar( 'distanceToGradient' );
  6934. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  6935. const numUnionPlanes = unionPlanes.length;
  6936. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6937. const clippingPlanes = uniformArray( unionPlanes );
  6938. Loop( numUnionPlanes, ( { i } ) => {
  6939. const plane = clippingPlanes.element( i );
  6940. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6941. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6942. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  6943. } );
  6944. }
  6945. const numIntersectionPlanes = intersectionPlanes.length;
  6946. if ( numIntersectionPlanes > 0 ) {
  6947. const clippingPlanes = uniformArray( intersectionPlanes );
  6948. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  6949. Loop( numIntersectionPlanes, ( { i } ) => {
  6950. const plane = clippingPlanes.element( i );
  6951. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6952. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6953. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  6954. } );
  6955. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  6956. }
  6957. diffuseColor.a.mulAssign( clipOpacity );
  6958. diffuseColor.a.equal( 0.0 ).discard();
  6959. } )();
  6960. }
  6961. setupDefault( intersectionPlanes, unionPlanes ) {
  6962. return Fn( () => {
  6963. const numUnionPlanes = unionPlanes.length;
  6964. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6965. const clippingPlanes = uniformArray( unionPlanes );
  6966. Loop( numUnionPlanes, ( { i } ) => {
  6967. const plane = clippingPlanes.element( i );
  6968. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  6969. } );
  6970. }
  6971. const numIntersectionPlanes = intersectionPlanes.length;
  6972. if ( numIntersectionPlanes > 0 ) {
  6973. const clippingPlanes = uniformArray( intersectionPlanes );
  6974. const clipped = bool( true ).toVar( 'clipped' );
  6975. Loop( numIntersectionPlanes, ( { i } ) => {
  6976. const plane = clippingPlanes.element( i );
  6977. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  6978. } );
  6979. clipped.discard();
  6980. }
  6981. } )();
  6982. }
  6983. setupHardwareClipping( unionPlanes, builder ) {
  6984. const numUnionPlanes = unionPlanes.length;
  6985. builder.enableHardwareClipping( numUnionPlanes );
  6986. return Fn( () => {
  6987. const clippingPlanes = uniformArray( unionPlanes );
  6988. const hw_clip_distances = builtin( builder.getClipDistance() );
  6989. Loop( numUnionPlanes, ( { i } ) => {
  6990. const plane = clippingPlanes.element( i );
  6991. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  6992. hw_clip_distances.element( i ).assign( distance );
  6993. } );
  6994. } )();
  6995. }
  6996. }
  6997. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  6998. ClippingNode.DEFAULT = 'default';
  6999. ClippingNode.HARDWARE = 'hardware';
  7000. const clipping = () => nodeObject( new ClippingNode() );
  7001. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  7002. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  7003. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  7004. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  7005. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  7006. 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 ) ) ) ) ) );
  7007. } );
  7008. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  7009. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  7010. } );
  7011. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  7012. // Find the discretized derivatives of our coordinates
  7013. const maxDeriv = max$1(
  7014. length( dFdx( position.xyz ) ),
  7015. length( dFdy( position.xyz ) )
  7016. );
  7017. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  7018. // Find two nearest log-discretized noise scales
  7019. const pixScales = vec2(
  7020. exp2( floor( log2( pixScale ) ) ),
  7021. exp2( ceil( log2( pixScale ) ) )
  7022. );
  7023. // Compute alpha thresholds at our two noise scales
  7024. const alpha = vec2(
  7025. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  7026. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  7027. );
  7028. // Factor to interpolate lerp with
  7029. const lerpFactor = fract( log2( pixScale ) );
  7030. // Interpolate alpha threshold from noise at two scales
  7031. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  7032. // Pass into CDF to compute uniformly distrib threshold
  7033. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  7034. const cases = vec3(
  7035. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  7036. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  7037. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  7038. // Find our final, uniformly distributed alpha threshold (ατ)
  7039. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  7040. // Avoids ατ == 0. Could also do ατ =1-ατ
  7041. return clamp( threshold, 1.0e-6, 1.0 );
  7042. } ).setLayout( {
  7043. name: 'getAlphaHashThreshold',
  7044. type: 'float',
  7045. inputs: [
  7046. { name: 'position', type: 'vec3' }
  7047. ]
  7048. } );
  7049. class NodeMaterial extends Material {
  7050. static get type() {
  7051. return 'NodeMaterial';
  7052. }
  7053. get type() {
  7054. return this.constructor.type;
  7055. }
  7056. set type( _value ) { /* */ }
  7057. constructor() {
  7058. super();
  7059. this.isNodeMaterial = true;
  7060. this.forceSinglePass = false;
  7061. this.fog = true;
  7062. this.lights = false;
  7063. this.hardwareClipping = false;
  7064. this.lightsNode = null;
  7065. this.envNode = null;
  7066. this.aoNode = null;
  7067. this.colorNode = null;
  7068. this.normalNode = null;
  7069. this.opacityNode = null;
  7070. this.backdropNode = null;
  7071. this.backdropAlphaNode = null;
  7072. this.alphaTestNode = null;
  7073. this.positionNode = null;
  7074. this.geometryNode = null;
  7075. this.depthNode = null;
  7076. this.shadowPositionNode = null;
  7077. this.receivedShadowNode = null;
  7078. this.castShadowNode = null;
  7079. this.outputNode = null;
  7080. this.mrtNode = null;
  7081. this.fragmentNode = null;
  7082. this.vertexNode = null;
  7083. }
  7084. customProgramCacheKey() {
  7085. return this.type + getCacheKey$1( this );
  7086. }
  7087. build( builder ) {
  7088. this.setup( builder );
  7089. }
  7090. setupObserver( builder ) {
  7091. return new NodeMaterialObserver( builder );
  7092. }
  7093. setup( builder ) {
  7094. builder.context.setupNormal = () => this.setupNormal( builder );
  7095. const renderer = builder.renderer;
  7096. const renderTarget = renderer.getRenderTarget();
  7097. // < VERTEX STAGE >
  7098. builder.addStack();
  7099. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  7100. if ( this.geometryNode !== null ) {
  7101. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  7102. }
  7103. builder.addFlow( 'vertex', builder.removeStack() );
  7104. // < FRAGMENT STAGE >
  7105. builder.addStack();
  7106. let resultNode;
  7107. const clippingNode = this.setupClipping( builder );
  7108. if ( this.depthWrite === true ) {
  7109. // only write depth if depth buffer is configured
  7110. if ( renderTarget !== null ) {
  7111. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  7112. } else {
  7113. if ( renderer.depth === true ) this.setupDepth( builder );
  7114. }
  7115. }
  7116. if ( this.fragmentNode === null ) {
  7117. this.setupDiffuseColor( builder );
  7118. this.setupVariants( builder );
  7119. const outgoingLightNode = this.setupLighting( builder );
  7120. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  7121. // force unsigned floats - useful for RenderTargets
  7122. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  7123. resultNode = this.setupOutput( builder, basicOutput );
  7124. // OUTPUT NODE
  7125. output.assign( resultNode );
  7126. //
  7127. if ( this.outputNode !== null ) resultNode = this.outputNode;
  7128. // MRT
  7129. if ( renderTarget !== null ) {
  7130. const mrt = renderer.getMRT();
  7131. const materialMRT = this.mrtNode;
  7132. if ( mrt !== null ) {
  7133. resultNode = mrt;
  7134. if ( materialMRT !== null ) {
  7135. resultNode = mrt.merge( materialMRT );
  7136. }
  7137. } else if ( materialMRT !== null ) {
  7138. resultNode = materialMRT;
  7139. }
  7140. }
  7141. } else {
  7142. let fragmentNode = this.fragmentNode;
  7143. if ( fragmentNode.isOutputStructNode !== true ) {
  7144. fragmentNode = vec4( fragmentNode );
  7145. }
  7146. resultNode = this.setupOutput( builder, fragmentNode );
  7147. }
  7148. builder.stack.outputNode = resultNode;
  7149. builder.addFlow( 'fragment', builder.removeStack() );
  7150. // < MONITOR >
  7151. builder.monitor = this.setupObserver( builder );
  7152. }
  7153. setupClipping( builder ) {
  7154. if ( builder.clippingContext === null ) return null;
  7155. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  7156. let result = null;
  7157. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  7158. const samples = builder.renderer.samples;
  7159. if ( this.alphaToCoverage && samples > 1 ) {
  7160. // to be added to flow when the color/alpha value has been determined
  7161. result = clippingAlpha();
  7162. } else {
  7163. builder.stack.add( clipping() );
  7164. }
  7165. }
  7166. return result;
  7167. }
  7168. setupHardwareClipping( builder ) {
  7169. this.hardwareClipping = false;
  7170. if ( builder.clippingContext === null ) return;
  7171. const candidateCount = builder.clippingContext.unionPlanes.length;
  7172. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  7173. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  7174. builder.stack.add( hardwareClipping() );
  7175. this.hardwareClipping = true;
  7176. }
  7177. return;
  7178. }
  7179. setupDepth( builder ) {
  7180. const { renderer, camera } = builder;
  7181. // Depth
  7182. let depthNode = this.depthNode;
  7183. if ( depthNode === null ) {
  7184. const mrt = renderer.getMRT();
  7185. if ( mrt && mrt.has( 'depth' ) ) {
  7186. depthNode = mrt.get( 'depth' );
  7187. } else if ( renderer.logarithmicDepthBuffer === true ) {
  7188. if ( camera.isPerspectiveCamera ) {
  7189. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  7190. } else {
  7191. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  7192. }
  7193. }
  7194. }
  7195. if ( depthNode !== null ) {
  7196. depth.assign( depthNode ).append();
  7197. }
  7198. }
  7199. setupPosition( builder ) {
  7200. const { object } = builder;
  7201. const geometry = object.geometry;
  7202. builder.addStack();
  7203. // Vertex
  7204. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  7205. morphReference( object ).append();
  7206. }
  7207. if ( object.isSkinnedMesh === true ) {
  7208. skinningReference( object ).append();
  7209. }
  7210. if ( this.displacementMap ) {
  7211. const displacementMap = materialReference( 'displacementMap', 'texture' );
  7212. const displacementScale = materialReference( 'displacementScale', 'float' );
  7213. const displacementBias = materialReference( 'displacementBias', 'float' );
  7214. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  7215. }
  7216. if ( object.isBatchedMesh ) {
  7217. batch( object ).append();
  7218. }
  7219. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  7220. instancedMesh( object ).append();
  7221. }
  7222. if ( this.positionNode !== null ) {
  7223. positionLocal.assign( this.positionNode );
  7224. }
  7225. this.setupHardwareClipping( builder );
  7226. const mvp = modelViewProjection();
  7227. builder.context.vertex = builder.removeStack();
  7228. builder.context.mvp = mvp;
  7229. return mvp;
  7230. }
  7231. setupDiffuseColor( { object, geometry } ) {
  7232. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  7233. // VERTEX COLORS
  7234. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  7235. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  7236. }
  7237. // Instanced colors
  7238. if ( object.instanceColor ) {
  7239. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  7240. colorNode = instanceColor.mul( colorNode );
  7241. }
  7242. if ( object.isBatchedMesh && object._colorsTexture ) {
  7243. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  7244. colorNode = batchColor.mul( colorNode );
  7245. }
  7246. // COLOR
  7247. diffuseColor.assign( colorNode );
  7248. // OPACITY
  7249. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7250. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  7251. // ALPHA TEST
  7252. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  7253. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  7254. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  7255. }
  7256. // ALPHA HASH
  7257. if ( this.alphaHash === true ) {
  7258. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  7259. }
  7260. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  7261. diffuseColor.a.assign( 1.0 );
  7262. }
  7263. }
  7264. setupVariants( /*builder*/ ) {
  7265. // Interface function.
  7266. }
  7267. setupOutgoingLight() {
  7268. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  7269. }
  7270. setupNormal() {
  7271. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  7272. }
  7273. setupEnvironment( /*builder*/ ) {
  7274. let node = null;
  7275. if ( this.envNode ) {
  7276. node = this.envNode;
  7277. } else if ( this.envMap ) {
  7278. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  7279. }
  7280. return node;
  7281. }
  7282. setupLightMap( builder ) {
  7283. let node = null;
  7284. if ( builder.material.lightMap ) {
  7285. node = new IrradianceNode( materialLightMap );
  7286. }
  7287. return node;
  7288. }
  7289. setupLights( builder ) {
  7290. const materialLightsNode = [];
  7291. //
  7292. const envNode = this.setupEnvironment( builder );
  7293. if ( envNode && envNode.isLightingNode ) {
  7294. materialLightsNode.push( envNode );
  7295. }
  7296. const lightMapNode = this.setupLightMap( builder );
  7297. if ( lightMapNode && lightMapNode.isLightingNode ) {
  7298. materialLightsNode.push( lightMapNode );
  7299. }
  7300. if ( this.aoNode !== null || builder.material.aoMap ) {
  7301. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  7302. materialLightsNode.push( new AONode( aoNode ) );
  7303. }
  7304. let lightsN = this.lightsNode || builder.lightsNode;
  7305. if ( materialLightsNode.length > 0 ) {
  7306. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  7307. }
  7308. return lightsN;
  7309. }
  7310. setupLightingModel( /*builder*/ ) {
  7311. // Interface function.
  7312. }
  7313. setupLighting( builder ) {
  7314. const { material } = builder;
  7315. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  7316. // OUTGOING LIGHT
  7317. const lights = this.lights === true || this.lightsNode !== null;
  7318. const lightsNode = lights ? this.setupLights( builder ) : null;
  7319. let outgoingLightNode = this.setupOutgoingLight( builder );
  7320. if ( lightsNode && lightsNode.getScope().hasLights ) {
  7321. const lightingModel = this.setupLightingModel( builder );
  7322. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  7323. } else if ( backdropNode !== null ) {
  7324. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  7325. }
  7326. // EMISSIVE
  7327. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  7328. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  7329. outgoingLightNode = outgoingLightNode.add( emissive );
  7330. }
  7331. return outgoingLightNode;
  7332. }
  7333. setupOutput( builder, outputNode ) {
  7334. // FOG
  7335. if ( this.fog === true ) {
  7336. const fogNode = builder.fogNode;
  7337. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  7338. }
  7339. return outputNode;
  7340. }
  7341. setDefaultValues( material ) {
  7342. // This approach is to reuse the native refreshUniforms*
  7343. // and turn available the use of features like transmission and environment in core
  7344. for ( const property in material ) {
  7345. const value = material[ property ];
  7346. if ( this[ property ] === undefined ) {
  7347. this[ property ] = value;
  7348. if ( value && value.clone ) this[ property ] = value.clone();
  7349. }
  7350. }
  7351. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  7352. for ( const key in descriptors ) {
  7353. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  7354. descriptors[ key ].get !== undefined ) {
  7355. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  7356. }
  7357. }
  7358. }
  7359. toJSON( meta ) {
  7360. const isRoot = ( meta === undefined || typeof meta === 'string' );
  7361. if ( isRoot ) {
  7362. meta = {
  7363. textures: {},
  7364. images: {},
  7365. nodes: {}
  7366. };
  7367. }
  7368. const data = Material.prototype.toJSON.call( this, meta );
  7369. const nodeChildren = getNodeChildren( this );
  7370. data.inputNodes = {};
  7371. for ( const { property, childNode } of nodeChildren ) {
  7372. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  7373. }
  7374. // TODO: Copied from Object3D.toJSON
  7375. function extractFromCache( cache ) {
  7376. const values = [];
  7377. for ( const key in cache ) {
  7378. const data = cache[ key ];
  7379. delete data.metadata;
  7380. values.push( data );
  7381. }
  7382. return values;
  7383. }
  7384. if ( isRoot ) {
  7385. const textures = extractFromCache( meta.textures );
  7386. const images = extractFromCache( meta.images );
  7387. const nodes = extractFromCache( meta.nodes );
  7388. if ( textures.length > 0 ) data.textures = textures;
  7389. if ( images.length > 0 ) data.images = images;
  7390. if ( nodes.length > 0 ) data.nodes = nodes;
  7391. }
  7392. return data;
  7393. }
  7394. copy( source ) {
  7395. this.lightsNode = source.lightsNode;
  7396. this.envNode = source.envNode;
  7397. this.colorNode = source.colorNode;
  7398. this.normalNode = source.normalNode;
  7399. this.opacityNode = source.opacityNode;
  7400. this.backdropNode = source.backdropNode;
  7401. this.backdropAlphaNode = source.backdropAlphaNode;
  7402. this.alphaTestNode = source.alphaTestNode;
  7403. this.positionNode = source.positionNode;
  7404. this.geometryNode = source.geometryNode;
  7405. this.depthNode = source.depthNode;
  7406. this.shadowPositionNode = source.shadowPositionNode;
  7407. this.receivedShadowNode = source.receivedShadowNode;
  7408. this.castShadowNode = source.castShadowNode;
  7409. this.outputNode = source.outputNode;
  7410. this.mrtNode = source.mrtNode;
  7411. this.fragmentNode = source.fragmentNode;
  7412. this.vertexNode = source.vertexNode;
  7413. return super.copy( source );
  7414. }
  7415. }
  7416. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  7417. class InstancedPointsNodeMaterial extends NodeMaterial {
  7418. static get type() {
  7419. return 'InstancedPointsNodeMaterial';
  7420. }
  7421. constructor( params = {} ) {
  7422. super();
  7423. this.lights = false;
  7424. this.useAlphaToCoverage = true;
  7425. this.useColor = params.vertexColors;
  7426. this.pointWidth = 1;
  7427. this.pointColorNode = null;
  7428. this.pointWidthNode = null;
  7429. this.setDefaultValues( _defaultValues$e );
  7430. this.setValues( params );
  7431. }
  7432. setup( builder ) {
  7433. this.setupShaders( builder );
  7434. super.setup( builder );
  7435. }
  7436. setupShaders( { renderer } ) {
  7437. const useAlphaToCoverage = this.alphaToCoverage;
  7438. const useColor = this.useColor;
  7439. this.vertexNode = Fn( () => {
  7440. const instancePosition = attribute( 'instancePosition' ).xyz;
  7441. // camera space
  7442. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  7443. const aspect = viewport.z.div( viewport.w );
  7444. // clip space
  7445. const clipPos = cameraProjectionMatrix.mul( mvPos );
  7446. // offset in ndc space
  7447. const offset = positionGeometry.xy.toVar();
  7448. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  7449. offset.assign( offset.div( viewport.z ) );
  7450. offset.y.assign( offset.y.mul( aspect ) );
  7451. // back to clip space
  7452. offset.assign( offset.mul( clipPos.w ) );
  7453. //clipPos.xy += offset;
  7454. clipPos.addAssign( vec4( offset, 0, 0 ) );
  7455. return clipPos;
  7456. } )();
  7457. this.fragmentNode = Fn( () => {
  7458. const alpha = float( 1 ).toVar();
  7459. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  7460. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7461. const dlen = float( len2.fwidth() ).toVar();
  7462. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7463. } else {
  7464. len2.greaterThan( 1.0 ).discard();
  7465. }
  7466. let pointColorNode;
  7467. if ( this.pointColorNode ) {
  7468. pointColorNode = this.pointColorNode;
  7469. } else {
  7470. if ( useColor ) {
  7471. const instanceColor = attribute( 'instanceColor' );
  7472. pointColorNode = instanceColor.mul( materialColor );
  7473. } else {
  7474. pointColorNode = materialColor;
  7475. }
  7476. }
  7477. alpha.mulAssign( materialOpacity );
  7478. return vec4( pointColorNode, alpha );
  7479. } )();
  7480. }
  7481. get alphaToCoverage() {
  7482. return this.useAlphaToCoverage;
  7483. }
  7484. set alphaToCoverage( value ) {
  7485. if ( this.useAlphaToCoverage !== value ) {
  7486. this.useAlphaToCoverage = value;
  7487. this.needsUpdate = true;
  7488. }
  7489. }
  7490. }
  7491. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  7492. class LineBasicNodeMaterial extends NodeMaterial {
  7493. static get type() {
  7494. return 'LineBasicNodeMaterial';
  7495. }
  7496. constructor( parameters ) {
  7497. super();
  7498. this.isLineBasicNodeMaterial = true;
  7499. this.lights = false;
  7500. this.setDefaultValues( _defaultValues$d );
  7501. this.setValues( parameters );
  7502. }
  7503. }
  7504. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  7505. class LineDashedNodeMaterial extends NodeMaterial {
  7506. static get type() {
  7507. return 'LineDashedNodeMaterial';
  7508. }
  7509. constructor( parameters ) {
  7510. super();
  7511. this.isLineDashedNodeMaterial = true;
  7512. this.lights = false;
  7513. this.setDefaultValues( _defaultValues$c );
  7514. this.dashOffset = 0;
  7515. this.offsetNode = null;
  7516. this.dashScaleNode = null;
  7517. this.dashSizeNode = null;
  7518. this.gapSizeNode = null;
  7519. this.setValues( parameters );
  7520. }
  7521. setupVariants() {
  7522. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7523. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7524. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7525. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7526. dashSize.assign( dashSizeNode );
  7527. gapSize.assign( gapSizeNode );
  7528. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  7529. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  7530. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  7531. }
  7532. }
  7533. let _sharedFramebuffer = null;
  7534. /**
  7535. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  7536. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  7537. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  7538. *
  7539. * @augments ViewportTextureNode
  7540. */
  7541. class ViewportSharedTextureNode extends ViewportTextureNode {
  7542. static get type() {
  7543. return 'ViewportSharedTextureNode';
  7544. }
  7545. /**
  7546. * Constructs a new viewport shared texture node.
  7547. *
  7548. * @param {Node} [uvNode=screenUV] - The uv node.
  7549. * @param {Node?} [levelNode=null] - The level node.
  7550. */
  7551. constructor( uvNode = screenUV, levelNode = null ) {
  7552. if ( _sharedFramebuffer === null ) {
  7553. _sharedFramebuffer = new FramebufferTexture();
  7554. }
  7555. super( uvNode, levelNode, _sharedFramebuffer );
  7556. }
  7557. updateReference() {
  7558. return this;
  7559. }
  7560. }
  7561. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  7562. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  7563. class Line2NodeMaterial extends NodeMaterial {
  7564. static get type() {
  7565. return 'Line2NodeMaterial';
  7566. }
  7567. constructor( params = {} ) {
  7568. super();
  7569. this.lights = false;
  7570. this.setDefaultValues( _defaultValues$b );
  7571. this.useAlphaToCoverage = true;
  7572. this.useColor = params.vertexColors;
  7573. this.useDash = params.dashed;
  7574. this.useWorldUnits = false;
  7575. this.dashOffset = 0;
  7576. this.lineWidth = 1;
  7577. this.lineColorNode = null;
  7578. this.offsetNode = null;
  7579. this.dashScaleNode = null;
  7580. this.dashSizeNode = null;
  7581. this.gapSizeNode = null;
  7582. this.blending = NoBlending;
  7583. this.setValues( params );
  7584. }
  7585. setup( builder ) {
  7586. this.setupShaders( builder );
  7587. super.setup( builder );
  7588. }
  7589. setupShaders( { renderer } ) {
  7590. const useAlphaToCoverage = this.alphaToCoverage;
  7591. const useColor = this.useColor;
  7592. const useDash = this.dashed;
  7593. const useWorldUnits = this.worldUnits;
  7594. const trimSegment = Fn( ( { start, end } ) => {
  7595. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  7596. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  7597. const nearEstimate = b.mul( - 0.5 ).div( a );
  7598. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  7599. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  7600. } ).setLayout( {
  7601. name: 'trimSegment',
  7602. type: 'vec4',
  7603. inputs: [
  7604. { name: 'start', type: 'vec4' },
  7605. { name: 'end', type: 'vec4' }
  7606. ]
  7607. } );
  7608. this.vertexNode = Fn( () => {
  7609. const instanceStart = attribute( 'instanceStart' );
  7610. const instanceEnd = attribute( 'instanceEnd' );
  7611. // camera space
  7612. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  7613. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  7614. if ( useDash ) {
  7615. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7616. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7617. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  7618. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  7619. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  7620. lineDistance = lineDistance.add( offsetNode );
  7621. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  7622. }
  7623. if ( useWorldUnits ) {
  7624. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  7625. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  7626. }
  7627. const aspect = viewport.z.div( viewport.w );
  7628. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7629. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7630. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7631. // perhaps there is a more elegant solution -- WestLangley
  7632. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  7633. If( perspective, () => {
  7634. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  7635. end.assign( trimSegment( { start: start, end: end } ) );
  7636. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  7637. start.assign( trimSegment( { start: end, end: start } ) );
  7638. } );
  7639. } );
  7640. // clip space
  7641. const clipStart = cameraProjectionMatrix.mul( start );
  7642. const clipEnd = cameraProjectionMatrix.mul( end );
  7643. // ndc space
  7644. const ndcStart = clipStart.xyz.div( clipStart.w );
  7645. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  7646. // direction
  7647. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  7648. // account for clip-space aspect ratio
  7649. dir.x.assign( dir.x.mul( aspect ) );
  7650. dir.assign( dir.normalize() );
  7651. const clip = vec4().toVar();
  7652. if ( useWorldUnits ) {
  7653. // get the offset direction as perpendicular to the view vector
  7654. const worldDir = end.xyz.sub( start.xyz ).normalize();
  7655. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  7656. const worldUp = worldDir.cross( tmpFwd ).normalize();
  7657. const worldFwd = worldDir.cross( worldUp );
  7658. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  7659. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  7660. // height offset
  7661. const hw = materialLineWidth.mul( 0.5 );
  7662. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  7663. // don't extend the line if we're rendering dashes because we
  7664. // won't be rendering the endcaps
  7665. if ( ! useDash ) {
  7666. // cap extension
  7667. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  7668. // add width to the box
  7669. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  7670. // endcaps
  7671. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  7672. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  7673. } );
  7674. }
  7675. // project the worldpos
  7676. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  7677. // shift the depth of the projected points so the line
  7678. // segments overlap neatly
  7679. const clipPose = vec3().toVar();
  7680. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  7681. clip.z.assign( clipPose.z.mul( clip.w ) );
  7682. } else {
  7683. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  7684. // undo aspect ratio adjustment
  7685. dir.x.assign( dir.x.div( aspect ) );
  7686. offset.x.assign( offset.x.div( aspect ) );
  7687. // sign flip
  7688. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  7689. // endcaps
  7690. If( positionGeometry.y.lessThan( 0.0 ), () => {
  7691. offset.assign( offset.sub( dir ) );
  7692. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  7693. offset.assign( offset.add( dir ) );
  7694. } );
  7695. // adjust for linewidth
  7696. offset.assign( offset.mul( materialLineWidth ) );
  7697. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7698. offset.assign( offset.div( viewport.w ) );
  7699. // select end
  7700. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  7701. // back to clip space
  7702. offset.assign( offset.mul( clip.w ) );
  7703. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  7704. }
  7705. return clip;
  7706. } )();
  7707. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  7708. const p13 = p1.sub( p3 );
  7709. const p43 = p4.sub( p3 );
  7710. const p21 = p2.sub( p1 );
  7711. const d1343 = p13.dot( p43 );
  7712. const d4321 = p43.dot( p21 );
  7713. const d1321 = p13.dot( p21 );
  7714. const d4343 = p43.dot( p43 );
  7715. const d2121 = p21.dot( p21 );
  7716. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  7717. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  7718. const mua = numer.div( denom ).clamp();
  7719. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  7720. return vec2( mua, mub );
  7721. } );
  7722. this.colorNode = Fn( () => {
  7723. const vUv = uv();
  7724. if ( useDash ) {
  7725. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7726. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7727. dashSize.assign( dashSizeNode );
  7728. gapSize.assign( gapSizeNode );
  7729. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  7730. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  7731. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  7732. }
  7733. const alpha = float( 1 ).toVar( 'alpha' );
  7734. if ( useWorldUnits ) {
  7735. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  7736. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  7737. // Find the closest points on the view ray and the line segment
  7738. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  7739. const lineDir = worldEnd.sub( worldStart );
  7740. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  7741. const p1 = worldStart.add( lineDir.mul( params.x ) );
  7742. const p2 = rayEnd.mul( params.y );
  7743. const delta = p1.sub( p2 );
  7744. const len = delta.length();
  7745. const norm = len.div( materialLineWidth );
  7746. if ( ! useDash ) {
  7747. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7748. const dnorm = norm.fwidth();
  7749. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  7750. } else {
  7751. norm.greaterThan( 0.5 ).discard();
  7752. }
  7753. }
  7754. } else {
  7755. // round endcaps
  7756. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7757. const a = vUv.x;
  7758. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7759. const len2 = a.mul( a ).add( b.mul( b ) );
  7760. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  7761. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7762. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7763. } );
  7764. } else {
  7765. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7766. const a = vUv.x;
  7767. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7768. const len2 = a.mul( a ).add( b.mul( b ) );
  7769. len2.greaterThan( 1.0 ).discard();
  7770. } );
  7771. }
  7772. }
  7773. let lineColorNode;
  7774. if ( this.lineColorNode ) {
  7775. lineColorNode = this.lineColorNode;
  7776. } else {
  7777. if ( useColor ) {
  7778. const instanceColorStart = attribute( 'instanceColorStart' );
  7779. const instanceColorEnd = attribute( 'instanceColorEnd' );
  7780. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  7781. lineColorNode = instanceColor.mul( materialColor );
  7782. } else {
  7783. lineColorNode = materialColor;
  7784. }
  7785. }
  7786. return vec4( lineColorNode, alpha );
  7787. } )();
  7788. if ( this.transparent ) {
  7789. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7790. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  7791. }
  7792. }
  7793. get worldUnits() {
  7794. return this.useWorldUnits;
  7795. }
  7796. set worldUnits( value ) {
  7797. if ( this.useWorldUnits !== value ) {
  7798. this.useWorldUnits = value;
  7799. this.needsUpdate = true;
  7800. }
  7801. }
  7802. get dashed() {
  7803. return this.useDash;
  7804. }
  7805. set dashed( value ) {
  7806. if ( this.useDash !== value ) {
  7807. this.useDash = value;
  7808. this.needsUpdate = true;
  7809. }
  7810. }
  7811. get alphaToCoverage() {
  7812. return this.useAlphaToCoverage;
  7813. }
  7814. set alphaToCoverage( value ) {
  7815. if ( this.useAlphaToCoverage !== value ) {
  7816. this.useAlphaToCoverage = value;
  7817. this.needsUpdate = true;
  7818. }
  7819. }
  7820. }
  7821. /** @module Packing **/
  7822. /**
  7823. * Packs a direction vector into a color value.
  7824. *
  7825. * @method
  7826. * @param {Node<vec3>} node - The direction to pack.
  7827. * @return {Node<vec3>} The color.
  7828. */
  7829. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  7830. /**
  7831. * Unpacks a color value into a direction vector.
  7832. *
  7833. * @method
  7834. * @param {Node<vec3>} node - The color to unpack.
  7835. * @return {Node<vec3>} The direction.
  7836. */
  7837. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  7838. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  7839. class MeshNormalNodeMaterial extends NodeMaterial {
  7840. static get type() {
  7841. return 'MeshNormalNodeMaterial';
  7842. }
  7843. constructor( parameters ) {
  7844. super();
  7845. this.lights = false;
  7846. this.isMeshNormalNodeMaterial = true;
  7847. this.setDefaultValues( _defaultValues$a );
  7848. this.setValues( parameters );
  7849. }
  7850. setupDiffuseColor() {
  7851. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7852. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  7853. }
  7854. }
  7855. /**
  7856. * Can be used to compute texture coordinates for projecting an
  7857. * equirectangular texture onto a mesh for using it as the scene's
  7858. * background.
  7859. *
  7860. * ```js
  7861. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  7862. * ```
  7863. *
  7864. * @augments TempNode
  7865. */
  7866. class EquirectUVNode extends TempNode {
  7867. static get type() {
  7868. return 'EquirectUVNode';
  7869. }
  7870. /**
  7871. * Constructs a new equirect uv node.
  7872. *
  7873. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling why is by default `positionWorldDirection`.
  7874. */
  7875. constructor( dirNode = positionWorldDirection ) {
  7876. super( 'vec2' );
  7877. /**
  7878. * A direction vector for sampling why is by default `positionWorldDirection`.
  7879. *
  7880. * @type {Node<vec3>}
  7881. */
  7882. this.dirNode = dirNode;
  7883. }
  7884. setup() {
  7885. const dir = this.dirNode;
  7886. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  7887. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  7888. return vec2( u, v );
  7889. }
  7890. }
  7891. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  7892. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  7893. class CubeRenderTarget extends WebGLCubeRenderTarget {
  7894. constructor( size = 1, options = {} ) {
  7895. super( size, options );
  7896. this.isCubeRenderTarget = true;
  7897. }
  7898. fromEquirectangularTexture( renderer, texture$1 ) {
  7899. const currentMinFilter = texture$1.minFilter;
  7900. const currentGenerateMipmaps = texture$1.generateMipmaps;
  7901. texture$1.generateMipmaps = true;
  7902. this.texture.type = texture$1.type;
  7903. this.texture.colorSpace = texture$1.colorSpace;
  7904. this.texture.generateMipmaps = texture$1.generateMipmaps;
  7905. this.texture.minFilter = texture$1.minFilter;
  7906. this.texture.magFilter = texture$1.magFilter;
  7907. const geometry = new BoxGeometry( 5, 5, 5 );
  7908. const uvNode = equirectUV( positionWorldDirection );
  7909. const material = new NodeMaterial();
  7910. material.colorNode = texture( texture$1, uvNode, 0 );
  7911. material.side = BackSide;
  7912. material.blending = NoBlending;
  7913. const mesh = new Mesh( geometry, material );
  7914. const scene = new Scene();
  7915. scene.add( mesh );
  7916. // Avoid blurred poles
  7917. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  7918. const camera = new CubeCamera( 1, 10, this );
  7919. const currentMRT = renderer.getMRT();
  7920. renderer.setMRT( null );
  7921. camera.update( renderer, scene );
  7922. renderer.setMRT( currentMRT );
  7923. texture$1.minFilter = currentMinFilter;
  7924. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  7925. mesh.geometry.dispose();
  7926. mesh.material.dispose();
  7927. return this;
  7928. }
  7929. }
  7930. const _cache$1 = new WeakMap();
  7931. /**
  7932. * This node can be used to automatically convert environment maps in the
  7933. * equirectangular format into the cube map format.
  7934. *
  7935. * @augments TempNode
  7936. */
  7937. class CubeMapNode extends TempNode {
  7938. static get type() {
  7939. return 'CubeMapNode';
  7940. }
  7941. /**
  7942. * Constructs a new cube map node.
  7943. *
  7944. * @param {Node} envNode - The node representing the environment map.
  7945. */
  7946. constructor( envNode ) {
  7947. super( 'vec3' );
  7948. /**
  7949. * The node representing the environment map.
  7950. *
  7951. * @type {Node}
  7952. */
  7953. this.envNode = envNode;
  7954. /**
  7955. * A reference to the internal cube texture.
  7956. *
  7957. * @private
  7958. * @type {CubeTexture}
  7959. * @default null
  7960. */
  7961. this._cubeTexture = null;
  7962. /**
  7963. * A reference to the internal cube texture node.
  7964. *
  7965. * @private
  7966. * @type {CubeTextureNode}
  7967. */
  7968. this._cubeTextureNode = cubeTexture();
  7969. const defaultTexture = new CubeTexture();
  7970. defaultTexture.isRenderTargetTexture = true;
  7971. /**
  7972. * A default cube texture that acts as a placeholder.
  7973. * It is used when the conversion from equirectangular to cube
  7974. * map has not finished yet for a given texture.
  7975. *
  7976. * @private
  7977. * @type {CubeTexture}
  7978. */
  7979. this._defaultTexture = defaultTexture;
  7980. /**
  7981. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  7982. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  7983. *
  7984. * @type {String}
  7985. * @default 'render'
  7986. */
  7987. this.updateBeforeType = NodeUpdateType.RENDER;
  7988. }
  7989. updateBefore( frame ) {
  7990. const { renderer, material } = frame;
  7991. const envNode = this.envNode;
  7992. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7993. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7994. if ( texture && texture.isTexture ) {
  7995. const mapping = texture.mapping;
  7996. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  7997. // check for converted cubemap map
  7998. if ( _cache$1.has( texture ) ) {
  7999. const cubeMap = _cache$1.get( texture );
  8000. mapTextureMapping( cubeMap, texture.mapping );
  8001. this._cubeTexture = cubeMap;
  8002. } else {
  8003. // create cube map from equirectangular map
  8004. const image = texture.image;
  8005. if ( isEquirectangularMapReady$1( image ) ) {
  8006. const renderTarget = new CubeRenderTarget( image.height );
  8007. renderTarget.fromEquirectangularTexture( renderer, texture );
  8008. mapTextureMapping( renderTarget.texture, texture.mapping );
  8009. this._cubeTexture = renderTarget.texture;
  8010. _cache$1.set( texture, renderTarget.texture );
  8011. texture.addEventListener( 'dispose', onTextureDispose );
  8012. } else {
  8013. // default cube texture as fallback when equirectangular texture is not yet loaded
  8014. this._cubeTexture = this._defaultTexture;
  8015. }
  8016. }
  8017. //
  8018. this._cubeTextureNode.value = this._cubeTexture;
  8019. } else {
  8020. // envNode already refers to a cube map
  8021. this._cubeTextureNode = this.envNode;
  8022. }
  8023. }
  8024. }
  8025. }
  8026. setup( builder ) {
  8027. this.updateBefore( builder );
  8028. return this._cubeTextureNode;
  8029. }
  8030. }
  8031. /**
  8032. * Returns true if the given equirectangular image has been fully loaded
  8033. * and is ready for further processing.
  8034. *
  8035. * @private
  8036. * @param {Image} image - The equirectangular image to check.
  8037. * @return {Boolean} Whether the image is ready or not.
  8038. */
  8039. function isEquirectangularMapReady$1( image ) {
  8040. if ( image === null || image === undefined ) return false;
  8041. return image.height > 0;
  8042. }
  8043. /**
  8044. * This function is executed when `dispose()` is called on the equirectangular
  8045. * texture. In this case, the generated cube map with its render target
  8046. * is deleted as well.
  8047. *
  8048. * @private
  8049. * @param {Object} event - The event object.
  8050. */
  8051. function onTextureDispose( event ) {
  8052. const texture = event.target;
  8053. texture.removeEventListener( 'dispose', onTextureDispose );
  8054. const renderTarget = _cache$1.get( texture );
  8055. if ( renderTarget !== undefined ) {
  8056. _cache$1.delete( texture );
  8057. renderTarget.dispose();
  8058. }
  8059. }
  8060. /**
  8061. * This function makes sure the generated cube map uses the correct
  8062. * texture mapping that corresponds to the equirectangular original.
  8063. *
  8064. * @private
  8065. * @param {Texture} texture - The cube texture.
  8066. * @param {Number} mapping - The original texture mapping.
  8067. */
  8068. function mapTextureMapping( texture, mapping ) {
  8069. if ( mapping === EquirectangularReflectionMapping ) {
  8070. texture.mapping = CubeReflectionMapping;
  8071. } else if ( mapping === EquirectangularRefractionMapping ) {
  8072. texture.mapping = CubeRefractionMapping;
  8073. }
  8074. }
  8075. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  8076. /**
  8077. * Represents a basic model for Image-based lighting (IBL). The environment
  8078. * is defined via environment maps in the equirectanular or cube map format.
  8079. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  8080. * or {@link MeshPhongNodeMaterial}.
  8081. *
  8082. * @augments LightingNode
  8083. */
  8084. class BasicEnvironmentNode extends LightingNode {
  8085. static get type() {
  8086. return 'BasicEnvironmentNode';
  8087. }
  8088. /**
  8089. * Constructs a new basic environment node.
  8090. *
  8091. * @param {Node} [envNode=null] - A node representing the environment.
  8092. */
  8093. constructor( envNode = null ) {
  8094. super();
  8095. /**
  8096. * A node representing the environment.
  8097. *
  8098. * @type {Node}
  8099. * @default null
  8100. */
  8101. this.envNode = envNode;
  8102. }
  8103. setup( builder ) {
  8104. // environment property is used in the finish() method of BasicLightingModel
  8105. builder.context.environment = cubeMapNode( this.envNode );
  8106. }
  8107. }
  8108. /**
  8109. * A specific version of {@link IrradianceNode} that is only relevant
  8110. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  8111. * requires a special scaling factor for the light map.
  8112. *
  8113. * @augments LightingNode
  8114. */
  8115. class BasicLightMapNode extends LightingNode {
  8116. static get type() {
  8117. return 'BasicLightMapNode';
  8118. }
  8119. /**
  8120. * Constructs a new basic light map node.
  8121. *
  8122. * @param {Node<vec3>} lightMapNode - The light map node.
  8123. */
  8124. constructor( lightMapNode = null ) {
  8125. super();
  8126. /**
  8127. * The light map node.
  8128. *
  8129. * @type {Node<vec3>}
  8130. */
  8131. this.lightMapNode = lightMapNode;
  8132. }
  8133. setup( builder ) {
  8134. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  8135. const RECIPROCAL_PI = float( 1 / Math.PI );
  8136. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  8137. }
  8138. }
  8139. /**
  8140. * Abstract class for implementing lighting models. The module defines
  8141. * multiple methods that concrete lighting models can implement. These
  8142. * methods are executed at different points during the light evaluation
  8143. * process.
  8144. */
  8145. class LightingModel {
  8146. /**
  8147. * This method is intended for setting up lighting model and context data
  8148. * which are later used in the evaluation process.
  8149. *
  8150. * @abstract
  8151. * @param {ContextNode} input - The current node context.
  8152. * @param {StackNode} stack - The current stack.
  8153. * @param {NodeBuilder} builder - The current node builder.
  8154. */
  8155. start( /*input, stack, builder*/ ) { }
  8156. /**
  8157. * This method is intended for executing final tasks like final updates
  8158. * to the outgoing light.
  8159. *
  8160. * @abstract
  8161. * @param {ContextNode} input - The current node context.
  8162. * @param {StackNode} stack - The current stack.
  8163. * @param {NodeBuilder} builder - The current node builder.
  8164. */
  8165. finish( /*input, stack, builder*/ ) { }
  8166. /**
  8167. * This method is intended for implementing the direct light term and
  8168. * executed during the build process of directional, point and spot light nodes.
  8169. *
  8170. * @abstract
  8171. * @param {Object} input - The input data.
  8172. * @param {StackNode} stack - The current stack.
  8173. * @param {NodeBuilder} builder - The current node builder.
  8174. */
  8175. direct( /*input, stack, builder*/ ) { }
  8176. /**
  8177. * This method is intended for implementing the direct light term for
  8178. * rect area light nodes.
  8179. *
  8180. * @abstract
  8181. * @param {Object} input - The input data.
  8182. * @param {StackNode} stack - The current stack.
  8183. * @param {NodeBuilder} builder - The current node builder.
  8184. */
  8185. directRectArea( /*input, stack, builder*/ ) {}
  8186. /**
  8187. * This method is intended for implementing the indirect light term.
  8188. *
  8189. * @abstract
  8190. * @param {ContextNode} input - The current node context.
  8191. * @param {StackNode} stack - The current stack.
  8192. * @param {NodeBuilder} builder - The current node builder.
  8193. */
  8194. indirect( /*input, stack, builder*/ ) { }
  8195. /**
  8196. * This method is intended for implementing the ambient occlusion term.
  8197. * Unlike other methods, this method must be called manually by the lighting
  8198. * model in its indirect term.
  8199. *
  8200. * @abstract
  8201. * @param {ContextNode} input - The current node context.
  8202. * @param {StackNode} stack - The current stack.
  8203. * @param {NodeBuilder} builder - The current node builder.
  8204. */
  8205. ambientOcclusion( /*input, stack, builder*/ ) { }
  8206. }
  8207. /**
  8208. * Represents the lighting model for unlit materials. The only light contribution
  8209. * is baked indirect lighting modulated with ambient occlusion and the material's
  8210. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  8211. *
  8212. * @augments LightingModel
  8213. */
  8214. class BasicLightingModel extends LightingModel {
  8215. /**
  8216. * Constructs a new basic lighting model.
  8217. */
  8218. constructor() {
  8219. super();
  8220. }
  8221. /**
  8222. * Implements the baked indirect lighting with its modulation.
  8223. *
  8224. * @param {ContextNode} context - The current node context.
  8225. * @param {StackNode} stack - The current stack.
  8226. * @param {NodeBuilder} builder - The current node builder.
  8227. */
  8228. indirect( context, stack, builder ) {
  8229. const ambientOcclusion = context.ambientOcclusion;
  8230. const reflectedLight = context.reflectedLight;
  8231. const irradianceLightMap = builder.context.irradianceLightMap;
  8232. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  8233. // accumulation (baked indirect lighting only)
  8234. if ( irradianceLightMap ) {
  8235. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  8236. } else {
  8237. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  8238. }
  8239. // modulation
  8240. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8241. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  8242. }
  8243. /**
  8244. * Implements the environment mapping.
  8245. *
  8246. * @param {ContextNode} context - The current node context.
  8247. * @param {StackNode} stack - The current stack.
  8248. * @param {NodeBuilder} builder - The current node builder.
  8249. */
  8250. finish( context, stack, builder ) {
  8251. const material = builder.material;
  8252. const outgoingLight = context.outgoingLight;
  8253. const envNode = builder.context.environment;
  8254. if ( envNode ) {
  8255. switch ( material.combine ) {
  8256. case MultiplyOperation:
  8257. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  8258. break;
  8259. case MixOperation:
  8260. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  8261. break;
  8262. case AddOperation:
  8263. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  8264. break;
  8265. default:
  8266. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  8267. break;
  8268. }
  8269. }
  8270. }
  8271. }
  8272. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  8273. class MeshBasicNodeMaterial extends NodeMaterial {
  8274. static get type() {
  8275. return 'MeshBasicNodeMaterial';
  8276. }
  8277. constructor( parameters ) {
  8278. super();
  8279. this.isMeshBasicNodeMaterial = true;
  8280. this.lights = true;
  8281. this.setDefaultValues( _defaultValues$9 );
  8282. this.setValues( parameters );
  8283. }
  8284. setupNormal() {
  8285. return normalView; // see #28839
  8286. }
  8287. setupEnvironment( builder ) {
  8288. const envNode = super.setupEnvironment( builder );
  8289. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8290. }
  8291. setupLightMap( builder ) {
  8292. let node = null;
  8293. if ( builder.material.lightMap ) {
  8294. node = new BasicLightMapNode( materialLightMap );
  8295. }
  8296. return node;
  8297. }
  8298. setupOutgoingLight() {
  8299. return diffuseColor.rgb;
  8300. }
  8301. setupLightingModel() {
  8302. return new BasicLightingModel();
  8303. }
  8304. }
  8305. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  8306. // Original approximation by Christophe Schlick '94
  8307. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  8308. // Optimized variant (presented by Epic at SIGGRAPH '13)
  8309. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  8310. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  8311. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  8312. } ); // validated
  8313. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  8314. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  8315. } ); // validated
  8316. const G_BlinnPhong_Implicit = () => float( 0.25 );
  8317. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  8318. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  8319. } );
  8320. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8321. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8322. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8323. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8324. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  8325. const G = G_BlinnPhong_Implicit();
  8326. const D = D_BlinnPhong( { dotNH } );
  8327. return F.mul( G ).mul( D );
  8328. } );
  8329. /**
  8330. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  8331. *
  8332. * @augments LightingModel
  8333. */
  8334. class PhongLightingModel extends BasicLightingModel {
  8335. /**
  8336. * Constructs a new phong lighting model.
  8337. *
  8338. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  8339. */
  8340. constructor( specular = true ) {
  8341. super();
  8342. /**
  8343. * Whether specular is supported or not. Set this to `false` if you are
  8344. * lookking for a Lambert-like material meaning a material for non-shiny
  8345. * surfaces, without specular highlights.
  8346. *
  8347. * @type {Boolean}
  8348. * @default true
  8349. */
  8350. this.specular = specular;
  8351. }
  8352. /**
  8353. * Implements the direct lighting. The specular portion is optional an can be controlled
  8354. * with the {@link PhongLightingModel#specular} flag.
  8355. *
  8356. * @param {Object} input - The input data.
  8357. * @param {StackNode} stack - The current stack.
  8358. * @param {NodeBuilder} builder - The current node builder.
  8359. */
  8360. direct( { lightDirection, lightColor, reflectedLight } ) {
  8361. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8362. const irradiance = dotNL.mul( lightColor );
  8363. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8364. if ( this.specular === true ) {
  8365. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  8366. }
  8367. }
  8368. /**
  8369. * Implements the indirect lighting.
  8370. *
  8371. * @param {ContextNode} input - The current node context.
  8372. * @param {StackNode} stack - The current stack.
  8373. * @param {NodeBuilder} builder - The current node builder.
  8374. */
  8375. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  8376. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8377. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8378. }
  8379. }
  8380. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  8381. class MeshLambertNodeMaterial extends NodeMaterial {
  8382. static get type() {
  8383. return 'MeshLambertNodeMaterial';
  8384. }
  8385. constructor( parameters ) {
  8386. super();
  8387. this.isMeshLambertNodeMaterial = true;
  8388. this.lights = true;
  8389. this.setDefaultValues( _defaultValues$8 );
  8390. this.setValues( parameters );
  8391. }
  8392. setupEnvironment( builder ) {
  8393. const envNode = super.setupEnvironment( builder );
  8394. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8395. }
  8396. setupLightingModel( /*builder*/ ) {
  8397. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  8398. }
  8399. }
  8400. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  8401. class MeshPhongNodeMaterial extends NodeMaterial {
  8402. static get type() {
  8403. return 'MeshPhongNodeMaterial';
  8404. }
  8405. constructor( parameters ) {
  8406. super();
  8407. this.isMeshPhongNodeMaterial = true;
  8408. this.lights = true;
  8409. this.shininessNode = null;
  8410. this.specularNode = null;
  8411. this.setDefaultValues( _defaultValues$7 );
  8412. this.setValues( parameters );
  8413. }
  8414. setupEnvironment( builder ) {
  8415. const envNode = super.setupEnvironment( builder );
  8416. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8417. }
  8418. setupLightingModel( /*builder*/ ) {
  8419. return new PhongLightingModel();
  8420. }
  8421. setupVariants() {
  8422. // SHININESS
  8423. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  8424. shininess.assign( shininessNode );
  8425. // SPECULAR COLOR
  8426. const specularNode = this.specularNode || materialSpecular;
  8427. specularColor.assign( specularNode );
  8428. }
  8429. copy( source ) {
  8430. this.shininessNode = source.shininessNode;
  8431. this.specularNode = source.specularNode;
  8432. return super.copy( source );
  8433. }
  8434. }
  8435. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  8436. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8437. return float( 0 );
  8438. }
  8439. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  8440. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  8441. return geometryRoughness;
  8442. } );
  8443. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  8444. const { roughness } = inputs;
  8445. const geometryRoughness = getGeometryRoughness();
  8446. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  8447. roughnessFactor = roughnessFactor.add( geometryRoughness );
  8448. roughnessFactor = roughnessFactor.min( 1.0 );
  8449. return roughnessFactor;
  8450. } );
  8451. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  8452. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  8453. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  8454. const a2 = alpha.pow2();
  8455. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  8456. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  8457. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  8458. } ).setLayout( {
  8459. name: 'V_GGX_SmithCorrelated',
  8460. type: 'float',
  8461. inputs: [
  8462. { name: 'alpha', type: 'float' },
  8463. { name: 'dotNL', type: 'float' },
  8464. { name: 'dotNV', type: 'float' }
  8465. ]
  8466. } ); // validated
  8467. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8468. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  8469. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  8470. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  8471. const v = div( 0.5, gv.add( gl ) );
  8472. return v.saturate();
  8473. } ).setLayout( {
  8474. name: 'V_GGX_SmithCorrelated_Anisotropic',
  8475. type: 'float',
  8476. inputs: [
  8477. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8478. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8479. { name: 'dotTV', type: 'float', qualifier: 'in' },
  8480. { name: 'dotBV', type: 'float', qualifier: 'in' },
  8481. { name: 'dotTL', type: 'float', qualifier: 'in' },
  8482. { name: 'dotBL', type: 'float', qualifier: 'in' },
  8483. { name: 'dotNV', type: 'float', qualifier: 'in' },
  8484. { name: 'dotNL', type: 'float', qualifier: 'in' }
  8485. ]
  8486. } );
  8487. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  8488. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  8489. // alpha is "roughness squared" in Disney’s reparameterization
  8490. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  8491. const a2 = alpha.pow2();
  8492. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  8493. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  8494. } ).setLayout( {
  8495. name: 'D_GGX',
  8496. type: 'float',
  8497. inputs: [
  8498. { name: 'alpha', type: 'float' },
  8499. { name: 'dotNH', type: 'float' }
  8500. ]
  8501. } ); // validated
  8502. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  8503. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8504. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  8505. const a2 = alphaT.mul( alphaB );
  8506. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  8507. const v2 = v.dot( v );
  8508. const w2 = a2.div( v2 );
  8509. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  8510. } ).setLayout( {
  8511. name: 'D_GGX_Anisotropic',
  8512. type: 'float',
  8513. inputs: [
  8514. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8515. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8516. { name: 'dotNH', type: 'float', qualifier: 'in' },
  8517. { name: 'dotTH', type: 'float', qualifier: 'in' },
  8518. { name: 'dotBH', type: 'float', qualifier: 'in' }
  8519. ]
  8520. } );
  8521. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  8522. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  8523. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  8524. const normalView = inputs.normalView || transformedNormalView;
  8525. const alpha = roughness.pow2(); // UE4's roughness
  8526. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8527. const dotNL = normalView.dot( lightDirection ).clamp();
  8528. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  8529. const dotNH = normalView.dot( halfDir ).clamp();
  8530. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8531. let F = F_Schlick( { f0, f90, dotVH } );
  8532. let V, D;
  8533. if ( defined( USE_IRIDESCENCE ) ) {
  8534. F = iridescence.mix( F, f );
  8535. }
  8536. if ( defined( USE_ANISOTROPY ) ) {
  8537. const dotTL = anisotropyT.dot( lightDirection );
  8538. const dotTV = anisotropyT.dot( positionViewDirection );
  8539. const dotTH = anisotropyT.dot( halfDir );
  8540. const dotBL = anisotropyB.dot( lightDirection );
  8541. const dotBV = anisotropyB.dot( positionViewDirection );
  8542. const dotBH = anisotropyB.dot( halfDir );
  8543. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  8544. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  8545. } else {
  8546. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  8547. D = D_GGX( { alpha, dotNH } );
  8548. }
  8549. return F.mul( V ).mul( D );
  8550. } ); // validated
  8551. // Analytical approximation of the DFG LUT, one half of the
  8552. // split-sum approximation used in indirect specular lighting.
  8553. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  8554. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  8555. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  8556. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  8557. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  8558. const r = roughness.mul( c0 ).add( c1 );
  8559. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  8560. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  8561. return fab;
  8562. } ).setLayout( {
  8563. name: 'DFGApprox',
  8564. type: 'vec2',
  8565. inputs: [
  8566. { name: 'roughness', type: 'float' },
  8567. { name: 'dotNV', type: 'vec3' }
  8568. ]
  8569. } );
  8570. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  8571. const { dotNV, specularColor, specularF90, roughness } = inputs;
  8572. const fab = DFGApprox( { dotNV, roughness } );
  8573. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  8574. } );
  8575. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  8576. const x = dotVH.oneMinus().saturate();
  8577. const x2 = x.mul( x );
  8578. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  8579. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  8580. } ).setLayout( {
  8581. name: 'Schlick_to_F0',
  8582. type: 'vec3',
  8583. inputs: [
  8584. { name: 'f', type: 'vec3' },
  8585. { name: 'f90', type: 'float' },
  8586. { name: 'dotVH', type: 'float' }
  8587. ]
  8588. } );
  8589. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8590. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  8591. const alpha = roughness.pow2();
  8592. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  8593. const invAlpha = float( 1.0 ).div( alpha );
  8594. const cos2h = dotNH.pow2();
  8595. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  8596. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  8597. } ).setLayout( {
  8598. name: 'D_Charlie',
  8599. type: 'float',
  8600. inputs: [
  8601. { name: 'roughness', type: 'float' },
  8602. { name: 'dotNH', type: 'float' }
  8603. ]
  8604. } );
  8605. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8606. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  8607. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  8608. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  8609. } ).setLayout( {
  8610. name: 'V_Neubelt',
  8611. type: 'float',
  8612. inputs: [
  8613. { name: 'dotNV', type: 'float' },
  8614. { name: 'dotNL', type: 'float' }
  8615. ]
  8616. } );
  8617. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8618. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8619. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8620. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  8621. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8622. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  8623. const V = V_Neubelt( { dotNV, dotNL } );
  8624. return sheen.mul( D ).mul( V );
  8625. } );
  8626. // Rect Area Light
  8627. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  8628. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  8629. // code: https://github.com/selfshadow/ltc_code/
  8630. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  8631. const LUT_SIZE = 64.0;
  8632. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  8633. const LUT_BIAS = 0.5 / LUT_SIZE;
  8634. const dotNV = N.dot( V ).saturate();
  8635. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  8636. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  8637. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  8638. return uv;
  8639. } ).setLayout( {
  8640. name: 'LTC_Uv',
  8641. type: 'vec2',
  8642. inputs: [
  8643. { name: 'N', type: 'vec3' },
  8644. { name: 'V', type: 'vec3' },
  8645. { name: 'roughness', type: 'float' }
  8646. ]
  8647. } );
  8648. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  8649. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  8650. // An approximation of the form factor of a horizon-clipped rectangle.
  8651. const l = f.length();
  8652. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  8653. } ).setLayout( {
  8654. name: 'LTC_ClippedSphereFormFactor',
  8655. type: 'float',
  8656. inputs: [
  8657. { name: 'f', type: 'vec3' }
  8658. ]
  8659. } );
  8660. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  8661. const x = v1.dot( v2 );
  8662. const y = x.abs().toVar();
  8663. // rational polynomial approximation to theta / sin( theta ) / 2PI
  8664. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  8665. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  8666. const v = a.div( b );
  8667. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  8668. return v1.cross( v2 ).mul( theta_sintheta );
  8669. } ).setLayout( {
  8670. name: 'LTC_EdgeVectorFormFactor',
  8671. type: 'vec3',
  8672. inputs: [
  8673. { name: 'v1', type: 'vec3' },
  8674. { name: 'v2', type: 'vec3' }
  8675. ]
  8676. } );
  8677. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  8678. // bail if point is on back side of plane of light
  8679. // assumes ccw winding order of light vertices
  8680. const v1 = p1.sub( p0 ).toVar();
  8681. const v2 = p3.sub( p0 ).toVar();
  8682. const lightNormal = v1.cross( v2 );
  8683. const result = vec3().toVar();
  8684. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  8685. // construct orthonormal basis around N
  8686. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  8687. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  8688. // compute transform
  8689. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  8690. // transform rect
  8691. // & project rect onto sphere
  8692. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  8693. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  8694. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  8695. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  8696. // calculate vector form factor
  8697. const vectorFormFactor = vec3( 0 ).toVar();
  8698. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  8699. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  8700. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  8701. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  8702. // adjust for horizon clipping
  8703. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  8704. } );
  8705. return result;
  8706. } ).setLayout( {
  8707. name: 'LTC_Evaluate',
  8708. type: 'vec3',
  8709. inputs: [
  8710. { name: 'N', type: 'vec3' },
  8711. { name: 'V', type: 'vec3' },
  8712. { name: 'P', type: 'vec3' },
  8713. { name: 'mInv', type: 'mat3' },
  8714. { name: 'p0', type: 'vec3' },
  8715. { name: 'p1', type: 'vec3' },
  8716. { name: 'p2', type: 'vec3' },
  8717. { name: 'p3', type: 'vec3' }
  8718. ]
  8719. } );
  8720. // Mipped Bicubic Texture Filtering by N8
  8721. // https://www.shadertoy.com/view/Dl2SDW
  8722. const bC = 1.0 / 6.0;
  8723. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  8724. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  8725. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  8726. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  8727. const g0 = ( a ) => w0( a ).add( w1( a ) );
  8728. const g1 = ( a ) => w2( a ).add( w3( a ) );
  8729. // h0 and h1 are the two offset functions
  8730. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  8731. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  8732. const bicubic = ( textureNode, texelSize, lod ) => {
  8733. const uv = textureNode.uvNode;
  8734. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  8735. const iuv = floor( uvScaled );
  8736. const fuv = fract( uvScaled );
  8737. const g0x = g0( fuv.x );
  8738. const g1x = g1( fuv.x );
  8739. const h0x = h0( fuv.x );
  8740. const h1x = h1( fuv.x );
  8741. const h0y = h0( fuv.y );
  8742. const h1y = h1( fuv.y );
  8743. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8744. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8745. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8746. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8747. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  8748. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  8749. return a.add( b );
  8750. };
  8751. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  8752. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  8753. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  8754. const fLodSizeInv = div( 1.0, fLodSize );
  8755. const cLodSizeInv = div( 1.0, cLodSize );
  8756. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  8757. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  8758. return fract( lodNode ).mix( fSample, cSample );
  8759. } );
  8760. //
  8761. // Transmission
  8762. //
  8763. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  8764. // Direction of refracted light.
  8765. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  8766. // Compute rotation-independent scaling of the model matrix.
  8767. const modelScale = vec3(
  8768. length( modelMatrix[ 0 ].xyz ),
  8769. length( modelMatrix[ 1 ].xyz ),
  8770. length( modelMatrix[ 2 ].xyz )
  8771. );
  8772. // The thickness is specified in local space.
  8773. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  8774. } ).setLayout( {
  8775. name: 'getVolumeTransmissionRay',
  8776. type: 'vec3',
  8777. inputs: [
  8778. { name: 'n', type: 'vec3' },
  8779. { name: 'v', type: 'vec3' },
  8780. { name: 'thickness', type: 'float' },
  8781. { name: 'ior', type: 'float' },
  8782. { name: 'modelMatrix', type: 'mat4' }
  8783. ]
  8784. } );
  8785. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  8786. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  8787. // an IOR of 1.5 results in the default amount of microfacet refraction.
  8788. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  8789. } ).setLayout( {
  8790. name: 'applyIorToRoughness',
  8791. type: 'float',
  8792. inputs: [
  8793. { name: 'roughness', type: 'float' },
  8794. { name: 'ior', type: 'float' }
  8795. ]
  8796. } );
  8797. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  8798. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  8799. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  8800. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  8801. const transmissionSample = vTexture.sample( fragCoord );
  8802. //const transmissionSample = viewportMipTexture( fragCoord );
  8803. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  8804. return textureBicubic( transmissionSample, lod );
  8805. } );
  8806. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  8807. If( attenuationDistance.notEqual( 0 ), () => {
  8808. // Compute light attenuation using Beer's law.
  8809. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  8810. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  8811. return transmittance;
  8812. } );
  8813. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  8814. return vec3( 1.0 );
  8815. } ).setLayout( {
  8816. name: 'volumeAttenuation',
  8817. type: 'vec3',
  8818. inputs: [
  8819. { name: 'transmissionDistance', type: 'float' },
  8820. { name: 'attenuationColor', type: 'vec3' },
  8821. { name: 'attenuationDistance', type: 'float' }
  8822. ]
  8823. } );
  8824. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  8825. let transmittedLight, transmittance;
  8826. if ( dispersion ) {
  8827. transmittedLight = vec4().toVar();
  8828. transmittance = vec3().toVar();
  8829. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  8830. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  8831. Loop( { start: 0, end: 3 }, ( { i } ) => {
  8832. const ior = iors.element( i );
  8833. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8834. const refractedRayExit = position.add( transmissionRay );
  8835. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8836. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8837. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8838. refractionCoords.addAssign( 1.0 );
  8839. refractionCoords.divAssign( 2.0 );
  8840. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8841. // Sample framebuffer to get pixel the refracted ray hits.
  8842. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  8843. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  8844. transmittedLight.a.addAssign( transmissionSample.a );
  8845. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  8846. } );
  8847. transmittedLight.a.divAssign( 3.0 );
  8848. } else {
  8849. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8850. const refractedRayExit = position.add( transmissionRay );
  8851. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8852. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8853. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8854. refractionCoords.addAssign( 1.0 );
  8855. refractionCoords.divAssign( 2.0 );
  8856. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8857. // Sample framebuffer to get pixel the refracted ray hits.
  8858. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  8859. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  8860. }
  8861. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  8862. const dotNV = n.dot( v ).clamp();
  8863. // Get the specular component.
  8864. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  8865. dotNV,
  8866. specularColor,
  8867. specularF90,
  8868. roughness
  8869. } ) );
  8870. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  8871. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  8872. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  8873. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  8874. } );
  8875. //
  8876. // Iridescence
  8877. //
  8878. // XYZ to linear-sRGB color space
  8879. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  8880. 3.2404542, - 0.9692660, 0.0556434,
  8881. - 1.5371385, 1.8760108, - 0.2040259,
  8882. - 0.4985314, 0.0415560, 1.0572252
  8883. );
  8884. // Assume air interface for top
  8885. // Note: We don't handle the case fresnel0 == 1
  8886. const Fresnel0ToIor = ( fresnel0 ) => {
  8887. const sqrtF0 = fresnel0.sqrt();
  8888. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  8889. };
  8890. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  8891. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  8892. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  8893. };
  8894. // Fresnel equations for dielectric/dielectric interfaces.
  8895. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  8896. // Evaluation XYZ sensitivity curves in Fourier space
  8897. const evalSensitivity = ( OPD, shift ) => {
  8898. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  8899. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  8900. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  8901. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  8902. 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() );
  8903. 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() );
  8904. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  8905. const rgb = XYZ_TO_REC709.mul( xyz );
  8906. return rgb;
  8907. };
  8908. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  8909. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  8910. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  8911. // Evaluate the cosTheta on the base layer (Snell law)
  8912. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  8913. // Handle TIR:
  8914. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  8915. If( cosTheta2Sq.lessThan( 0 ), () => {
  8916. return vec3( 1.0 );
  8917. } );
  8918. const cosTheta2 = cosTheta2Sq.sqrt();
  8919. // First interface
  8920. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  8921. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  8922. //const R21 = R12;
  8923. const T121 = R12.oneMinus();
  8924. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  8925. const phi21 = float( Math.PI ).sub( phi12 );
  8926. // Second interface
  8927. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  8928. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  8929. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  8930. const phi23 = vec3(
  8931. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8932. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8933. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  8934. );
  8935. // Phase shift
  8936. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  8937. const phi = vec3( phi21 ).add( phi23 );
  8938. // Compound terms
  8939. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  8940. const r123 = R123.sqrt();
  8941. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  8942. // Reflectance term for m = 0 (DC term amplitude)
  8943. const C0 = R12.add( Rs );
  8944. const I = C0.toVar();
  8945. // Reflectance term for m > 0 (pairs of diracs)
  8946. const Cm = Rs.sub( T121 ).toVar();
  8947. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  8948. Cm.mulAssign( r123 );
  8949. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  8950. I.addAssign( Cm.mul( Sm ) );
  8951. } );
  8952. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  8953. return I.max( vec3( 0.0 ) );
  8954. } ).setLayout( {
  8955. name: 'evalIridescence',
  8956. type: 'vec3',
  8957. inputs: [
  8958. { name: 'outsideIOR', type: 'float' },
  8959. { name: 'eta2', type: 'float' },
  8960. { name: 'cosTheta1', type: 'float' },
  8961. { name: 'thinFilmThickness', type: 'float' },
  8962. { name: 'baseF0', type: 'vec3' }
  8963. ]
  8964. } );
  8965. //
  8966. // Sheen
  8967. //
  8968. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  8969. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  8970. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  8971. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  8972. const dotNV = normal.dot( viewDir ).saturate();
  8973. const r2 = roughness.pow2();
  8974. const a = select(
  8975. roughness.lessThan( 0.25 ),
  8976. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  8977. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  8978. );
  8979. const b = select(
  8980. roughness.lessThan( 0.25 ),
  8981. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  8982. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  8983. );
  8984. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  8985. return DG.mul( 1.0 / Math.PI ).saturate();
  8986. } );
  8987. const clearcoatF0 = vec3( 0.04 );
  8988. const clearcoatF90 = float( 1 );
  8989. /**
  8990. * Represents the lighting model for a PBR material.
  8991. *
  8992. * @augments LightingModel
  8993. */
  8994. class PhysicalLightingModel extends LightingModel {
  8995. /**
  8996. * Constructs a new physical lighting model.
  8997. *
  8998. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  8999. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  9000. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  9001. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  9002. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  9003. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  9004. */
  9005. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  9006. super();
  9007. /**
  9008. * Whether clearcoat is supported or not.
  9009. *
  9010. * @type {Boolean}
  9011. * @default false
  9012. */
  9013. this.clearcoat = clearcoat;
  9014. /**
  9015. * Whether sheen is supported or not.
  9016. *
  9017. * @type {Boolean}
  9018. * @default false
  9019. */
  9020. this.sheen = sheen;
  9021. /**
  9022. * Whether iridescence is supported or not.
  9023. *
  9024. * @type {Boolean}
  9025. * @default false
  9026. */
  9027. this.iridescence = iridescence;
  9028. /**
  9029. * Whether anisotropy is supported or not.
  9030. *
  9031. * @type {Boolean}
  9032. * @default false
  9033. */
  9034. this.anisotropy = anisotropy;
  9035. /**
  9036. * Whether transmission is supported or not.
  9037. *
  9038. * @type {Boolean}
  9039. * @default false
  9040. */
  9041. this.transmission = transmission;
  9042. /**
  9043. * Whether dispersion is supported or not.
  9044. *
  9045. * @type {Boolean}
  9046. * @default false
  9047. */
  9048. this.dispersion = dispersion;
  9049. /**
  9050. * The clear coat radiance.
  9051. *
  9052. * @type {Node?}
  9053. * @default null
  9054. */
  9055. this.clearcoatRadiance = null;
  9056. /**
  9057. * The clear coat specular direct.
  9058. *
  9059. * @type {Node?}
  9060. * @default null
  9061. */
  9062. this.clearcoatSpecularDirect = null;
  9063. /**
  9064. * The clear coat specular indirect.
  9065. *
  9066. * @type {Node?}
  9067. * @default null
  9068. */
  9069. this.clearcoatSpecularIndirect = null;
  9070. /**
  9071. * The sheen specular direct.
  9072. *
  9073. * @type {Node?}
  9074. * @default null
  9075. */
  9076. this.sheenSpecularDirect = null;
  9077. /**
  9078. * The sheen specular indirect.
  9079. *
  9080. * @type {Node?}
  9081. * @default null
  9082. */
  9083. this.sheenSpecularIndirect = null;
  9084. /**
  9085. * The iridescence Fresnel.
  9086. *
  9087. * @type {Node?}
  9088. * @default null
  9089. */
  9090. this.iridescenceFresnel = null;
  9091. /**
  9092. * The iridescence F0.
  9093. *
  9094. * @type {Node?}
  9095. * @default null
  9096. */
  9097. this.iridescenceF0 = null;
  9098. }
  9099. /**
  9100. * Depending on what features are requested, the method prepares certain node variables
  9101. * which are later used for lighting computations.
  9102. *
  9103. * @param {ContextNode} context - The current node context.
  9104. */
  9105. start( context ) {
  9106. if ( this.clearcoat === true ) {
  9107. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  9108. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  9109. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  9110. }
  9111. if ( this.sheen === true ) {
  9112. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  9113. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  9114. }
  9115. if ( this.iridescence === true ) {
  9116. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  9117. this.iridescenceFresnel = evalIridescence( {
  9118. outsideIOR: float( 1.0 ),
  9119. eta2: iridescenceIOR,
  9120. cosTheta1: dotNVi,
  9121. thinFilmThickness: iridescenceThickness,
  9122. baseF0: specularColor
  9123. } );
  9124. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  9125. }
  9126. if ( this.transmission === true ) {
  9127. const position = positionWorld;
  9128. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  9129. const n = transformedNormalWorld;
  9130. context.backdrop = getIBLVolumeRefraction(
  9131. n,
  9132. v,
  9133. roughness,
  9134. diffuseColor,
  9135. specularColor,
  9136. specularF90, // specularF90
  9137. position, // positionWorld
  9138. modelWorldMatrix, // modelMatrix
  9139. cameraViewMatrix, // viewMatrix
  9140. cameraProjectionMatrix, // projMatrix
  9141. ior,
  9142. thickness,
  9143. attenuationColor,
  9144. attenuationDistance,
  9145. this.dispersion ? dispersion : null
  9146. );
  9147. context.backdropAlpha = transmission;
  9148. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  9149. }
  9150. }
  9151. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  9152. // Approximates multi-scattering in order to preserve energy.
  9153. // http://www.jcgt.org/published/0008/01/03/
  9154. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  9155. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  9156. const fab = DFGApprox( { roughness, dotNV } );
  9157. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  9158. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  9159. const Ess = fab.x.add( fab.y );
  9160. const Ems = Ess.oneMinus();
  9161. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  9162. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  9163. singleScatter.addAssign( FssEss );
  9164. multiScatter.addAssign( Fms.mul( Ems ) );
  9165. }
  9166. /**
  9167. * Implements the direct light.
  9168. *
  9169. * @param {Object} input - The input data.
  9170. * @param {StackNode} stack - The current stack.
  9171. * @param {NodeBuilder} builder - The current node builder.
  9172. */
  9173. direct( { lightDirection, lightColor, reflectedLight } ) {
  9174. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  9175. const irradiance = dotNL.mul( lightColor );
  9176. if ( this.sheen === true ) {
  9177. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  9178. }
  9179. if ( this.clearcoat === true ) {
  9180. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  9181. const ccIrradiance = dotNLcc.mul( lightColor );
  9182. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  9183. }
  9184. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  9185. 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 } ) ) );
  9186. }
  9187. /**
  9188. * This method is intended for implementing the direct light term for
  9189. * rect area light nodes.
  9190. *
  9191. * @param {Object} input - The input data.
  9192. * @param {StackNode} stack - The current stack.
  9193. * @param {NodeBuilder} builder - The current node builder.
  9194. */
  9195. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  9196. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  9197. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  9198. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  9199. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  9200. const N = transformedNormalView;
  9201. const V = positionViewDirection;
  9202. const P = positionView.toVar();
  9203. const uv = LTC_Uv( { N, V, roughness } );
  9204. const t1 = ltc_1.sample( uv ).toVar();
  9205. const t2 = ltc_2.sample( uv ).toVar();
  9206. const mInv = mat3(
  9207. vec3( t1.x, 0, t1.y ),
  9208. vec3( 0, 1, 0 ),
  9209. vec3( t1.z, 0, t1.w )
  9210. ).toVar();
  9211. // LTC Fresnel Approximation by Stephen Hill
  9212. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  9213. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  9214. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  9215. 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 } ) ) );
  9216. }
  9217. /**
  9218. * Implements the indirect lighting.
  9219. *
  9220. * @param {ContextNode} context - The current node context.
  9221. * @param {StackNode} stack - The current stack.
  9222. * @param {NodeBuilder} builder - The current node builder.
  9223. */
  9224. indirect( context, stack, builder ) {
  9225. this.indirectDiffuse( context, stack, builder );
  9226. this.indirectSpecular( context, stack, builder );
  9227. this.ambientOcclusion( context, stack, builder );
  9228. }
  9229. /**
  9230. * Implements the indirect diffuse term.
  9231. *
  9232. * @param {ContextNode} input - The current node context.
  9233. * @param {StackNode} stack - The current stack.
  9234. * @param {NodeBuilder} builder - The current node builder.
  9235. */
  9236. indirectDiffuse( { irradiance, reflectedLight } ) {
  9237. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  9238. }
  9239. /**
  9240. * Implements the indirect specular term.
  9241. *
  9242. * @param {ContextNode} input - The current node context.
  9243. * @param {StackNode} stack - The current stack.
  9244. * @param {NodeBuilder} builder - The current node builder.
  9245. */
  9246. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  9247. if ( this.sheen === true ) {
  9248. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  9249. sheen,
  9250. IBLSheenBRDF( {
  9251. normal: transformedNormalView,
  9252. viewDir: positionViewDirection,
  9253. roughness: sheenRoughness
  9254. } )
  9255. ) );
  9256. }
  9257. if ( this.clearcoat === true ) {
  9258. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  9259. const clearcoatEnv = EnvironmentBRDF( {
  9260. dotNV: dotNVcc,
  9261. specularColor: clearcoatF0,
  9262. specularF90: clearcoatF90,
  9263. roughness: clearcoatRoughness
  9264. } );
  9265. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  9266. }
  9267. // Both indirect specular and indirect diffuse light accumulate here
  9268. const singleScattering = vec3().toVar( 'singleScattering' );
  9269. const multiScattering = vec3().toVar( 'multiScattering' );
  9270. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  9271. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  9272. const totalScattering = singleScattering.add( multiScattering );
  9273. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  9274. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  9275. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  9276. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  9277. }
  9278. /**
  9279. * Implements the ambient occlusion term.
  9280. *
  9281. * @param {ContextNode} input - The current node context.
  9282. * @param {StackNode} stack - The current stack.
  9283. * @param {NodeBuilder} builder - The current node builder.
  9284. */
  9285. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  9286. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  9287. const aoNV = dotNV.add( ambientOcclusion );
  9288. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  9289. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  9290. if ( this.clearcoat === true ) {
  9291. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  9292. }
  9293. if ( this.sheen === true ) {
  9294. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  9295. }
  9296. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  9297. reflectedLight.indirectSpecular.mulAssign( aoNode );
  9298. }
  9299. /**
  9300. * Used for final lighting accumulations depending on the requested features.
  9301. *
  9302. * @param {ContextNode} context - The current node context.
  9303. * @param {StackNode} stack - The current stack.
  9304. * @param {NodeBuilder} builder - The current node builder.
  9305. */
  9306. finish( context ) {
  9307. const { outgoingLight } = context;
  9308. if ( this.clearcoat === true ) {
  9309. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  9310. const Fcc = F_Schlick( {
  9311. dotVH: dotNVcc,
  9312. f0: clearcoatF0,
  9313. f90: clearcoatF90
  9314. } );
  9315. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  9316. outgoingLight.assign( clearcoatLight );
  9317. }
  9318. if ( this.sheen === true ) {
  9319. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  9320. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  9321. outgoingLight.assign( sheenLight );
  9322. }
  9323. }
  9324. }
  9325. // These defines must match with PMREMGenerator
  9326. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  9327. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  9328. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  9329. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  9330. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  9331. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  9332. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  9333. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  9334. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  9335. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  9336. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  9337. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  9338. // These shader functions convert between the UV coordinates of a single face of
  9339. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  9340. // sampling a textureCube (not generally normalized ).
  9341. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  9342. const absDirection = vec3( abs( direction ) ).toVar();
  9343. const face = float( - 1.0 ).toVar();
  9344. If( absDirection.x.greaterThan( absDirection.z ), () => {
  9345. If( absDirection.x.greaterThan( absDirection.y ), () => {
  9346. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  9347. } ).Else( () => {
  9348. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9349. } );
  9350. } ).Else( () => {
  9351. If( absDirection.z.greaterThan( absDirection.y ), () => {
  9352. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  9353. } ).Else( () => {
  9354. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9355. } );
  9356. } );
  9357. return face;
  9358. } ).setLayout( {
  9359. name: 'getFace',
  9360. type: 'float',
  9361. inputs: [
  9362. { name: 'direction', type: 'vec3' }
  9363. ]
  9364. } );
  9365. // RH coordinate system; PMREM face-indexing convention
  9366. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  9367. const uv = vec2().toVar();
  9368. If( face.equal( 0.0 ), () => {
  9369. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  9370. } ).ElseIf( face.equal( 1.0 ), () => {
  9371. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  9372. } ).ElseIf( face.equal( 2.0 ), () => {
  9373. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  9374. } ).ElseIf( face.equal( 3.0 ), () => {
  9375. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  9376. } ).ElseIf( face.equal( 4.0 ), () => {
  9377. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  9378. } ).Else( () => {
  9379. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  9380. } );
  9381. return mul( 0.5, uv.add( 1.0 ) );
  9382. } ).setLayout( {
  9383. name: 'getUV',
  9384. type: 'vec2',
  9385. inputs: [
  9386. { name: 'direction', type: 'vec3' },
  9387. { name: 'face', type: 'float' }
  9388. ]
  9389. } );
  9390. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  9391. const mip = float( 0.0 ).toVar();
  9392. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  9393. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  9394. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  9395. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  9396. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  9397. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  9398. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  9399. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  9400. } ).Else( () => {
  9401. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  9402. } );
  9403. return mip;
  9404. } ).setLayout( {
  9405. name: 'roughnessToMip',
  9406. type: 'float',
  9407. inputs: [
  9408. { name: 'roughness', type: 'float' }
  9409. ]
  9410. } );
  9411. // RH coordinate system; PMREM face-indexing convention
  9412. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  9413. const uv = uv_immutable.toVar();
  9414. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  9415. const direction = vec3( uv, 1.0 ).toVar();
  9416. If( face.equal( 0.0 ), () => {
  9417. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  9418. } ).ElseIf( face.equal( 1.0 ), () => {
  9419. direction.assign( direction.xzy );
  9420. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  9421. } ).ElseIf( face.equal( 2.0 ), () => {
  9422. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  9423. } ).ElseIf( face.equal( 3.0 ), () => {
  9424. direction.assign( direction.zyx );
  9425. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  9426. } ).ElseIf( face.equal( 4.0 ), () => {
  9427. direction.assign( direction.xzy );
  9428. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  9429. } ).ElseIf( face.equal( 5.0 ), () => {
  9430. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  9431. } );
  9432. return direction;
  9433. } ).setLayout( {
  9434. name: 'getDirection',
  9435. type: 'vec3',
  9436. inputs: [
  9437. { name: 'uv', type: 'vec2' },
  9438. { name: 'face', type: 'float' }
  9439. ]
  9440. } );
  9441. //
  9442. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9443. const roughness = float( roughness_immutable );
  9444. const sampleDir = vec3( sampleDir_immutable );
  9445. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  9446. const mipF = fract( mip );
  9447. const mipInt = floor( mip );
  9448. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9449. If( mipF.notEqual( 0.0 ), () => {
  9450. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9451. color0.assign( mix( color0, color1, mipF ) );
  9452. } );
  9453. return color0;
  9454. } );
  9455. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9456. const mipInt = float( mipInt_immutable ).toVar();
  9457. const direction = vec3( direction_immutable );
  9458. const face = float( getFace( direction ) ).toVar();
  9459. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  9460. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  9461. const faceSize = float( exp2( mipInt ) ).toVar();
  9462. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  9463. If( face.greaterThan( 2.0 ), () => {
  9464. uv.y.addAssign( faceSize );
  9465. face.subAssign( 3.0 );
  9466. } );
  9467. uv.x.addAssign( face.mul( faceSize ) );
  9468. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  9469. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  9470. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  9471. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  9472. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  9473. } );
  9474. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9475. const cosTheta = cos( theta );
  9476. // Rodrigues' axis-angle rotation
  9477. const sampleDirection = outputDirection.mul( cosTheta )
  9478. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  9479. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  9480. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  9481. } );
  9482. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9483. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  9484. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  9485. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  9486. } );
  9487. axis.assign( normalize( axis ) );
  9488. const gl_FragColor = vec3().toVar();
  9489. 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 } ) ) );
  9490. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  9491. If( i.greaterThanEqual( samples ), () => {
  9492. Break();
  9493. } );
  9494. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  9495. 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 } ) ) );
  9496. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  9497. } );
  9498. return vec4( gl_FragColor, 1 );
  9499. } );
  9500. let _generator = null;
  9501. const _cache = new WeakMap();
  9502. /**
  9503. * Generates the cubeUV size based on the given image height.
  9504. *
  9505. * @private
  9506. * @param {Number} imageHeight - The image height.
  9507. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  9508. */
  9509. function _generateCubeUVSize( imageHeight ) {
  9510. const maxMip = Math.log2( imageHeight ) - 2;
  9511. const texelHeight = 1.0 / imageHeight;
  9512. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  9513. return { texelWidth, texelHeight, maxMip };
  9514. }
  9515. /**
  9516. * Generates a PMREM from the given texture .
  9517. *
  9518. * @private
  9519. * @param {Texture} texture - The texture to create the PMREM for.
  9520. * @return {Texture} The PMREM.
  9521. */
  9522. function _getPMREMFromTexture( texture ) {
  9523. let cacheTexture = _cache.get( texture );
  9524. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  9525. if ( pmremVersion !== texture.pmremVersion ) {
  9526. const image = texture.image;
  9527. if ( texture.isCubeTexture ) {
  9528. if ( isCubeMapReady( image ) ) {
  9529. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  9530. } else {
  9531. return null;
  9532. }
  9533. } else {
  9534. if ( isEquirectangularMapReady( image ) ) {
  9535. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  9536. } else {
  9537. return null;
  9538. }
  9539. }
  9540. cacheTexture.pmremVersion = texture.pmremVersion;
  9541. _cache.set( texture, cacheTexture );
  9542. }
  9543. return cacheTexture.texture;
  9544. }
  9545. /**
  9546. * This node represents a PMREM which is a special type of preprocessed
  9547. * environment map intended for PBR materials.
  9548. *
  9549. * ```js
  9550. * const material = new MeshStandardNodeMaterial();
  9551. * material.envNode = pmremTexture( envMap );
  9552. * ```
  9553. *
  9554. * @augments TempNode
  9555. */
  9556. class PMREMNode extends TempNode {
  9557. static get type() {
  9558. return 'PMREMNode';
  9559. }
  9560. /**
  9561. * Constructs a new function overloading node.
  9562. *
  9563. * @param {Texture} value - The input texture.
  9564. * @param {Node<vec2>} [uvNode=null] - The uv node.
  9565. * @param {Node<float>} [levelNode=null] - The level node.
  9566. */
  9567. constructor( value, uvNode = null, levelNode = null ) {
  9568. super( 'vec3' );
  9569. /**
  9570. * Reference to the input texture.
  9571. *
  9572. * @private
  9573. * @type {Texture}
  9574. */
  9575. this._value = value;
  9576. /**
  9577. * Reference to the generated PMREM.
  9578. *
  9579. * @private
  9580. * @type {Texture | null}
  9581. * @default null
  9582. */
  9583. this._pmrem = null;
  9584. /**
  9585. * The uv node.
  9586. *
  9587. * @type {Node<vec2>}
  9588. */
  9589. this.uvNode = uvNode;
  9590. /**
  9591. * The level node.
  9592. *
  9593. * @type {Node<float>}
  9594. */
  9595. this.levelNode = levelNode;
  9596. /**
  9597. * Reference to a PMREM generator.
  9598. *
  9599. * @private
  9600. * @type {PMREMGenerator}
  9601. * @default null
  9602. */
  9603. this._generator = null;
  9604. const defaultTexture = new Texture();
  9605. defaultTexture.isRenderTargetTexture = true;
  9606. /**
  9607. * The texture node holding the generated PMREM.
  9608. *
  9609. * @private
  9610. * @type {TextureNode}
  9611. */
  9612. this._texture = texture( defaultTexture );
  9613. /**
  9614. * A uniform representing the PMREM's width.
  9615. *
  9616. * @private
  9617. * @type {UniformNode<float>}
  9618. */
  9619. this._width = uniform( 0 );
  9620. /**
  9621. * A uniform representing the PMREM's height.
  9622. *
  9623. * @private
  9624. * @type {UniformNode<float>}
  9625. */
  9626. this._height = uniform( 0 );
  9627. /**
  9628. * A uniform representing the PMREM's max Mip.
  9629. *
  9630. * @private
  9631. * @type {UniformNode<float>}
  9632. */
  9633. this._maxMip = uniform( 0 );
  9634. /**
  9635. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  9636. *
  9637. * @type {String}
  9638. * @default 'render'
  9639. */
  9640. this.updateBeforeType = NodeUpdateType.RENDER;
  9641. }
  9642. set value( value ) {
  9643. this._value = value;
  9644. this._pmrem = null;
  9645. }
  9646. /**
  9647. * The node's texture value.
  9648. *
  9649. * @type {Texture}
  9650. */
  9651. get value() {
  9652. return this._value;
  9653. }
  9654. /**
  9655. * Uses the given PMREM texture to update internal values.
  9656. *
  9657. * @param {Texture} texture - The PMREM texture.
  9658. */
  9659. updateFromTexture( texture ) {
  9660. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  9661. this._texture.value = texture;
  9662. this._width.value = cubeUVSize.texelWidth;
  9663. this._height.value = cubeUVSize.texelHeight;
  9664. this._maxMip.value = cubeUVSize.maxMip;
  9665. }
  9666. updateBefore() {
  9667. let pmrem = this._pmrem;
  9668. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  9669. const texture = this._value;
  9670. if ( pmremVersion !== texture.pmremVersion ) {
  9671. if ( texture.isPMREMTexture === true ) {
  9672. pmrem = texture;
  9673. } else {
  9674. pmrem = _getPMREMFromTexture( texture );
  9675. }
  9676. if ( pmrem !== null ) {
  9677. this._pmrem = pmrem;
  9678. this.updateFromTexture( pmrem );
  9679. }
  9680. }
  9681. }
  9682. setup( builder ) {
  9683. if ( _generator === null ) {
  9684. _generator = builder.createPMREMGenerator();
  9685. }
  9686. //
  9687. this.updateBefore( builder );
  9688. //
  9689. let uvNode = this.uvNode;
  9690. if ( uvNode === null && builder.context.getUV ) {
  9691. uvNode = builder.context.getUV( this );
  9692. }
  9693. //
  9694. const texture = this.value;
  9695. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  9696. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9697. }
  9698. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  9699. //
  9700. let levelNode = this.levelNode;
  9701. if ( levelNode === null && builder.context.getTextureLevel ) {
  9702. levelNode = builder.context.getTextureLevel( this );
  9703. }
  9704. //
  9705. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  9706. }
  9707. }
  9708. /**
  9709. * Returns `true` if the given cube map image has been fully loaded.
  9710. *
  9711. * @private
  9712. * @param {Array<(Image|Object)>} image - The cube map image.
  9713. * @return {Boolean} Whether the given cube map is ready or not.
  9714. */
  9715. function isCubeMapReady( image ) {
  9716. if ( image === null || image === undefined ) return false;
  9717. let count = 0;
  9718. const length = 6;
  9719. for ( let i = 0; i < length; i ++ ) {
  9720. if ( image[ i ] !== undefined ) count ++;
  9721. }
  9722. return count === length;
  9723. }
  9724. /**
  9725. * Returns `true` if the given equirectangular image has been fully loaded.
  9726. *
  9727. * @private
  9728. * @param {(Image|Object)} image - The equirectangular image.
  9729. * @return {Boolean} Whether the given cube map is ready or not.
  9730. */
  9731. function isEquirectangularMapReady( image ) {
  9732. if ( image === null || image === undefined ) return false;
  9733. return image.height > 0;
  9734. }
  9735. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  9736. const _envNodeCache = new WeakMap();
  9737. /**
  9738. * Represents a physical model for Image-based lighting (IBL). The environment
  9739. * is defined via environment maps in the equirectanular, cube map or cubeUV (PMREM) format.
  9740. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  9741. *
  9742. * @augments LightingNode
  9743. */
  9744. class EnvironmentNode extends LightingNode {
  9745. static get type() {
  9746. return 'EnvironmentNode';
  9747. }
  9748. /**
  9749. * Constructs a new environment node.
  9750. *
  9751. * @param {Node} [envNode=null] - A node representing the environment.
  9752. */
  9753. constructor( envNode = null ) {
  9754. super();
  9755. /**
  9756. * A node representing the environment.
  9757. *
  9758. * @type {Node}
  9759. * @default null
  9760. */
  9761. this.envNode = envNode;
  9762. }
  9763. setup( builder ) {
  9764. const { material } = builder;
  9765. let envNode = this.envNode;
  9766. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  9767. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  9768. let cacheEnvNode = _envNodeCache.get( value );
  9769. if ( cacheEnvNode === undefined ) {
  9770. cacheEnvNode = pmremTexture( value );
  9771. _envNodeCache.set( value, cacheEnvNode );
  9772. }
  9773. envNode = cacheEnvNode;
  9774. }
  9775. //
  9776. const envMap = material.envMap;
  9777. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  9778. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  9779. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  9780. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  9781. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  9782. const isolateRadiance = cache( radiance );
  9783. const isolateIrradiance = cache( irradiance );
  9784. //
  9785. builder.context.radiance.addAssign( isolateRadiance );
  9786. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  9787. //
  9788. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  9789. if ( clearcoatRadiance ) {
  9790. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  9791. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  9792. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  9793. }
  9794. }
  9795. }
  9796. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  9797. let reflectVec = null;
  9798. return {
  9799. getUV: () => {
  9800. if ( reflectVec === null ) {
  9801. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  9802. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  9803. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  9804. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  9805. }
  9806. return reflectVec;
  9807. },
  9808. getTextureLevel: () => {
  9809. return roughnessNode;
  9810. }
  9811. };
  9812. };
  9813. const createIrradianceContext = ( normalWorldNode ) => {
  9814. return {
  9815. getUV: () => {
  9816. return normalWorldNode;
  9817. },
  9818. getTextureLevel: () => {
  9819. return float( 1.0 );
  9820. }
  9821. };
  9822. };
  9823. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  9824. class MeshStandardNodeMaterial extends NodeMaterial {
  9825. static get type() {
  9826. return 'MeshStandardNodeMaterial';
  9827. }
  9828. constructor( parameters ) {
  9829. super();
  9830. this.isMeshStandardNodeMaterial = true;
  9831. this.lights = true;
  9832. this.emissiveNode = null;
  9833. this.metalnessNode = null;
  9834. this.roughnessNode = null;
  9835. this.setDefaultValues( _defaultValues$6 );
  9836. this.setValues( parameters );
  9837. }
  9838. setupEnvironment( builder ) {
  9839. let envNode = super.setupEnvironment( builder );
  9840. if ( envNode === null && builder.environmentNode ) {
  9841. envNode = builder.environmentNode;
  9842. }
  9843. return envNode ? new EnvironmentNode( envNode ) : null;
  9844. }
  9845. setupLightingModel( /*builder*/ ) {
  9846. return new PhysicalLightingModel();
  9847. }
  9848. setupSpecular() {
  9849. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  9850. specularColor.assign( specularColorNode );
  9851. specularF90.assign( 1.0 );
  9852. }
  9853. setupVariants() {
  9854. // METALNESS
  9855. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  9856. metalness.assign( metalnessNode );
  9857. // ROUGHNESS
  9858. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  9859. roughnessNode = getRoughness( { roughness: roughnessNode } );
  9860. roughness.assign( roughnessNode );
  9861. // SPECULAR COLOR
  9862. this.setupSpecular();
  9863. // DIFFUSE COLOR
  9864. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  9865. }
  9866. copy( source ) {
  9867. this.emissiveNode = source.emissiveNode;
  9868. this.metalnessNode = source.metalnessNode;
  9869. this.roughnessNode = source.roughnessNode;
  9870. return super.copy( source );
  9871. }
  9872. }
  9873. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  9874. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  9875. static get type() {
  9876. return 'MeshPhysicalNodeMaterial';
  9877. }
  9878. constructor( parameters ) {
  9879. super();
  9880. this.isMeshPhysicalNodeMaterial = true;
  9881. this.clearcoatNode = null;
  9882. this.clearcoatRoughnessNode = null;
  9883. this.clearcoatNormalNode = null;
  9884. this.sheenNode = null;
  9885. this.sheenRoughnessNode = null;
  9886. this.iridescenceNode = null;
  9887. this.iridescenceIORNode = null;
  9888. this.iridescenceThicknessNode = null;
  9889. this.specularIntensityNode = null;
  9890. this.specularColorNode = null;
  9891. this.iorNode = null;
  9892. this.transmissionNode = null;
  9893. this.thicknessNode = null;
  9894. this.attenuationDistanceNode = null;
  9895. this.attenuationColorNode = null;
  9896. this.dispersionNode = null;
  9897. this.anisotropyNode = null;
  9898. this.setDefaultValues( _defaultValues$5 );
  9899. this.setValues( parameters );
  9900. }
  9901. get useClearcoat() {
  9902. return this.clearcoat > 0 || this.clearcoatNode !== null;
  9903. }
  9904. get useIridescence() {
  9905. return this.iridescence > 0 || this.iridescenceNode !== null;
  9906. }
  9907. get useSheen() {
  9908. return this.sheen > 0 || this.sheenNode !== null;
  9909. }
  9910. get useAnisotropy() {
  9911. return this.anisotropy > 0 || this.anisotropyNode !== null;
  9912. }
  9913. get useTransmission() {
  9914. return this.transmission > 0 || this.transmissionNode !== null;
  9915. }
  9916. get useDispersion() {
  9917. return this.dispersion > 0 || this.dispersionNode !== null;
  9918. }
  9919. setupSpecular() {
  9920. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  9921. ior.assign( iorNode );
  9922. 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 ) );
  9923. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  9924. }
  9925. setupLightingModel( /*builder*/ ) {
  9926. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  9927. }
  9928. setupVariants( builder ) {
  9929. super.setupVariants( builder );
  9930. // CLEARCOAT
  9931. if ( this.useClearcoat ) {
  9932. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  9933. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  9934. clearcoat.assign( clearcoatNode );
  9935. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  9936. }
  9937. // SHEEN
  9938. if ( this.useSheen ) {
  9939. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  9940. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  9941. sheen.assign( sheenNode );
  9942. sheenRoughness.assign( sheenRoughnessNode );
  9943. }
  9944. // IRIDESCENCE
  9945. if ( this.useIridescence ) {
  9946. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  9947. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  9948. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  9949. iridescence.assign( iridescenceNode );
  9950. iridescenceIOR.assign( iridescenceIORNode );
  9951. iridescenceThickness.assign( iridescenceThicknessNode );
  9952. }
  9953. // ANISOTROPY
  9954. if ( this.useAnisotropy ) {
  9955. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  9956. anisotropy.assign( anisotropyV.length() );
  9957. If( anisotropy.equal( 0.0 ), () => {
  9958. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  9959. } ).Else( () => {
  9960. anisotropyV.divAssign( vec2( anisotropy ) );
  9961. anisotropy.assign( anisotropy.saturate() );
  9962. } );
  9963. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  9964. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  9965. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  9966. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  9967. }
  9968. // TRANSMISSION
  9969. if ( this.useTransmission ) {
  9970. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  9971. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  9972. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  9973. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  9974. transmission.assign( transmissionNode );
  9975. thickness.assign( thicknessNode );
  9976. attenuationDistance.assign( attenuationDistanceNode );
  9977. attenuationColor.assign( attenuationColorNode );
  9978. if ( this.useDispersion ) {
  9979. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  9980. dispersion.assign( dispersionNode );
  9981. }
  9982. }
  9983. }
  9984. setupClearcoatNormal() {
  9985. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  9986. }
  9987. setup( builder ) {
  9988. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  9989. super.setup( builder );
  9990. }
  9991. copy( source ) {
  9992. this.clearcoatNode = source.clearcoatNode;
  9993. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  9994. this.clearcoatNormalNode = source.clearcoatNormalNode;
  9995. this.sheenNode = source.sheenNode;
  9996. this.sheenRoughnessNode = source.sheenRoughnessNode;
  9997. this.iridescenceNode = source.iridescenceNode;
  9998. this.iridescenceIORNode = source.iridescenceIORNode;
  9999. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  10000. this.specularIntensityNode = source.specularIntensityNode;
  10001. this.specularColorNode = source.specularColorNode;
  10002. this.transmissionNode = source.transmissionNode;
  10003. this.thicknessNode = source.thicknessNode;
  10004. this.attenuationDistanceNode = source.attenuationDistanceNode;
  10005. this.attenuationColorNode = source.attenuationColorNode;
  10006. this.dispersionNode = source.dispersionNode;
  10007. this.anisotropyNode = source.anisotropyNode;
  10008. return super.copy( source );
  10009. }
  10010. }
  10011. class SSSLightingModel extends PhysicalLightingModel {
  10012. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  10013. super( useClearcoat, useSheen, useIridescence );
  10014. this.useSSS = useSSS;
  10015. }
  10016. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  10017. if ( this.useSSS === true ) {
  10018. const material = builder.material;
  10019. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  10020. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  10021. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  10022. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  10023. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  10024. }
  10025. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  10026. }
  10027. }
  10028. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  10029. static get type() {
  10030. return 'MeshSSSNodeMaterial';
  10031. }
  10032. constructor( parameters ) {
  10033. super( parameters );
  10034. this.thicknessColorNode = null;
  10035. this.thicknessDistortionNode = float( 0.1 );
  10036. this.thicknessAmbientNode = float( 0.0 );
  10037. this.thicknessAttenuationNode = float( .1 );
  10038. this.thicknessPowerNode = float( 2.0 );
  10039. this.thicknessScaleNode = float( 10.0 );
  10040. }
  10041. get useSSS() {
  10042. return this.thicknessColorNode !== null;
  10043. }
  10044. setupLightingModel( /*builder*/ ) {
  10045. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  10046. }
  10047. copy( source ) {
  10048. this.thicknessColorNode = source.thicknessColorNode;
  10049. this.thicknessDistortionNode = source.thicknessDistortionNode;
  10050. this.thicknessAmbientNode = source.thicknessAmbientNode;
  10051. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  10052. this.thicknessPowerNode = source.thicknessPowerNode;
  10053. this.thicknessScaleNode = source.thicknessScaleNode;
  10054. return super.copy( source );
  10055. }
  10056. }
  10057. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  10058. // dotNL will be from -1.0 to 1.0
  10059. const dotNL = normal.dot( lightDirection );
  10060. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  10061. if ( builder.material.gradientMap ) {
  10062. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  10063. return vec3( gradientMap.r );
  10064. } else {
  10065. const fw = coord.fwidth().mul( 0.5 );
  10066. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  10067. }
  10068. } );
  10069. /**
  10070. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  10071. *
  10072. * @augments LightingModel
  10073. */
  10074. class ToonLightingModel extends LightingModel {
  10075. /**
  10076. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  10077. * reduced to a small number of discrete shades to create a comic-like, flat look.
  10078. *
  10079. * @param {Object} input - The input data.
  10080. * @param {StackNode} stack - The current stack.
  10081. * @param {NodeBuilder} builder - The current node builder.
  10082. */
  10083. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  10084. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  10085. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  10086. }
  10087. /**
  10088. * Implements the indirect lighting.
  10089. *
  10090. * @param {ContextNode} input - The current node context.
  10091. * @param {StackNode} stack - The current stack.
  10092. * @param {NodeBuilder} builder - The current node builder.
  10093. */
  10094. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  10095. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  10096. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  10097. }
  10098. }
  10099. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  10100. class MeshToonNodeMaterial extends NodeMaterial {
  10101. static get type() {
  10102. return 'MeshToonNodeMaterial';
  10103. }
  10104. constructor( parameters ) {
  10105. super();
  10106. this.isMeshToonNodeMaterial = true;
  10107. this.lights = true;
  10108. this.setDefaultValues( _defaultValues$4 );
  10109. this.setValues( parameters );
  10110. }
  10111. setupLightingModel( /*builder*/ ) {
  10112. return new ToonLightingModel();
  10113. }
  10114. }
  10115. /**
  10116. * Can be used to compute texture coordinates for projecting a
  10117. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  10118. *
  10119. * @augments TempNode
  10120. */
  10121. class MatcapUVNode extends TempNode {
  10122. static get type() {
  10123. return 'MatcapUVNode';
  10124. }
  10125. /**
  10126. * Constructs a new matcap uv node.
  10127. */
  10128. constructor() {
  10129. super( 'vec2' );
  10130. }
  10131. setup() {
  10132. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  10133. const y = positionViewDirection.cross( x );
  10134. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  10135. }
  10136. }
  10137. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  10138. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  10139. class MeshMatcapNodeMaterial extends NodeMaterial {
  10140. static get type() {
  10141. return 'MeshMatcapNodeMaterial';
  10142. }
  10143. constructor( parameters ) {
  10144. super();
  10145. this.lights = false;
  10146. this.isMeshMatcapNodeMaterial = true;
  10147. this.setDefaultValues( _defaultValues$3 );
  10148. this.setValues( parameters );
  10149. }
  10150. setupVariants( builder ) {
  10151. const uv = matcapUV;
  10152. let matcapColor;
  10153. if ( builder.material.matcap ) {
  10154. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  10155. } else {
  10156. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  10157. }
  10158. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  10159. }
  10160. }
  10161. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  10162. class PointsNodeMaterial extends NodeMaterial {
  10163. static get type() {
  10164. return 'PointsNodeMaterial';
  10165. }
  10166. constructor( parameters ) {
  10167. super();
  10168. this.isPointsNodeMaterial = true;
  10169. this.lights = false;
  10170. this.transparent = true;
  10171. this.sizeNode = null;
  10172. this.setDefaultValues( _defaultValues$2 );
  10173. this.setValues( parameters );
  10174. }
  10175. copy( source ) {
  10176. this.sizeNode = source.sizeNode;
  10177. return super.copy( source );
  10178. }
  10179. }
  10180. /**
  10181. * Applies a rotation to the given position node.
  10182. *
  10183. * @augments TempNode
  10184. */
  10185. class RotateNode extends TempNode {
  10186. static get type() {
  10187. return 'RotateNode';
  10188. }
  10189. /**
  10190. * Constructs a new rotate node.
  10191. *
  10192. * @param {Node} positionNode - The position node.
  10193. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  10194. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  10195. */
  10196. constructor( positionNode, rotationNode ) {
  10197. super();
  10198. /**
  10199. * The position node.
  10200. *
  10201. * @type {Node}
  10202. */
  10203. this.positionNode = positionNode;
  10204. /**
  10205. * Represents the rotation that is applied to the position node.
  10206. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  10207. *
  10208. * @type {Node}
  10209. */
  10210. this.rotationNode = rotationNode;
  10211. }
  10212. /**
  10213. * The type of the {@link RotateNode#positionNode} defines the node's type.
  10214. *
  10215. * @param {NodeBuilder} builder - The current node builder.
  10216. * @return {String} The node's type.
  10217. */
  10218. getNodeType( builder ) {
  10219. return this.positionNode.getNodeType( builder );
  10220. }
  10221. setup( builder ) {
  10222. const { rotationNode, positionNode } = this;
  10223. const nodeType = this.getNodeType( builder );
  10224. if ( nodeType === 'vec2' ) {
  10225. const cosAngle = rotationNode.cos();
  10226. const sinAngle = rotationNode.sin();
  10227. const rotationMatrix = mat2(
  10228. cosAngle, sinAngle,
  10229. sinAngle.negate(), cosAngle
  10230. );
  10231. return rotationMatrix.mul( positionNode );
  10232. } else {
  10233. const rotation = rotationNode;
  10234. 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 ) );
  10235. 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 ) );
  10236. 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 ) );
  10237. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  10238. }
  10239. }
  10240. }
  10241. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  10242. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  10243. class SpriteNodeMaterial extends NodeMaterial {
  10244. static get type() {
  10245. return 'SpriteNodeMaterial';
  10246. }
  10247. constructor( parameters ) {
  10248. super();
  10249. this.isSpriteNodeMaterial = true;
  10250. this.lights = false;
  10251. this._useSizeAttenuation = true;
  10252. this.positionNode = null;
  10253. this.rotationNode = null;
  10254. this.scaleNode = null;
  10255. this.setDefaultValues( _defaultValues$1 );
  10256. this.setValues( parameters );
  10257. }
  10258. setupPosition( { object, camera, context } ) {
  10259. const sizeAttenuation = this.sizeAttenuation;
  10260. // < VERTEX STAGE >
  10261. const { positionNode, rotationNode, scaleNode } = this;
  10262. const vertex = positionLocal;
  10263. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  10264. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  10265. if ( scaleNode !== null ) {
  10266. scale = scale.mul( scaleNode );
  10267. }
  10268. if ( ! sizeAttenuation ) {
  10269. if ( camera.isPerspectiveCamera ) {
  10270. scale = scale.mul( mvPosition.z.negate() );
  10271. } else {
  10272. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  10273. scale = scale.mul( orthoScale.mul( 2 ) );
  10274. }
  10275. }
  10276. let alignedPosition = vertex.xy;
  10277. if ( object.center && object.center.isVector2 === true ) {
  10278. const center = reference$1( 'center', 'vec2' );
  10279. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  10280. }
  10281. alignedPosition = alignedPosition.mul( scale );
  10282. const rotation = float( rotationNode || materialRotation );
  10283. const rotatedPosition = rotate( alignedPosition, rotation );
  10284. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  10285. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  10286. context.vertex = vertex;
  10287. return modelViewProjection;
  10288. }
  10289. copy( source ) {
  10290. this.positionNode = source.positionNode;
  10291. this.rotationNode = source.rotationNode;
  10292. this.scaleNode = source.scaleNode;
  10293. return super.copy( source );
  10294. }
  10295. get sizeAttenuation() {
  10296. return this._useSizeAttenuation;
  10297. }
  10298. set sizeAttenuation( value ) {
  10299. if ( this._useSizeAttenuation !== value ) {
  10300. this._useSizeAttenuation = value;
  10301. this.needsUpdate = true;
  10302. }
  10303. }
  10304. }
  10305. /**
  10306. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  10307. *
  10308. * @augments LightingModel
  10309. */
  10310. class ShadowMaskModel extends LightingModel {
  10311. /**
  10312. * Constructs a new shadow mask model.
  10313. */
  10314. constructor() {
  10315. super();
  10316. /**
  10317. * The shadow mask node.
  10318. *
  10319. * @type {Node}
  10320. */
  10321. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  10322. }
  10323. /**
  10324. * Only used to save the shadow mask.
  10325. *
  10326. * @param {Object} input - The input data.
  10327. */
  10328. direct( { shadowMask } ) {
  10329. this.shadowNode.mulAssign( shadowMask );
  10330. }
  10331. /**
  10332. * Uses the shadow mask to produce the final color.
  10333. *
  10334. * @param {ContextNode} context - The current node context.
  10335. */
  10336. finish( context ) {
  10337. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  10338. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  10339. }
  10340. }
  10341. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  10342. class ShadowNodeMaterial extends NodeMaterial {
  10343. static get type() {
  10344. return 'ShadowNodeMaterial';
  10345. }
  10346. constructor( parameters ) {
  10347. super();
  10348. this.isShadowNodeMaterial = true;
  10349. this.lights = true;
  10350. this.setDefaultValues( _defaultValues );
  10351. this.setValues( parameters );
  10352. }
  10353. setupLightingModel( /*builder*/ ) {
  10354. return new ShadowMaskModel();
  10355. }
  10356. }
  10357. const normal = Fn( ( { texture, uv } ) => {
  10358. const epsilon = 0.0001;
  10359. const ret = vec3().toVar();
  10360. If( uv.x.lessThan( epsilon ), () => {
  10361. ret.assign( vec3( 1, 0, 0 ) );
  10362. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  10363. ret.assign( vec3( 0, 1, 0 ) );
  10364. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  10365. ret.assign( vec3( 0, 0, 1 ) );
  10366. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  10367. ret.assign( vec3( - 1, 0, 0 ) );
  10368. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  10369. ret.assign( vec3( 0, - 1, 0 ) );
  10370. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  10371. ret.assign( vec3( 0, 0, - 1 ) );
  10372. } ).Else( () => {
  10373. const step = 0.01;
  10374. 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 );
  10375. 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 );
  10376. 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 );
  10377. ret.assign( vec3( x, y, z ) );
  10378. } );
  10379. return ret.normalize();
  10380. } );
  10381. class Texture3DNode extends TextureNode {
  10382. static get type() {
  10383. return 'Texture3DNode';
  10384. }
  10385. constructor( value, uvNode = null, levelNode = null ) {
  10386. super( value, uvNode, levelNode );
  10387. this.isTexture3DNode = true;
  10388. }
  10389. getInputType( /*builder*/ ) {
  10390. return 'texture3D';
  10391. }
  10392. getDefaultUV() {
  10393. return vec3( 0.5, 0.5, 0.5 );
  10394. }
  10395. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  10396. setupUV( builder, uvNode ) {
  10397. return uvNode;
  10398. }
  10399. generateUV( builder, uvNode ) {
  10400. return uvNode.build( builder, 'vec3' );
  10401. }
  10402. normal( uvNode ) {
  10403. return normal( { texture: this, uv: uvNode } );
  10404. }
  10405. }
  10406. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  10407. class VolumeNodeMaterial extends NodeMaterial {
  10408. static get type() {
  10409. return 'VolumeNodeMaterial';
  10410. }
  10411. constructor( params = {} ) {
  10412. super();
  10413. this.lights = false;
  10414. this.isVolumeNodeMaterial = true;
  10415. this.testNode = null;
  10416. this.setValues( params );
  10417. }
  10418. setup( builder ) {
  10419. const map = texture3D( this.map, null, 0 );
  10420. const hitBox = Fn( ( { orig, dir } ) => {
  10421. const box_min = vec3( - 0.5 );
  10422. const box_max = vec3( 0.5 );
  10423. const inv_dir = dir.reciprocal();
  10424. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  10425. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  10426. const tmin = min$1( tmin_tmp, tmax_tmp );
  10427. const tmax = max$1( tmin_tmp, tmax_tmp );
  10428. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  10429. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  10430. return vec2( t0, t1 );
  10431. } );
  10432. this.fragmentNode = Fn( () => {
  10433. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  10434. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  10435. const rayDir = vDirection.normalize();
  10436. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  10437. bounds.x.greaterThan( bounds.y ).discard();
  10438. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  10439. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  10440. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  10441. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  10442. delta.divAssign( materialReference( 'steps', 'float' ) );
  10443. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  10444. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  10445. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  10446. if ( this.testNode !== null ) {
  10447. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  10448. } else {
  10449. // default to show surface of mesh
  10450. ac.a.assign( 1 );
  10451. Break();
  10452. }
  10453. p.addAssign( rayDir.mul( delta ) );
  10454. } );
  10455. ac.a.equal( 0 ).discard();
  10456. return vec4( ac );
  10457. } )();
  10458. super.setup( builder );
  10459. }
  10460. }
  10461. class Animation {
  10462. constructor( nodes, info ) {
  10463. this.nodes = nodes;
  10464. this.info = info;
  10465. this._context = self;
  10466. this._animationLoop = null;
  10467. this._requestId = null;
  10468. }
  10469. start() {
  10470. const update = ( time, frame ) => {
  10471. this._requestId = this._context.requestAnimationFrame( update );
  10472. if ( this.info.autoReset === true ) this.info.reset();
  10473. this.nodes.nodeFrame.update();
  10474. this.info.frame = this.nodes.nodeFrame.frameId;
  10475. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  10476. };
  10477. update();
  10478. }
  10479. stop() {
  10480. this._context.cancelAnimationFrame( this._requestId );
  10481. this._requestId = null;
  10482. }
  10483. setAnimationLoop( callback ) {
  10484. this._animationLoop = callback;
  10485. }
  10486. setContext( context ) {
  10487. this._context = context;
  10488. }
  10489. dispose() {
  10490. this.stop();
  10491. }
  10492. }
  10493. class ChainMap {
  10494. constructor() {
  10495. this.weakMap = new WeakMap();
  10496. }
  10497. get( keys ) {
  10498. let map = this.weakMap;
  10499. for ( let i = 0; i < keys.length; i ++ ) {
  10500. map = map.get( keys[ i ] );
  10501. if ( map === undefined ) return undefined;
  10502. }
  10503. return map.get( keys[ keys.length - 1 ] );
  10504. }
  10505. set( keys, value ) {
  10506. let map = this.weakMap;
  10507. for ( let i = 0; i < keys.length; i ++ ) {
  10508. const key = keys[ i ];
  10509. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  10510. map = map.get( key );
  10511. }
  10512. return map.set( keys[ keys.length - 1 ], value );
  10513. }
  10514. delete( keys ) {
  10515. let map = this.weakMap;
  10516. for ( let i = 0; i < keys.length; i ++ ) {
  10517. map = map.get( keys[ i ] );
  10518. if ( map === undefined ) return false;
  10519. }
  10520. return map.delete( keys[ keys.length - 1 ] );
  10521. }
  10522. }
  10523. let _id$8 = 0;
  10524. function getKeys( obj ) {
  10525. const keys = Object.keys( obj );
  10526. let proto = Object.getPrototypeOf( obj );
  10527. while ( proto ) {
  10528. const descriptors = Object.getOwnPropertyDescriptors( proto );
  10529. for ( const key in descriptors ) {
  10530. if ( descriptors[ key ] !== undefined ) {
  10531. const descriptor = descriptors[ key ];
  10532. if ( descriptor && typeof descriptor.get === 'function' ) {
  10533. keys.push( key );
  10534. }
  10535. }
  10536. }
  10537. proto = Object.getPrototypeOf( proto );
  10538. }
  10539. return keys;
  10540. }
  10541. class RenderObject {
  10542. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  10543. this._nodes = nodes;
  10544. this._geometries = geometries;
  10545. this.id = _id$8 ++;
  10546. this.renderer = renderer;
  10547. this.object = object;
  10548. this.material = material;
  10549. this.scene = scene;
  10550. this.camera = camera;
  10551. this.lightsNode = lightsNode;
  10552. this.context = renderContext;
  10553. this.geometry = object.geometry;
  10554. this.version = material.version;
  10555. this.drawRange = null;
  10556. this.attributes = null;
  10557. this.pipeline = null;
  10558. this.vertexBuffers = null;
  10559. this.drawParams = null;
  10560. this.bundle = null;
  10561. this.clippingContext = clippingContext;
  10562. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  10563. this.initialNodesCacheKey = this.getDynamicCacheKey();
  10564. this.initialCacheKey = this.getCacheKey();
  10565. this._nodeBuilderState = null;
  10566. this._bindings = null;
  10567. this._monitor = null;
  10568. this.onDispose = null;
  10569. this.isRenderObject = true;
  10570. this.onMaterialDispose = () => {
  10571. this.dispose();
  10572. };
  10573. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  10574. }
  10575. updateClipping( parent ) {
  10576. this.clippingContext = parent;
  10577. }
  10578. get clippingNeedsUpdate() {
  10579. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  10580. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  10581. return true;
  10582. }
  10583. get hardwareClippingPlanes() {
  10584. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  10585. }
  10586. getNodeBuilderState() {
  10587. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  10588. }
  10589. getMonitor() {
  10590. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  10591. }
  10592. getBindings() {
  10593. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  10594. }
  10595. getIndex() {
  10596. return this._geometries.getIndex( this );
  10597. }
  10598. getIndirect() {
  10599. return this._geometries.getIndirect( this );
  10600. }
  10601. getChainArray() {
  10602. return [ this.object, this.material, this.context, this.lightsNode ];
  10603. }
  10604. setGeometry( geometry ) {
  10605. this.geometry = geometry;
  10606. this.attributes = null;
  10607. }
  10608. getAttributes() {
  10609. if ( this.attributes !== null ) return this.attributes;
  10610. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  10611. const geometry = this.geometry;
  10612. const attributes = [];
  10613. const vertexBuffers = new Set();
  10614. for ( const nodeAttribute of nodeAttributes ) {
  10615. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  10616. if ( attribute === undefined ) continue;
  10617. attributes.push( attribute );
  10618. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  10619. vertexBuffers.add( bufferAttribute );
  10620. }
  10621. this.attributes = attributes;
  10622. this.vertexBuffers = Array.from( vertexBuffers.values() );
  10623. return attributes;
  10624. }
  10625. getVertexBuffers() {
  10626. if ( this.vertexBuffers === null ) this.getAttributes();
  10627. return this.vertexBuffers;
  10628. }
  10629. getDrawParameters() {
  10630. const { object, material, geometry, group, drawRange } = this;
  10631. const drawParams = this.drawParams || ( this.drawParams = {
  10632. vertexCount: 0,
  10633. firstVertex: 0,
  10634. instanceCount: 0,
  10635. firstInstance: 0
  10636. } );
  10637. const index = this.getIndex();
  10638. const hasIndex = ( index !== null );
  10639. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  10640. if ( instanceCount === 0 ) return null;
  10641. drawParams.instanceCount = instanceCount;
  10642. if ( object.isBatchedMesh === true ) return drawParams;
  10643. let rangeFactor = 1;
  10644. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  10645. rangeFactor = 2;
  10646. }
  10647. let firstVertex = drawRange.start * rangeFactor;
  10648. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  10649. if ( group !== null ) {
  10650. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  10651. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  10652. }
  10653. const position = geometry.attributes.position;
  10654. let itemCount = Infinity;
  10655. if ( hasIndex ) {
  10656. itemCount = index.count;
  10657. } else if ( position !== undefined && position !== null ) {
  10658. itemCount = position.count;
  10659. }
  10660. firstVertex = Math.max( firstVertex, 0 );
  10661. lastVertex = Math.min( lastVertex, itemCount );
  10662. const count = lastVertex - firstVertex;
  10663. if ( count < 0 || count === Infinity ) return null;
  10664. drawParams.vertexCount = count;
  10665. drawParams.firstVertex = firstVertex;
  10666. return drawParams;
  10667. }
  10668. getGeometryCacheKey() {
  10669. const { geometry } = this;
  10670. let cacheKey = '';
  10671. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  10672. const attribute = geometry.attributes[ name ];
  10673. cacheKey += name + ',';
  10674. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  10675. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  10676. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  10677. if ( attribute.normalized ) cacheKey += 'n,';
  10678. }
  10679. if ( geometry.index ) {
  10680. cacheKey += 'index,';
  10681. }
  10682. return cacheKey;
  10683. }
  10684. getMaterialCacheKey() {
  10685. const { object, material } = this;
  10686. let cacheKey = material.customProgramCacheKey();
  10687. for ( const property of getKeys( material ) ) {
  10688. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  10689. const value = material[ property ];
  10690. let valueKey;
  10691. if ( value !== null ) {
  10692. // some material values require a formatting
  10693. const type = typeof value;
  10694. if ( type === 'number' ) {
  10695. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  10696. } else if ( type === 'object' ) {
  10697. valueKey = '{';
  10698. if ( value.isTexture ) {
  10699. valueKey += value.mapping;
  10700. }
  10701. valueKey += '}';
  10702. } else {
  10703. valueKey = String( value );
  10704. }
  10705. } else {
  10706. valueKey = String( value );
  10707. }
  10708. cacheKey += /*property + ':' +*/ valueKey + ',';
  10709. }
  10710. cacheKey += this.clippingContextCacheKey + ',';
  10711. if ( object.geometry ) {
  10712. cacheKey += this.getGeometryCacheKey();
  10713. }
  10714. if ( object.skeleton ) {
  10715. cacheKey += object.skeleton.bones.length + ',';
  10716. }
  10717. if ( object.morphTargetInfluences ) {
  10718. cacheKey += object.morphTargetInfluences.length + ',';
  10719. }
  10720. if ( object.isBatchedMesh ) {
  10721. cacheKey += object._matricesTexture.uuid + ',';
  10722. if ( object._colorsTexture !== null ) {
  10723. cacheKey += object._colorsTexture.uuid + ',';
  10724. }
  10725. }
  10726. if ( object.count > 1 ) {
  10727. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  10728. cacheKey += object.uuid + ',';
  10729. }
  10730. cacheKey += object.receiveShadow + ',';
  10731. return hashString( cacheKey );
  10732. }
  10733. get needsGeometryUpdate() {
  10734. return this.geometry.id !== this.object.geometry.id;
  10735. }
  10736. get needsUpdate() {
  10737. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  10738. }
  10739. getDynamicCacheKey() {
  10740. // Environment Nodes Cache Key
  10741. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  10742. if ( this.object.receiveShadow ) {
  10743. cacheKey += 1;
  10744. }
  10745. return cacheKey;
  10746. }
  10747. getCacheKey() {
  10748. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  10749. }
  10750. dispose() {
  10751. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  10752. this.onDispose();
  10753. }
  10754. }
  10755. const chainArray = [];
  10756. class RenderObjects {
  10757. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  10758. this.renderer = renderer;
  10759. this.nodes = nodes;
  10760. this.geometries = geometries;
  10761. this.pipelines = pipelines;
  10762. this.bindings = bindings;
  10763. this.info = info;
  10764. this.chainMaps = {};
  10765. }
  10766. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10767. const chainMap = this.getChainMap( passId );
  10768. // reuse chainArray
  10769. chainArray[ 0 ] = object;
  10770. chainArray[ 1 ] = material;
  10771. chainArray[ 2 ] = renderContext;
  10772. chainArray[ 3 ] = lightsNode;
  10773. let renderObject = chainMap.get( chainArray );
  10774. if ( renderObject === undefined ) {
  10775. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10776. chainMap.set( chainArray, renderObject );
  10777. } else {
  10778. renderObject.updateClipping( clippingContext );
  10779. if ( renderObject.needsGeometryUpdate ) {
  10780. renderObject.setGeometry( object.geometry );
  10781. }
  10782. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  10783. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  10784. renderObject.dispose();
  10785. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10786. } else {
  10787. renderObject.version = material.version;
  10788. }
  10789. }
  10790. }
  10791. return renderObject;
  10792. }
  10793. getChainMap( passId = 'default' ) {
  10794. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  10795. }
  10796. dispose() {
  10797. this.chainMaps = {};
  10798. }
  10799. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10800. const chainMap = this.getChainMap( passId );
  10801. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  10802. renderObject.onDispose = () => {
  10803. this.pipelines.delete( renderObject );
  10804. this.bindings.delete( renderObject );
  10805. this.nodes.delete( renderObject );
  10806. chainMap.delete( renderObject.getChainArray() );
  10807. };
  10808. return renderObject;
  10809. }
  10810. }
  10811. class DataMap {
  10812. constructor() {
  10813. this.data = new WeakMap();
  10814. }
  10815. get( object ) {
  10816. let map = this.data.get( object );
  10817. if ( map === undefined ) {
  10818. map = {};
  10819. this.data.set( object, map );
  10820. }
  10821. return map;
  10822. }
  10823. delete( object ) {
  10824. let map;
  10825. if ( this.data.has( object ) ) {
  10826. map = this.data.get( object );
  10827. this.data.delete( object );
  10828. }
  10829. return map;
  10830. }
  10831. has( object ) {
  10832. return this.data.has( object );
  10833. }
  10834. dispose() {
  10835. this.data = new WeakMap();
  10836. }
  10837. }
  10838. const AttributeType = {
  10839. VERTEX: 1,
  10840. INDEX: 2,
  10841. STORAGE: 3,
  10842. INDIRECT: 4
  10843. };
  10844. // size of a chunk in bytes (STD140 layout)
  10845. const GPU_CHUNK_BYTES = 16;
  10846. // @TODO: Move to src/constants.js
  10847. const BlendColorFactor = 211;
  10848. const OneMinusBlendColorFactor = 212;
  10849. class Attributes extends DataMap {
  10850. constructor( backend ) {
  10851. super();
  10852. this.backend = backend;
  10853. }
  10854. delete( attribute ) {
  10855. const attributeData = super.delete( attribute );
  10856. if ( attributeData !== undefined ) {
  10857. this.backend.destroyAttribute( attribute );
  10858. }
  10859. return attributeData;
  10860. }
  10861. update( attribute, type ) {
  10862. const data = this.get( attribute );
  10863. if ( data.version === undefined ) {
  10864. if ( type === AttributeType.VERTEX ) {
  10865. this.backend.createAttribute( attribute );
  10866. } else if ( type === AttributeType.INDEX ) {
  10867. this.backend.createIndexAttribute( attribute );
  10868. } else if ( type === AttributeType.STORAGE ) {
  10869. this.backend.createStorageAttribute( attribute );
  10870. } else if ( type === AttributeType.INDIRECT ) {
  10871. this.backend.createIndirectStorageAttribute( attribute );
  10872. }
  10873. data.version = this._getBufferAttribute( attribute ).version;
  10874. } else {
  10875. const bufferAttribute = this._getBufferAttribute( attribute );
  10876. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  10877. this.backend.updateAttribute( attribute );
  10878. data.version = bufferAttribute.version;
  10879. }
  10880. }
  10881. }
  10882. _getBufferAttribute( attribute ) {
  10883. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10884. return attribute;
  10885. }
  10886. }
  10887. function arrayNeedsUint32( array ) {
  10888. // assumes larger values usually on last
  10889. for ( let i = array.length - 1; i >= 0; -- i ) {
  10890. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  10891. }
  10892. return false;
  10893. }
  10894. function getWireframeVersion( geometry ) {
  10895. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  10896. }
  10897. function getWireframeIndex( geometry ) {
  10898. const indices = [];
  10899. const geometryIndex = geometry.index;
  10900. const geometryPosition = geometry.attributes.position;
  10901. if ( geometryIndex !== null ) {
  10902. const array = geometryIndex.array;
  10903. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10904. const a = array[ i + 0 ];
  10905. const b = array[ i + 1 ];
  10906. const c = array[ i + 2 ];
  10907. indices.push( a, b, b, c, c, a );
  10908. }
  10909. } else {
  10910. const array = geometryPosition.array;
  10911. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10912. const a = i + 0;
  10913. const b = i + 1;
  10914. const c = i + 2;
  10915. indices.push( a, b, b, c, c, a );
  10916. }
  10917. }
  10918. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10919. attribute.version = getWireframeVersion( geometry );
  10920. return attribute;
  10921. }
  10922. class Geometries extends DataMap {
  10923. constructor( attributes, info ) {
  10924. super();
  10925. this.attributes = attributes;
  10926. this.info = info;
  10927. this.wireframes = new WeakMap();
  10928. this.attributeCall = new WeakMap();
  10929. }
  10930. has( renderObject ) {
  10931. const geometry = renderObject.geometry;
  10932. return super.has( geometry ) && this.get( geometry ).initialized === true;
  10933. }
  10934. updateForRender( renderObject ) {
  10935. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  10936. this.updateAttributes( renderObject );
  10937. }
  10938. initGeometry( renderObject ) {
  10939. const geometry = renderObject.geometry;
  10940. const geometryData = this.get( geometry );
  10941. geometryData.initialized = true;
  10942. this.info.memory.geometries ++;
  10943. const onDispose = () => {
  10944. this.info.memory.geometries --;
  10945. const index = geometry.index;
  10946. const geometryAttributes = renderObject.getAttributes();
  10947. if ( index !== null ) {
  10948. this.attributes.delete( index );
  10949. }
  10950. for ( const geometryAttribute of geometryAttributes ) {
  10951. this.attributes.delete( geometryAttribute );
  10952. }
  10953. const wireframeAttribute = this.wireframes.get( geometry );
  10954. if ( wireframeAttribute !== undefined ) {
  10955. this.attributes.delete( wireframeAttribute );
  10956. }
  10957. geometry.removeEventListener( 'dispose', onDispose );
  10958. };
  10959. geometry.addEventListener( 'dispose', onDispose );
  10960. }
  10961. updateAttributes( renderObject ) {
  10962. // attributes
  10963. const attributes = renderObject.getAttributes();
  10964. for ( const attribute of attributes ) {
  10965. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  10966. this.updateAttribute( attribute, AttributeType.STORAGE );
  10967. } else {
  10968. this.updateAttribute( attribute, AttributeType.VERTEX );
  10969. }
  10970. }
  10971. // indexes
  10972. const index = this.getIndex( renderObject );
  10973. if ( index !== null ) {
  10974. this.updateAttribute( index, AttributeType.INDEX );
  10975. }
  10976. // indirect
  10977. const indirect = renderObject.geometry.indirect;
  10978. if ( indirect !== null ) {
  10979. this.updateAttribute( indirect, AttributeType.INDIRECT );
  10980. }
  10981. }
  10982. updateAttribute( attribute, type ) {
  10983. const callId = this.info.render.calls;
  10984. if ( ! attribute.isInterleavedBufferAttribute ) {
  10985. if ( this.attributeCall.get( attribute ) !== callId ) {
  10986. this.attributes.update( attribute, type );
  10987. this.attributeCall.set( attribute, callId );
  10988. }
  10989. } else {
  10990. if ( this.attributeCall.get( attribute ) === undefined ) {
  10991. this.attributes.update( attribute, type );
  10992. this.attributeCall.set( attribute, callId );
  10993. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  10994. this.attributes.update( attribute, type );
  10995. this.attributeCall.set( attribute.data, callId );
  10996. this.attributeCall.set( attribute, callId );
  10997. }
  10998. }
  10999. }
  11000. getIndirect( renderObject ) {
  11001. return renderObject.geometry.indirect;
  11002. }
  11003. getIndex( renderObject ) {
  11004. const { geometry, material } = renderObject;
  11005. let index = geometry.index;
  11006. if ( material.wireframe === true ) {
  11007. const wireframes = this.wireframes;
  11008. let wireframeAttribute = wireframes.get( geometry );
  11009. if ( wireframeAttribute === undefined ) {
  11010. wireframeAttribute = getWireframeIndex( geometry );
  11011. wireframes.set( geometry, wireframeAttribute );
  11012. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  11013. this.attributes.delete( wireframeAttribute );
  11014. wireframeAttribute = getWireframeIndex( geometry );
  11015. wireframes.set( geometry, wireframeAttribute );
  11016. }
  11017. index = wireframeAttribute;
  11018. }
  11019. return index;
  11020. }
  11021. }
  11022. class Info {
  11023. constructor() {
  11024. this.autoReset = true;
  11025. this.frame = 0;
  11026. this.calls = 0;
  11027. this.render = {
  11028. calls: 0,
  11029. frameCalls: 0,
  11030. drawCalls: 0,
  11031. triangles: 0,
  11032. points: 0,
  11033. lines: 0,
  11034. timestamp: 0,
  11035. previousFrameCalls: 0,
  11036. timestampCalls: 0
  11037. };
  11038. this.compute = {
  11039. calls: 0,
  11040. frameCalls: 0,
  11041. timestamp: 0,
  11042. previousFrameCalls: 0,
  11043. timestampCalls: 0
  11044. };
  11045. this.memory = {
  11046. geometries: 0,
  11047. textures: 0
  11048. };
  11049. }
  11050. update( object, count, instanceCount ) {
  11051. this.render.drawCalls ++;
  11052. if ( object.isMesh || object.isSprite ) {
  11053. this.render.triangles += instanceCount * ( count / 3 );
  11054. } else if ( object.isPoints ) {
  11055. this.render.points += instanceCount * count;
  11056. } else if ( object.isLineSegments ) {
  11057. this.render.lines += instanceCount * ( count / 2 );
  11058. } else if ( object.isLine ) {
  11059. this.render.lines += instanceCount * ( count - 1 );
  11060. } else {
  11061. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  11062. }
  11063. }
  11064. updateTimestamp( type, time ) {
  11065. if ( this[ type ].timestampCalls === 0 ) {
  11066. this[ type ].timestamp = 0;
  11067. }
  11068. this[ type ].timestamp += time;
  11069. this[ type ].timestampCalls ++;
  11070. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  11071. this[ type ].timestampCalls = 0;
  11072. }
  11073. }
  11074. reset() {
  11075. const previousRenderFrameCalls = this.render.frameCalls;
  11076. this.render.previousFrameCalls = previousRenderFrameCalls;
  11077. const previousComputeFrameCalls = this.compute.frameCalls;
  11078. this.compute.previousFrameCalls = previousComputeFrameCalls;
  11079. this.render.drawCalls = 0;
  11080. this.render.frameCalls = 0;
  11081. this.compute.frameCalls = 0;
  11082. this.render.triangles = 0;
  11083. this.render.points = 0;
  11084. this.render.lines = 0;
  11085. }
  11086. dispose() {
  11087. this.reset();
  11088. this.calls = 0;
  11089. this.render.calls = 0;
  11090. this.compute.calls = 0;
  11091. this.render.timestamp = 0;
  11092. this.compute.timestamp = 0;
  11093. this.memory.geometries = 0;
  11094. this.memory.textures = 0;
  11095. }
  11096. }
  11097. class Pipeline {
  11098. constructor( cacheKey ) {
  11099. this.cacheKey = cacheKey;
  11100. this.usedTimes = 0;
  11101. }
  11102. }
  11103. class RenderPipeline extends Pipeline {
  11104. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  11105. super( cacheKey );
  11106. this.vertexProgram = vertexProgram;
  11107. this.fragmentProgram = fragmentProgram;
  11108. }
  11109. }
  11110. class ComputePipeline extends Pipeline {
  11111. constructor( cacheKey, computeProgram ) {
  11112. super( cacheKey );
  11113. this.computeProgram = computeProgram;
  11114. this.isComputePipeline = true;
  11115. }
  11116. }
  11117. let _id$7 = 0;
  11118. class ProgrammableStage {
  11119. constructor( code, type, transforms = null, attributes = null ) {
  11120. this.id = _id$7 ++;
  11121. this.code = code;
  11122. this.stage = type;
  11123. this.transforms = transforms;
  11124. this.attributes = attributes;
  11125. this.usedTimes = 0;
  11126. }
  11127. }
  11128. class Pipelines extends DataMap {
  11129. constructor( backend, nodes ) {
  11130. super();
  11131. this.backend = backend;
  11132. this.nodes = nodes;
  11133. this.bindings = null; // set by the bindings
  11134. this.caches = new Map();
  11135. this.programs = {
  11136. vertex: new Map(),
  11137. fragment: new Map(),
  11138. compute: new Map()
  11139. };
  11140. }
  11141. getForCompute( computeNode, bindings ) {
  11142. const { backend } = this;
  11143. const data = this.get( computeNode );
  11144. if ( this._needsComputeUpdate( computeNode ) ) {
  11145. const previousPipeline = data.pipeline;
  11146. if ( previousPipeline ) {
  11147. previousPipeline.usedTimes --;
  11148. previousPipeline.computeProgram.usedTimes --;
  11149. }
  11150. // get shader
  11151. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  11152. // programmable stage
  11153. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  11154. if ( stageCompute === undefined ) {
  11155. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  11156. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  11157. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  11158. backend.createProgram( stageCompute );
  11159. }
  11160. // determine compute pipeline
  11161. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  11162. let pipeline = this.caches.get( cacheKey );
  11163. if ( pipeline === undefined ) {
  11164. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  11165. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  11166. }
  11167. // keep track of all used times
  11168. pipeline.usedTimes ++;
  11169. stageCompute.usedTimes ++;
  11170. //
  11171. data.version = computeNode.version;
  11172. data.pipeline = pipeline;
  11173. }
  11174. return data.pipeline;
  11175. }
  11176. getForRender( renderObject, promises = null ) {
  11177. const { backend } = this;
  11178. const data = this.get( renderObject );
  11179. if ( this._needsRenderUpdate( renderObject ) ) {
  11180. const previousPipeline = data.pipeline;
  11181. if ( previousPipeline ) {
  11182. previousPipeline.usedTimes --;
  11183. previousPipeline.vertexProgram.usedTimes --;
  11184. previousPipeline.fragmentProgram.usedTimes --;
  11185. }
  11186. // get shader
  11187. const nodeBuilderState = renderObject.getNodeBuilderState();
  11188. // programmable stages
  11189. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  11190. if ( stageVertex === undefined ) {
  11191. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  11192. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  11193. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  11194. backend.createProgram( stageVertex );
  11195. }
  11196. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  11197. if ( stageFragment === undefined ) {
  11198. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  11199. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  11200. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  11201. backend.createProgram( stageFragment );
  11202. }
  11203. // determine render pipeline
  11204. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  11205. let pipeline = this.caches.get( cacheKey );
  11206. if ( pipeline === undefined ) {
  11207. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  11208. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  11209. } else {
  11210. renderObject.pipeline = pipeline;
  11211. }
  11212. // keep track of all used times
  11213. pipeline.usedTimes ++;
  11214. stageVertex.usedTimes ++;
  11215. stageFragment.usedTimes ++;
  11216. //
  11217. data.pipeline = pipeline;
  11218. }
  11219. return data.pipeline;
  11220. }
  11221. delete( object ) {
  11222. const pipeline = this.get( object ).pipeline;
  11223. if ( pipeline ) {
  11224. // pipeline
  11225. pipeline.usedTimes --;
  11226. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  11227. // programs
  11228. if ( pipeline.isComputePipeline ) {
  11229. pipeline.computeProgram.usedTimes --;
  11230. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  11231. } else {
  11232. pipeline.fragmentProgram.usedTimes --;
  11233. pipeline.vertexProgram.usedTimes --;
  11234. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  11235. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  11236. }
  11237. }
  11238. return super.delete( object );
  11239. }
  11240. dispose() {
  11241. super.dispose();
  11242. this.caches = new Map();
  11243. this.programs = {
  11244. vertex: new Map(),
  11245. fragment: new Map(),
  11246. compute: new Map()
  11247. };
  11248. }
  11249. updateForRender( renderObject ) {
  11250. this.getForRender( renderObject );
  11251. }
  11252. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  11253. // check for existing pipeline
  11254. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  11255. let pipeline = this.caches.get( cacheKey );
  11256. if ( pipeline === undefined ) {
  11257. pipeline = new ComputePipeline( cacheKey, stageCompute );
  11258. this.caches.set( cacheKey, pipeline );
  11259. this.backend.createComputePipeline( pipeline, bindings );
  11260. }
  11261. return pipeline;
  11262. }
  11263. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  11264. // check for existing pipeline
  11265. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  11266. let pipeline = this.caches.get( cacheKey );
  11267. if ( pipeline === undefined ) {
  11268. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  11269. this.caches.set( cacheKey, pipeline );
  11270. renderObject.pipeline = pipeline;
  11271. this.backend.createRenderPipeline( renderObject, promises );
  11272. }
  11273. return pipeline;
  11274. }
  11275. _getComputeCacheKey( computeNode, stageCompute ) {
  11276. return computeNode.id + ',' + stageCompute.id;
  11277. }
  11278. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  11279. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  11280. }
  11281. _releasePipeline( pipeline ) {
  11282. this.caches.delete( pipeline.cacheKey );
  11283. }
  11284. _releaseProgram( program ) {
  11285. const code = program.code;
  11286. const stage = program.stage;
  11287. this.programs[ stage ].delete( code );
  11288. }
  11289. _needsComputeUpdate( computeNode ) {
  11290. const data = this.get( computeNode );
  11291. return data.pipeline === undefined || data.version !== computeNode.version;
  11292. }
  11293. _needsRenderUpdate( renderObject ) {
  11294. const data = this.get( renderObject );
  11295. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  11296. }
  11297. }
  11298. class Bindings extends DataMap {
  11299. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  11300. super();
  11301. this.backend = backend;
  11302. this.textures = textures;
  11303. this.pipelines = pipelines;
  11304. this.attributes = attributes;
  11305. this.nodes = nodes;
  11306. this.info = info;
  11307. this.pipelines.bindings = this; // assign bindings to pipelines
  11308. }
  11309. getForRender( renderObject ) {
  11310. const bindings = renderObject.getBindings();
  11311. for ( const bindGroup of bindings ) {
  11312. const groupData = this.get( bindGroup );
  11313. if ( groupData.bindGroup === undefined ) {
  11314. // each object defines an array of bindings (ubos, textures, samplers etc.)
  11315. this._init( bindGroup );
  11316. this.backend.createBindings( bindGroup, bindings, 0 );
  11317. groupData.bindGroup = bindGroup;
  11318. }
  11319. }
  11320. return bindings;
  11321. }
  11322. getForCompute( computeNode ) {
  11323. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  11324. for ( const bindGroup of bindings ) {
  11325. const groupData = this.get( bindGroup );
  11326. if ( groupData.bindGroup === undefined ) {
  11327. this._init( bindGroup );
  11328. this.backend.createBindings( bindGroup, bindings, 0 );
  11329. groupData.bindGroup = bindGroup;
  11330. }
  11331. }
  11332. return bindings;
  11333. }
  11334. updateForCompute( computeNode ) {
  11335. this._updateBindings( this.getForCompute( computeNode ) );
  11336. }
  11337. updateForRender( renderObject ) {
  11338. this._updateBindings( this.getForRender( renderObject ) );
  11339. }
  11340. _updateBindings( bindings ) {
  11341. for ( const bindGroup of bindings ) {
  11342. this._update( bindGroup, bindings );
  11343. }
  11344. }
  11345. _init( bindGroup ) {
  11346. for ( const binding of bindGroup.bindings ) {
  11347. if ( binding.isSampledTexture ) {
  11348. this.textures.updateTexture( binding.texture );
  11349. } else if ( binding.isStorageBuffer ) {
  11350. const attribute = binding.attribute;
  11351. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  11352. this.attributes.update( attribute, attributeType );
  11353. }
  11354. }
  11355. }
  11356. _update( bindGroup, bindings ) {
  11357. const { backend } = this;
  11358. let needsBindingsUpdate = false;
  11359. let cacheBindings = true;
  11360. let cacheIndex = 0;
  11361. let version = 0;
  11362. // iterate over all bindings and check if buffer updates or a new binding group is required
  11363. for ( const binding of bindGroup.bindings ) {
  11364. if ( binding.isNodeUniformsGroup ) {
  11365. const updated = this.nodes.updateGroup( binding );
  11366. if ( ! updated ) continue;
  11367. }
  11368. if ( binding.isUniformBuffer ) {
  11369. const updated = binding.update();
  11370. if ( updated ) {
  11371. backend.updateBinding( binding );
  11372. }
  11373. } else if ( binding.isSampler ) {
  11374. binding.update();
  11375. } else if ( binding.isSampledTexture ) {
  11376. const texturesTextureData = this.textures.get( binding.texture );
  11377. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  11378. const updated = binding.update();
  11379. const texture = binding.texture;
  11380. if ( updated ) {
  11381. this.textures.updateTexture( texture );
  11382. }
  11383. const textureData = backend.get( texture );
  11384. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  11385. cacheBindings = false;
  11386. } else {
  11387. cacheIndex = cacheIndex * 10 + texture.id;
  11388. version += texture.version;
  11389. }
  11390. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  11391. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  11392. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  11393. this.textures.updateTexture( texture );
  11394. needsBindingsUpdate = true;
  11395. }
  11396. if ( texture.isStorageTexture === true ) {
  11397. const textureData = this.get( texture );
  11398. if ( binding.store === true ) {
  11399. textureData.needsMipmap = true;
  11400. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  11401. this.backend.generateMipmaps( texture );
  11402. textureData.needsMipmap = false;
  11403. }
  11404. }
  11405. }
  11406. }
  11407. if ( needsBindingsUpdate === true ) {
  11408. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  11409. }
  11410. }
  11411. }
  11412. function painterSortStable( a, b ) {
  11413. if ( a.groupOrder !== b.groupOrder ) {
  11414. return a.groupOrder - b.groupOrder;
  11415. } else if ( a.renderOrder !== b.renderOrder ) {
  11416. return a.renderOrder - b.renderOrder;
  11417. } else if ( a.material.id !== b.material.id ) {
  11418. return a.material.id - b.material.id;
  11419. } else if ( a.z !== b.z ) {
  11420. return a.z - b.z;
  11421. } else {
  11422. return a.id - b.id;
  11423. }
  11424. }
  11425. function reversePainterSortStable( a, b ) {
  11426. if ( a.groupOrder !== b.groupOrder ) {
  11427. return a.groupOrder - b.groupOrder;
  11428. } else if ( a.renderOrder !== b.renderOrder ) {
  11429. return a.renderOrder - b.renderOrder;
  11430. } else if ( a.z !== b.z ) {
  11431. return b.z - a.z;
  11432. } else {
  11433. return a.id - b.id;
  11434. }
  11435. }
  11436. function needsDoublePass( material ) {
  11437. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  11438. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  11439. }
  11440. class RenderList {
  11441. constructor( lighting, scene, camera ) {
  11442. this.renderItems = [];
  11443. this.renderItemsIndex = 0;
  11444. this.opaque = [];
  11445. this.transparentDoublePass = [];
  11446. this.transparent = [];
  11447. this.bundles = [];
  11448. this.lightsNode = lighting.getNode( scene, camera );
  11449. this.lightsArray = [];
  11450. this.scene = scene;
  11451. this.camera = camera;
  11452. this.occlusionQueryCount = 0;
  11453. }
  11454. begin() {
  11455. this.renderItemsIndex = 0;
  11456. this.opaque.length = 0;
  11457. this.transparentDoublePass.length = 0;
  11458. this.transparent.length = 0;
  11459. this.bundles.length = 0;
  11460. this.lightsArray.length = 0;
  11461. this.occlusionQueryCount = 0;
  11462. return this;
  11463. }
  11464. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11465. let renderItem = this.renderItems[ this.renderItemsIndex ];
  11466. if ( renderItem === undefined ) {
  11467. renderItem = {
  11468. id: object.id,
  11469. object: object,
  11470. geometry: geometry,
  11471. material: material,
  11472. groupOrder: groupOrder,
  11473. renderOrder: object.renderOrder,
  11474. z: z,
  11475. group: group,
  11476. clippingContext: clippingContext
  11477. };
  11478. this.renderItems[ this.renderItemsIndex ] = renderItem;
  11479. } else {
  11480. renderItem.id = object.id;
  11481. renderItem.object = object;
  11482. renderItem.geometry = geometry;
  11483. renderItem.material = material;
  11484. renderItem.groupOrder = groupOrder;
  11485. renderItem.renderOrder = object.renderOrder;
  11486. renderItem.z = z;
  11487. renderItem.group = group;
  11488. renderItem.clippingContext = clippingContext;
  11489. }
  11490. this.renderItemsIndex ++;
  11491. return renderItem;
  11492. }
  11493. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11494. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11495. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  11496. if ( material.transparent === true || material.transmission > 0 ) {
  11497. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  11498. this.transparent.push( renderItem );
  11499. } else {
  11500. this.opaque.push( renderItem );
  11501. }
  11502. }
  11503. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11504. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11505. if ( material.transparent === true || material.transmission > 0 ) {
  11506. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  11507. this.transparent.unshift( renderItem );
  11508. } else {
  11509. this.opaque.unshift( renderItem );
  11510. }
  11511. }
  11512. pushBundle( group ) {
  11513. this.bundles.push( group );
  11514. }
  11515. pushLight( light ) {
  11516. this.lightsArray.push( light );
  11517. }
  11518. sort( customOpaqueSort, customTransparentSort ) {
  11519. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  11520. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  11521. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  11522. }
  11523. finish() {
  11524. // update lights
  11525. this.lightsNode.setLights( this.lightsArray );
  11526. // Clear references from inactive renderItems in the list
  11527. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  11528. const renderItem = this.renderItems[ i ];
  11529. if ( renderItem.id === null ) break;
  11530. renderItem.id = null;
  11531. renderItem.object = null;
  11532. renderItem.geometry = null;
  11533. renderItem.material = null;
  11534. renderItem.groupOrder = null;
  11535. renderItem.renderOrder = null;
  11536. renderItem.z = null;
  11537. renderItem.group = null;
  11538. renderItem.clippingContext = null;
  11539. }
  11540. }
  11541. }
  11542. class RenderLists {
  11543. constructor( lighting ) {
  11544. this.lighting = lighting;
  11545. this.lists = new ChainMap();
  11546. }
  11547. get( scene, camera ) {
  11548. const lists = this.lists;
  11549. const keys = [ scene, camera ];
  11550. let list = lists.get( keys );
  11551. if ( list === undefined ) {
  11552. list = new RenderList( this.lighting, scene, camera );
  11553. lists.set( keys, list );
  11554. }
  11555. return list;
  11556. }
  11557. dispose() {
  11558. this.lists = new ChainMap();
  11559. }
  11560. }
  11561. let id = 0;
  11562. class RenderContext {
  11563. constructor() {
  11564. this.id = id ++;
  11565. this.color = true;
  11566. this.clearColor = true;
  11567. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  11568. this.depth = true;
  11569. this.clearDepth = true;
  11570. this.clearDepthValue = 1;
  11571. this.stencil = false;
  11572. this.clearStencil = true;
  11573. this.clearStencilValue = 1;
  11574. this.viewport = false;
  11575. this.viewportValue = new Vector4();
  11576. this.scissor = false;
  11577. this.scissorValue = new Vector4();
  11578. this.textures = null;
  11579. this.depthTexture = null;
  11580. this.activeCubeFace = 0;
  11581. this.sampleCount = 1;
  11582. this.width = 0;
  11583. this.height = 0;
  11584. this.isRenderContext = true;
  11585. }
  11586. getCacheKey() {
  11587. return getCacheKey( this );
  11588. }
  11589. }
  11590. function getCacheKey( renderContext ) {
  11591. const { textures, activeCubeFace } = renderContext;
  11592. const values = [ activeCubeFace ];
  11593. for ( const texture of textures ) {
  11594. values.push( texture.id );
  11595. }
  11596. return hashArray( values );
  11597. }
  11598. class RenderContexts {
  11599. constructor() {
  11600. this.chainMaps = {};
  11601. }
  11602. get( scene, camera, renderTarget = null ) {
  11603. const chainKey = [ scene, camera ];
  11604. let attachmentState;
  11605. if ( renderTarget === null ) {
  11606. attachmentState = 'default';
  11607. } else {
  11608. const format = renderTarget.texture.format;
  11609. const count = renderTarget.textures.length;
  11610. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  11611. }
  11612. const chainMap = this.getChainMap( attachmentState );
  11613. let renderState = chainMap.get( chainKey );
  11614. if ( renderState === undefined ) {
  11615. renderState = new RenderContext();
  11616. chainMap.set( chainKey, renderState );
  11617. }
  11618. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11619. return renderState;
  11620. }
  11621. getChainMap( attachmentState ) {
  11622. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  11623. }
  11624. dispose() {
  11625. this.chainMaps = {};
  11626. }
  11627. }
  11628. const _size$3 = /*@__PURE__*/ new Vector3();
  11629. class Textures extends DataMap {
  11630. constructor( renderer, backend, info ) {
  11631. super();
  11632. this.renderer = renderer;
  11633. this.backend = backend;
  11634. this.info = info;
  11635. }
  11636. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  11637. const renderTargetData = this.get( renderTarget );
  11638. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11639. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  11640. const textures = renderTarget.textures;
  11641. const size = this.getSize( textures[ 0 ] );
  11642. const mipWidth = size.width >> activeMipmapLevel;
  11643. const mipHeight = size.height >> activeMipmapLevel;
  11644. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  11645. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  11646. let textureNeedsUpdate = false;
  11647. if ( depthTexture === undefined && useDepthTexture ) {
  11648. depthTexture = new DepthTexture();
  11649. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  11650. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  11651. depthTexture.image.width = mipWidth;
  11652. depthTexture.image.height = mipHeight;
  11653. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  11654. }
  11655. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  11656. textureNeedsUpdate = true;
  11657. if ( depthTexture ) {
  11658. depthTexture.needsUpdate = true;
  11659. depthTexture.image.width = mipWidth;
  11660. depthTexture.image.height = mipHeight;
  11661. }
  11662. }
  11663. renderTargetData.width = size.width;
  11664. renderTargetData.height = size.height;
  11665. renderTargetData.textures = textures;
  11666. renderTargetData.depthTexture = depthTexture || null;
  11667. renderTargetData.depth = renderTarget.depthBuffer;
  11668. renderTargetData.stencil = renderTarget.stencilBuffer;
  11669. renderTargetData.renderTarget = renderTarget;
  11670. if ( renderTargetData.sampleCount !== sampleCount ) {
  11671. textureNeedsUpdate = true;
  11672. if ( depthTexture ) {
  11673. depthTexture.needsUpdate = true;
  11674. }
  11675. renderTargetData.sampleCount = sampleCount;
  11676. }
  11677. //
  11678. const options = { sampleCount };
  11679. for ( let i = 0; i < textures.length; i ++ ) {
  11680. const texture = textures[ i ];
  11681. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  11682. this.updateTexture( texture, options );
  11683. }
  11684. if ( depthTexture ) {
  11685. this.updateTexture( depthTexture, options );
  11686. }
  11687. // dispose handler
  11688. if ( renderTargetData.initialized !== true ) {
  11689. renderTargetData.initialized = true;
  11690. // dispose
  11691. const onDispose = () => {
  11692. renderTarget.removeEventListener( 'dispose', onDispose );
  11693. for ( let i = 0; i < textures.length; i ++ ) {
  11694. this._destroyTexture( textures[ i ] );
  11695. }
  11696. if ( depthTexture ) {
  11697. this._destroyTexture( depthTexture );
  11698. }
  11699. this.delete( renderTarget );
  11700. };
  11701. renderTarget.addEventListener( 'dispose', onDispose );
  11702. }
  11703. }
  11704. updateTexture( texture, options = {} ) {
  11705. const textureData = this.get( texture );
  11706. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  11707. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  11708. const backend = this.backend;
  11709. if ( isRenderTarget && textureData.initialized === true ) {
  11710. // it's an update
  11711. backend.destroySampler( texture );
  11712. backend.destroyTexture( texture );
  11713. }
  11714. //
  11715. if ( texture.isFramebufferTexture ) {
  11716. const renderTarget = this.renderer.getRenderTarget();
  11717. if ( renderTarget ) {
  11718. texture.type = renderTarget.texture.type;
  11719. } else {
  11720. texture.type = UnsignedByteType;
  11721. }
  11722. }
  11723. //
  11724. const { width, height, depth } = this.getSize( texture );
  11725. options.width = width;
  11726. options.height = height;
  11727. options.depth = depth;
  11728. options.needsMipmaps = this.needsMipmaps( texture );
  11729. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  11730. //
  11731. if ( isRenderTarget || texture.isStorageTexture === true ) {
  11732. backend.createSampler( texture );
  11733. backend.createTexture( texture, options );
  11734. textureData.generation = texture.version;
  11735. } else {
  11736. const needsCreate = textureData.initialized !== true;
  11737. if ( needsCreate ) backend.createSampler( texture );
  11738. if ( texture.version > 0 ) {
  11739. const image = texture.image;
  11740. if ( image === undefined ) {
  11741. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  11742. } else if ( image.complete === false ) {
  11743. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  11744. } else {
  11745. if ( texture.images ) {
  11746. const images = [];
  11747. for ( const image of texture.images ) {
  11748. images.push( image );
  11749. }
  11750. options.images = images;
  11751. } else {
  11752. options.image = image;
  11753. }
  11754. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  11755. backend.createTexture( texture, options );
  11756. textureData.isDefaultTexture = false;
  11757. textureData.generation = texture.version;
  11758. }
  11759. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  11760. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  11761. }
  11762. } else {
  11763. // async update
  11764. backend.createDefaultTexture( texture );
  11765. textureData.isDefaultTexture = true;
  11766. textureData.generation = texture.version;
  11767. }
  11768. }
  11769. // dispose handler
  11770. if ( textureData.initialized !== true ) {
  11771. textureData.initialized = true;
  11772. textureData.generation = texture.version;
  11773. //
  11774. this.info.memory.textures ++;
  11775. // dispose
  11776. const onDispose = () => {
  11777. texture.removeEventListener( 'dispose', onDispose );
  11778. this._destroyTexture( texture );
  11779. this.info.memory.textures --;
  11780. };
  11781. texture.addEventListener( 'dispose', onDispose );
  11782. }
  11783. //
  11784. textureData.version = texture.version;
  11785. }
  11786. getSize( texture, target = _size$3 ) {
  11787. let image = texture.images ? texture.images[ 0 ] : texture.image;
  11788. if ( image ) {
  11789. if ( image.image !== undefined ) image = image.image;
  11790. target.width = image.width || 1;
  11791. target.height = image.height || 1;
  11792. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  11793. } else {
  11794. target.width = target.height = target.depth = 1;
  11795. }
  11796. return target;
  11797. }
  11798. getMipLevels( texture, width, height ) {
  11799. let mipLevelCount;
  11800. if ( texture.isCompressedTexture ) {
  11801. if ( texture.mipmaps ) {
  11802. mipLevelCount = texture.mipmaps.length;
  11803. } else {
  11804. mipLevelCount = 1;
  11805. }
  11806. } else {
  11807. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  11808. }
  11809. return mipLevelCount;
  11810. }
  11811. needsMipmaps( texture ) {
  11812. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  11813. }
  11814. isEnvironmentTexture( texture ) {
  11815. const mapping = texture.mapping;
  11816. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  11817. }
  11818. _destroyTexture( texture ) {
  11819. this.backend.destroySampler( texture );
  11820. this.backend.destroyTexture( texture );
  11821. this.delete( texture );
  11822. }
  11823. }
  11824. class Color4 extends Color {
  11825. constructor( r, g, b, a = 1 ) {
  11826. super( r, g, b );
  11827. this.a = a;
  11828. }
  11829. set( r, g, b, a = 1 ) {
  11830. this.a = a;
  11831. return super.set( r, g, b );
  11832. }
  11833. copy( color ) {
  11834. if ( color.a !== undefined ) this.a = color.a;
  11835. return super.copy( color );
  11836. }
  11837. clone() {
  11838. return new this.constructor( this.r, this.g, this.b, this.a );
  11839. }
  11840. }
  11841. /**
  11842. * Special version of {@link PropertyNode} which is used for parameters.
  11843. *
  11844. * @augments PropertyNode
  11845. */
  11846. class ParameterNode extends PropertyNode {
  11847. static get type() {
  11848. return 'ParameterNode';
  11849. }
  11850. /**
  11851. * Constructs a new parameter node.
  11852. *
  11853. * @param {String} nodeType - The type of the node.
  11854. * @param {String?} [name=null] - The name of the parameter in the shader.
  11855. */
  11856. constructor( nodeType, name = null ) {
  11857. super( nodeType, name );
  11858. /**
  11859. * This flag can be used for type testing.
  11860. *
  11861. * @type {Boolean}
  11862. * @readonly
  11863. * @default true
  11864. */
  11865. this.isParameterNode = true;
  11866. }
  11867. getHash() {
  11868. return this.uuid;
  11869. }
  11870. generate() {
  11871. return this.name;
  11872. }
  11873. }
  11874. /**
  11875. *
  11876. * @param {string} type
  11877. * @param {string?} [name=null]
  11878. * @returns {ShaderNodeObject}
  11879. */
  11880. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  11881. /**
  11882. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  11883. * They are usually needed in cases like `If`, `Else`.
  11884. *
  11885. * @augments Node
  11886. */
  11887. class StackNode extends Node {
  11888. static get type() {
  11889. return 'StackNode';
  11890. }
  11891. /**
  11892. * Constructs a new stack node.
  11893. *
  11894. * @param {StackNode?} [parent=null] - The parent stack node.
  11895. */
  11896. constructor( parent = null ) {
  11897. super();
  11898. /**
  11899. * List of nodes.
  11900. *
  11901. * @type {Array<Node>}
  11902. */
  11903. this.nodes = [];
  11904. /**
  11905. * The output node.
  11906. *
  11907. * @type {Node?}
  11908. * @default null
  11909. */
  11910. this.outputNode = null;
  11911. /**
  11912. * The parent stack node.
  11913. *
  11914. * @type {StackNode}
  11915. * @default null
  11916. */
  11917. this.parent = parent;
  11918. /**
  11919. * The current conditional node.
  11920. *
  11921. * @private
  11922. * @type {ConditionalNode}
  11923. * @default null
  11924. */
  11925. this._currentCond = null;
  11926. /**
  11927. * This flag can be used for type testing.
  11928. *
  11929. * @type {Boolean}
  11930. * @readonly
  11931. * @default true
  11932. */
  11933. this.isStackNode = true;
  11934. }
  11935. getNodeType( builder ) {
  11936. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  11937. }
  11938. /**
  11939. * Adds a node to this stack.
  11940. *
  11941. * @param {Node} node - The node to add.
  11942. * @return {StackNode} A reference to this stack node.
  11943. */
  11944. add( node ) {
  11945. this.nodes.push( node );
  11946. return this;
  11947. }
  11948. /**
  11949. * Represent an `if` statement in TSL.
  11950. *
  11951. * @param {Node} boolNode - Represents the condition.
  11952. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11953. * @return {StackNode} A reference to this stack node.
  11954. */
  11955. If( boolNode, method ) {
  11956. const methodNode = new ShaderNode( method );
  11957. this._currentCond = select( boolNode, methodNode );
  11958. return this.add( this._currentCond );
  11959. }
  11960. /**
  11961. * Represent an `elseif` statement in TSL.
  11962. *
  11963. * @param {Node} boolNode - Represents the condition.
  11964. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11965. * @return {StackNode} A reference to this stack node.
  11966. */
  11967. ElseIf( boolNode, method ) {
  11968. const methodNode = new ShaderNode( method );
  11969. const ifNode = select( boolNode, methodNode );
  11970. this._currentCond.elseNode = ifNode;
  11971. this._currentCond = ifNode;
  11972. return this;
  11973. }
  11974. /**
  11975. * Represent an `else` statement in TSL.
  11976. *
  11977. * @param {Function} method - TSL code which is executed in the `else` case.
  11978. * @return {StackNode} A reference to this stack node.
  11979. */
  11980. Else( method ) {
  11981. this._currentCond.elseNode = new ShaderNode( method );
  11982. return this;
  11983. }
  11984. build( builder, ...params ) {
  11985. const previousStack = getCurrentStack();
  11986. setCurrentStack( this );
  11987. for ( const node of this.nodes ) {
  11988. node.build( builder, 'void' );
  11989. }
  11990. setCurrentStack( previousStack );
  11991. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  11992. }
  11993. //
  11994. else( ...params ) { // @deprecated, r168
  11995. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  11996. return this.Else( ...params );
  11997. }
  11998. elseif( ...params ) { // @deprecated, r168
  11999. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  12000. return this.ElseIf( ...params );
  12001. }
  12002. }
  12003. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  12004. /**
  12005. * This node can be used to define multiple outputs in a shader programs.
  12006. *
  12007. * @augments Node
  12008. */
  12009. class OutputStructNode extends Node {
  12010. static get type() {
  12011. return 'OutputStructNode';
  12012. }
  12013. /**
  12014. * Constructs a new output struct node. The constructor can be invoked with an
  12015. * arbitrary number of nodes representing the members.
  12016. *
  12017. * @param {...Node} members - A parameter list of nodes.
  12018. */
  12019. constructor( ...members ) {
  12020. super();
  12021. /**
  12022. * An array of nodes which defines the output.
  12023. *
  12024. * @type {Array<Node>}
  12025. */
  12026. this.members = members;
  12027. /**
  12028. * This flag can be used for type testing.
  12029. *
  12030. * @type {Boolean}
  12031. * @readonly
  12032. * @default true
  12033. */
  12034. this.isOutputStructNode = true;
  12035. }
  12036. setup( builder ) {
  12037. super.setup( builder );
  12038. const members = this.members;
  12039. const types = [];
  12040. for ( let i = 0; i < members.length; i ++ ) {
  12041. types.push( members[ i ].getNodeType( builder ) );
  12042. }
  12043. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  12044. }
  12045. generate( builder, output ) {
  12046. const propertyName = builder.getOutputStructName();
  12047. const members = this.members;
  12048. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  12049. for ( let i = 0; i < members.length; i ++ ) {
  12050. const snippet = members[ i ].build( builder, output );
  12051. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  12052. }
  12053. return propertyName;
  12054. }
  12055. }
  12056. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  12057. /**
  12058. * Returns the MRT texture index for the given name.
  12059. *
  12060. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  12061. * @param {String} name - The name of the MRT texture which index is requested.
  12062. * @return {Number} The texture index.
  12063. */
  12064. function getTextureIndex( textures, name ) {
  12065. for ( let i = 0; i < textures.length; i ++ ) {
  12066. if ( textures[ i ].name === name ) {
  12067. return i;
  12068. }
  12069. }
  12070. return - 1;
  12071. }
  12072. /**
  12073. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  12074. * post-processing is shown below:
  12075. * ```js
  12076. * const mrtNode = mrt( {
  12077. * output: output,
  12078. * normal: normalView
  12079. * } ) );
  12080. * ```
  12081. * The MRT output is defined as a dictionary.
  12082. *
  12083. * @augments OutputStructNode
  12084. */
  12085. class MRTNode extends OutputStructNode {
  12086. static get type() {
  12087. return 'MRTNode';
  12088. }
  12089. /**
  12090. * Constructs a new output struct node.
  12091. *
  12092. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  12093. */
  12094. constructor( outputNodes ) {
  12095. super();
  12096. /**
  12097. * A dictionary representing the MRT outputs. The key
  12098. * is the name of the output, the value the node which produces
  12099. * the output result.
  12100. *
  12101. * @type {Object<String, Node>}
  12102. */
  12103. this.outputNodes = outputNodes;
  12104. /**
  12105. * This flag can be used for type testing.
  12106. *
  12107. * @type {Boolean}
  12108. * @readonly
  12109. * @default true
  12110. */
  12111. this.isMRTNode = true;
  12112. }
  12113. /**
  12114. * Returns `true` if the MRT node has an output with the given name.
  12115. *
  12116. * @param {String} name - The name of the output.
  12117. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  12118. */
  12119. has( name ) {
  12120. return this.outputNodes[ name ] !== undefined;
  12121. }
  12122. /**
  12123. * Returns the output node for the given name.
  12124. *
  12125. * @param {String} name - The name of the output.
  12126. * @return {Node} The output node.
  12127. */
  12128. get( name ) {
  12129. return this.outputNodes[ name ];
  12130. }
  12131. /**
  12132. * Merges the outputs of the given MRT node with the outputs of this node.
  12133. *
  12134. * @param {MRTNode} mrtNode - The MRT to merge.
  12135. * @return {MRTNode} A new MRT node with merged outputs..
  12136. */
  12137. merge( mrtNode ) {
  12138. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  12139. return mrt( outputs );
  12140. }
  12141. setup( builder ) {
  12142. const outputNodes = this.outputNodes;
  12143. const mrt = builder.renderer.getRenderTarget();
  12144. const members = [];
  12145. const textures = mrt.textures;
  12146. for ( const name in outputNodes ) {
  12147. const index = getTextureIndex( textures, name );
  12148. members[ index ] = vec4( outputNodes[ name ] );
  12149. }
  12150. this.members = members;
  12151. return super.setup( builder );
  12152. }
  12153. }
  12154. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  12155. /** @module Hash **/
  12156. /**
  12157. * Generates a hash value in the range `[0, 1]` from the given seed.
  12158. *
  12159. * @method
  12160. * @param {Node<float>} seed - The seed.
  12161. * @return {Node<float>} The hash value.
  12162. */
  12163. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  12164. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  12165. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  12166. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  12167. const result = word.shiftRight( 22 ).bitXor( word );
  12168. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  12169. } );
  12170. /** @module MathUtils **/
  12171. /**
  12172. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  12173. * The corners are mapped to `0` and the center to `1`.
  12174. * Reference: {@link https://iquilezles.org/articles/functions/}.
  12175. *
  12176. * @method
  12177. * @param {Node<float>} x - The value to remap.
  12178. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabolar to a power `k`.
  12179. * @return {Node<float>} The remapped value.
  12180. */
  12181. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  12182. /**
  12183. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  12184. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  12185. * Reference: {@link https://iquilezles.org/articles/functions/}.
  12186. *
  12187. * @method
  12188. * @param {Node<float>} x - The value to remap.
  12189. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curces.
  12190. * @return {Node<float>} The remapped value.
  12191. */
  12192. 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 ) );
  12193. /**
  12194. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  12195. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  12196. * Reference: {@link https://iquilezles.org/articles/functions/}.
  12197. *
  12198. * @method
  12199. * @param {Node<float>} x - The value to remap.
  12200. * @param {Node<float>} a - First control paramter.
  12201. * @param {Node<float>} b - Second control paramter.
  12202. * @return {Node<float>} The remapped value.
  12203. */
  12204. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  12205. /**
  12206. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  12207. * Reference: {@link https://iquilezles.org/articles/functions/}.
  12208. *
  12209. * @method
  12210. * @param {Node<float>} x - The value to compute the sin for.
  12211. * @param {Node<float>} k - Controls the amount of bounces.
  12212. * @return {Node<float>} The result value.
  12213. */
  12214. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  12215. // https://github.com/cabbibo/glsl-tri-noise-3d
  12216. /** @module TriNoise3D **/
  12217. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  12218. return x.fract().sub( .5 ).abs();
  12219. } ).setLayout( {
  12220. name: 'tri',
  12221. type: 'float',
  12222. inputs: [
  12223. { name: 'x', type: 'float' }
  12224. ]
  12225. } );
  12226. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  12227. 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. ) ) ) ) );
  12228. } ).setLayout( {
  12229. name: 'tri3',
  12230. type: 'vec3',
  12231. inputs: [
  12232. { name: 'p', type: 'vec3' }
  12233. ]
  12234. } );
  12235. /** @module Hash **/
  12236. /**
  12237. * Generates a noise value from the given position, speed and time parameters.
  12238. *
  12239. * @method
  12240. * @param {Node<vec3>} position - The position.
  12241. * @param {Node<float>} speed - The speed.
  12242. * @param {Node<float>} time - The time.
  12243. * @return {Node<float>} The generated noise.
  12244. */
  12245. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  12246. const p = vec3( position ).toVar();
  12247. const z = float( 1.4 ).toVar();
  12248. const rz = float( 0.0 ).toVar();
  12249. const bp = vec3( p ).toVar();
  12250. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  12251. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  12252. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  12253. bp.mulAssign( 1.8 );
  12254. z.mulAssign( 1.5 );
  12255. p.mulAssign( 1.2 );
  12256. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  12257. rz.addAssign( t.div( z ) );
  12258. bp.addAssign( 0.14 );
  12259. } );
  12260. return rz;
  12261. } ).setLayout( {
  12262. name: 'triNoise3D',
  12263. type: 'float',
  12264. inputs: [
  12265. { name: 'position', type: 'vec3' },
  12266. { name: 'speed', type: 'float' },
  12267. { name: 'time', type: 'float' }
  12268. ]
  12269. } );
  12270. /**
  12271. * This class allows to define multiple overloaded versions
  12272. * of the same function. Depending on the parameters of the function
  12273. * call, the node picks the best-fit overloaded version.
  12274. *
  12275. * @augments Node
  12276. */
  12277. class FunctionOverloadingNode extends Node {
  12278. static get type() {
  12279. return 'FunctionOverloadingNode';
  12280. }
  12281. /**
  12282. * Constructs a new function overloading node.
  12283. *
  12284. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  12285. * @param {...Node} parametersNodes - A list of paramater nodes.
  12286. */
  12287. constructor( functionNodes = [], ...parametersNodes ) {
  12288. super();
  12289. /**
  12290. * Array of `Fn` function definitions.
  12291. *
  12292. * @type {Array<Function>}
  12293. */
  12294. this.functionNodes = functionNodes;
  12295. /**
  12296. * A list of paramater nodes.
  12297. *
  12298. * @type {Array<Nodes>}
  12299. */
  12300. this.parametersNodes = parametersNodes;
  12301. /**
  12302. * The selected overloaded function call.
  12303. *
  12304. * @private
  12305. * @type {ShaderCallNodeInternal}
  12306. */
  12307. this._candidateFnCall = null;
  12308. /**
  12309. * This node is marked as global.
  12310. *
  12311. * @type {Boolean}
  12312. * @default true
  12313. */
  12314. this.global = true;
  12315. }
  12316. /**
  12317. * This method is overwritten since the node type is inferred from
  12318. * the function's return type.
  12319. *
  12320. * @param {NodeBuilder} builder - The current node builder.
  12321. * @return {String} The node type.
  12322. */
  12323. getNodeType() {
  12324. return this.functionNodes[ 0 ].shaderNode.layout.type;
  12325. }
  12326. setup( builder ) {
  12327. const params = this.parametersNodes;
  12328. let candidateFnCall = this._candidateFnCall;
  12329. if ( candidateFnCall === null ) {
  12330. let candidateFn = null;
  12331. let candidateScore = - 1;
  12332. for ( const functionNode of this.functionNodes ) {
  12333. const shaderNode = functionNode.shaderNode;
  12334. const layout = shaderNode.layout;
  12335. if ( layout === null ) {
  12336. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  12337. }
  12338. const inputs = layout.inputs;
  12339. if ( params.length === inputs.length ) {
  12340. let score = 0;
  12341. for ( let i = 0; i < params.length; i ++ ) {
  12342. const param = params[ i ];
  12343. const input = inputs[ i ];
  12344. if ( param.getNodeType( builder ) === input.type ) {
  12345. score ++;
  12346. } else {
  12347. score = 0;
  12348. }
  12349. }
  12350. if ( score > candidateScore ) {
  12351. candidateFn = functionNode;
  12352. candidateScore = score;
  12353. }
  12354. }
  12355. }
  12356. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  12357. }
  12358. return candidateFnCall;
  12359. }
  12360. }
  12361. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  12362. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  12363. /** @module Timer **/
  12364. /**
  12365. * Represents the elapsed time in seconds.
  12366. *
  12367. * @type {UniformNode<float>}
  12368. */
  12369. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  12370. /**
  12371. * Represents the delta time in seconds.
  12372. *
  12373. * @type {UniformNode<float>}
  12374. */
  12375. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  12376. /**
  12377. * Represents the current frame ID.
  12378. *
  12379. * @type {UniformNode<uint>}
  12380. */
  12381. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  12382. // Deprecated
  12383. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  12384. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  12385. return time.mul( timeScale );
  12386. };
  12387. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  12388. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  12389. return time.mul( timeScale );
  12390. };
  12391. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  12392. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  12393. return deltaTime.mul( timeScale );
  12394. };
  12395. /** @module Oscillators **/
  12396. /**
  12397. * Generates a sine wave oscillation based on a timer.
  12398. *
  12399. * @method
  12400. * @param {Node<float>} t - The timer to generate the oscillation with.
  12401. * @return {Node<float>} The oscillation node.
  12402. */
  12403. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  12404. /**
  12405. * Generates a square wave oscillation based on a timer.
  12406. *
  12407. * @method
  12408. * @param {Node<float>} t - The timer to generate the oscillation with.
  12409. * @return {Node<float>} The oscillation node.
  12410. */
  12411. const oscSquare = ( t = time ) => t.fract().round();
  12412. /**
  12413. * Generates a triangle wave oscillation based on a timer.
  12414. *
  12415. * @method
  12416. * @param {Node<float>} t - The timer to generate the oscillation with.
  12417. * @return {Node<float>} The oscillation node.
  12418. */
  12419. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  12420. /**
  12421. * Generates a sawtooth wave oscillation based on a timer.
  12422. *
  12423. * @method
  12424. * @param {Node<float>} t - The timer to generate the oscillation with.
  12425. * @return {Node<float>} The oscillation node.
  12426. */
  12427. const oscSawtooth = ( t = time ) => t.fract();
  12428. /** @module UVUtils **/
  12429. /**
  12430. * Rotates the given uv coordinates around a center point
  12431. *
  12432. * @method
  12433. * @param {Node<vec2>} uv - The uv coordinates.
  12434. * @param {Node<float>} rotation - The rotation defined in radians.
  12435. * @param {Node<vec2>} center - The center of rotation
  12436. * @return {Node<vec2>} The rotated uv coordinates.
  12437. */
  12438. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  12439. return rotate( uv.sub( center ), rotation ).add( center );
  12440. } );
  12441. /**
  12442. * Applies a spherical warping effect to the given uv coordinates.
  12443. *
  12444. * @method
  12445. * @param {Node<vec2>} uv - The uv coordinates.
  12446. * @param {Node<float>} strength - The strength of the effect.
  12447. * @param {Node<vec2>} center - The center point
  12448. * @return {Node<vec2>} The updated uv coordinates.
  12449. */
  12450. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  12451. const delta = uv.sub( center );
  12452. const delta2 = delta.dot( delta );
  12453. const delta4 = delta2.mul( delta2 );
  12454. const deltaOffset = delta4.mul( strength );
  12455. return uv.add( delta.mul( deltaOffset ) );
  12456. } );
  12457. /** @module SpriteUtils **/
  12458. /**
  12459. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  12460. * oriented always towards the camera.
  12461. *
  12462. * ```js
  12463. * material.vertexNode = billboarding();
  12464. * ```
  12465. *
  12466. * @method
  12467. * @param {Object} config - The configuration object.
  12468. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  12469. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  12470. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  12471. * @return {Node<vec3>} The updated vertex position in clip space.
  12472. */
  12473. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  12474. let worldMatrix;
  12475. if ( position !== null ) {
  12476. worldMatrix = modelWorldMatrix.toVar();
  12477. worldMatrix[ 3 ][ 0 ] = position.x;
  12478. worldMatrix[ 3 ][ 1 ] = position.y;
  12479. worldMatrix[ 3 ][ 2 ] = position.z;
  12480. } else {
  12481. worldMatrix = modelWorldMatrix;
  12482. }
  12483. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  12484. if ( defined( horizontal ) ) {
  12485. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  12486. modelViewMatrix[ 0 ][ 1 ] = 0;
  12487. modelViewMatrix[ 0 ][ 2 ] = 0;
  12488. }
  12489. if ( defined( vertical ) ) {
  12490. modelViewMatrix[ 1 ][ 0 ] = 0;
  12491. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  12492. modelViewMatrix[ 1 ][ 2 ] = 0;
  12493. }
  12494. modelViewMatrix[ 2 ][ 0 ] = 0;
  12495. modelViewMatrix[ 2 ][ 1 ] = 0;
  12496. modelViewMatrix[ 2 ][ 2 ] = 1;
  12497. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  12498. } );
  12499. /** @module ViewportUtils **/
  12500. /**
  12501. * A special version of a screen uv function that involves a depth comparison
  12502. * when computing the final uvs. The function mitigates visual erros when
  12503. * using viewport texture nodes for refraction purposes. Without this function
  12504. * objects in front of a refractive surface might appear on the refractive surface
  12505. * which is incorrect.
  12506. *
  12507. * @method
  12508. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  12509. * @return {Node<vec2>} The update uv coordinates.
  12510. */
  12511. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  12512. const depth = linearDepth();
  12513. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  12514. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  12515. return finalUV;
  12516. } );
  12517. /**
  12518. * Can be used to compute texture coordinates for animated sprite sheets.
  12519. *
  12520. * ```js
  12521. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  12522. *
  12523. * material.colorNode = texture( spriteSheet, uvNode );
  12524. * ```
  12525. *
  12526. * @augments Node
  12527. */
  12528. class SpriteSheetUVNode extends Node {
  12529. static get type() {
  12530. return 'SpriteSheetUVNode';
  12531. }
  12532. /**
  12533. * Constructs a new sprite sheet uv node.
  12534. *
  12535. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12536. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  12537. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  12538. */
  12539. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  12540. super( 'vec2' );
  12541. /**
  12542. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12543. *
  12544. * @type {Node<vec2>}
  12545. */
  12546. this.countNode = countNode;
  12547. /**
  12548. * The uv node.
  12549. *
  12550. * @type {Node<vec2>}
  12551. */
  12552. this.uvNode = uvNode;
  12553. /**
  12554. * The node that defines the current frame/sprite.
  12555. *
  12556. * @type {Node<float>}
  12557. */
  12558. this.frameNode = frameNode;
  12559. }
  12560. setup() {
  12561. const { frameNode, uvNode, countNode } = this;
  12562. const { width, height } = countNode;
  12563. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  12564. const column = frameNum.mod( width );
  12565. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  12566. const scale = countNode.reciprocal();
  12567. const uvFrameOffset = vec2( column, row );
  12568. return uvNode.add( uvFrameOffset ).mul( scale );
  12569. }
  12570. }
  12571. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  12572. /**
  12573. * Can be used for triplanar texture mapping.
  12574. *
  12575. * ```js
  12576. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  12577. * ```
  12578. *
  12579. * @augments Node
  12580. */
  12581. class TriplanarTexturesNode extends Node {
  12582. static get type() {
  12583. return 'TriplanarTexturesNode';
  12584. }
  12585. /**
  12586. * Constructs a new triplanar textures node.
  12587. *
  12588. * @param {Node} textureXNode - First texture node.
  12589. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12590. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12591. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  12592. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  12593. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  12594. */
  12595. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  12596. super( 'vec4' );
  12597. /**
  12598. * First texture node.
  12599. *
  12600. * @type {Node}
  12601. */
  12602. this.textureXNode = textureXNode;
  12603. /**
  12604. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12605. *
  12606. * @type {Node}
  12607. * @default null
  12608. */
  12609. this.textureYNode = textureYNode;
  12610. /**
  12611. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12612. *
  12613. * @type {Node}
  12614. * @default null
  12615. */
  12616. this.textureZNode = textureZNode;
  12617. /**
  12618. * The scale node.
  12619. *
  12620. * @type {Node<float>}
  12621. * @default float(1)
  12622. */
  12623. this.scaleNode = scaleNode;
  12624. /**
  12625. * Vertex positions in local space.
  12626. *
  12627. * @type {Node<vec3>}
  12628. * @default positionLocal
  12629. */
  12630. this.positionNode = positionNode;
  12631. /**
  12632. * Normals in local space.
  12633. *
  12634. * @type {Node<vec3>}
  12635. * @default normalLocal
  12636. */
  12637. this.normalNode = normalNode;
  12638. }
  12639. setup() {
  12640. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  12641. // Ref: https://github.com/keijiro/StandardTriplanar
  12642. // Blending factor of triplanar mapping
  12643. let bf = normalNode.abs().normalize();
  12644. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  12645. // Triplanar mapping
  12646. const tx = positionNode.yz.mul( scaleNode );
  12647. const ty = positionNode.zx.mul( scaleNode );
  12648. const tz = positionNode.xy.mul( scaleNode );
  12649. // Base color
  12650. const textureX = textureXNode.value;
  12651. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  12652. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  12653. const cx = texture( textureX, tx ).mul( bf.x );
  12654. const cy = texture( textureY, ty ).mul( bf.y );
  12655. const cz = texture( textureZ, tz ).mul( bf.z );
  12656. return add( cx, cy, cz );
  12657. }
  12658. }
  12659. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  12660. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  12661. const _reflectorPlane = new Plane();
  12662. const _normal = new Vector3();
  12663. const _reflectorWorldPosition = new Vector3();
  12664. const _cameraWorldPosition = new Vector3();
  12665. const _rotationMatrix = new Matrix4();
  12666. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  12667. const clipPlane = new Vector4();
  12668. const _view = new Vector3();
  12669. const _target = new Vector3();
  12670. const _q = new Vector4();
  12671. const _size$2 = new Vector2();
  12672. const _defaultRT = new RenderTarget();
  12673. const _defaultUV = screenUV.flipX();
  12674. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  12675. let _inReflector = false;
  12676. /**
  12677. * This node can be used to implement mirror-like flat reflective surfaces.
  12678. *
  12679. * ```js
  12680. * const groundReflector = reflector();
  12681. * material.colorNode = groundReflector;
  12682. *
  12683. * const plane = new Mesh( geometry, material );
  12684. * plane.add( groundReflector.target );
  12685. * ```
  12686. *
  12687. * @augments TextureNode
  12688. */
  12689. class ReflectorNode extends TextureNode {
  12690. static get type() {
  12691. return 'ReflectorNode';
  12692. }
  12693. /**
  12694. * Constructs a new reflector node.
  12695. *
  12696. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12697. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12698. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12699. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12700. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12701. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12702. */
  12703. constructor( parameters = {} ) {
  12704. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  12705. /**
  12706. * A reference to the internal reflector base node which holds the actual implementation.
  12707. *
  12708. * @private
  12709. * @type {Node?}
  12710. * @default null
  12711. */
  12712. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  12713. /**
  12714. * A reference to the internal depth node.
  12715. *
  12716. * @private
  12717. * @type {Node?}
  12718. * @default null
  12719. */
  12720. this._depthNode = null;
  12721. this.setUpdateMatrix( false );
  12722. }
  12723. /**
  12724. * A reference to the internal reflector node.
  12725. *
  12726. * @type {Node}
  12727. */
  12728. get reflector() {
  12729. return this._reflectorBaseNode;
  12730. }
  12731. /**
  12732. * A reference to 3D object the reflector is linked to.
  12733. *
  12734. * @type {Object3D}
  12735. */
  12736. get target() {
  12737. return this._reflectorBaseNode.target;
  12738. }
  12739. /**
  12740. * Returns a node representing the mirror's depth. That can be used
  12741. * to implement more advanced reflection effects like distance attenuation.
  12742. *
  12743. * @return {Node} The depth node.
  12744. */
  12745. getDepthNode() {
  12746. if ( this._depthNode === null ) {
  12747. if ( this._reflectorBaseNode.depth !== true ) {
  12748. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  12749. }
  12750. this._depthNode = nodeObject( new ReflectorNode( {
  12751. defaultTexture: _defaultRT.depthTexture,
  12752. reflector: this._reflectorBaseNode
  12753. } ) );
  12754. }
  12755. return this._depthNode;
  12756. }
  12757. setup( builder ) {
  12758. // ignore if used in post-processing
  12759. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  12760. return super.setup( builder );
  12761. }
  12762. clone() {
  12763. const texture = new this.constructor( this.reflectorNode );
  12764. texture._reflectorBaseNode = this._reflectorBaseNode;
  12765. return texture;
  12766. }
  12767. }
  12768. /**
  12769. * Holds the actual implementation of the reflector.
  12770. *
  12771. * TOOD: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  12772. * in `ReflectorNode`, see #29619.
  12773. *
  12774. * @private
  12775. * @augments Node
  12776. */
  12777. class ReflectorBaseNode extends Node {
  12778. static get type() {
  12779. return 'ReflectorBaseNode';
  12780. }
  12781. /**
  12782. * Constructs a new reflector base node.
  12783. *
  12784. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  12785. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12786. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12787. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12788. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12789. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12790. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12791. */
  12792. constructor( textureNode, parameters = {} ) {
  12793. super();
  12794. const {
  12795. target = new Object3D(),
  12796. resolution = 1,
  12797. generateMipmaps = false,
  12798. bounces = true,
  12799. depth = false
  12800. } = parameters;
  12801. /**
  12802. * Represents the rendered reflections as a texture node.
  12803. *
  12804. * @type {TextureNode}
  12805. */
  12806. this.textureNode = textureNode;
  12807. /**
  12808. * The 3D object the reflector is linked to.
  12809. *
  12810. * @type {Object3D}
  12811. * @default {new Object3D()}
  12812. */
  12813. this.target = target;
  12814. /**
  12815. * The resolution scale.
  12816. *
  12817. * @type {Number}
  12818. * @default {1}
  12819. */
  12820. this.resolution = resolution;
  12821. /**
  12822. * Whether mipmaps should be generated or not.
  12823. *
  12824. * @type {Boolean}
  12825. * @default {false}
  12826. */
  12827. this.generateMipmaps = generateMipmaps;
  12828. /**
  12829. * Whether reflectors can render other reflector nodes or not.
  12830. *
  12831. * @type {Boolean}
  12832. * @default {true}
  12833. */
  12834. this.bounces = bounces;
  12835. /**
  12836. * Whether depth data should be generated or not.
  12837. *
  12838. * @type {Boolean}
  12839. * @default {false}
  12840. */
  12841. this.depth = depth;
  12842. /**
  12843. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  12844. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  12845. *
  12846. * @type {String}
  12847. * @default 'render'
  12848. */
  12849. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  12850. /**
  12851. * Weak map for managing virtual cameras.
  12852. *
  12853. * @type {WeakMap<Camera,Camera>}
  12854. */
  12855. this.virtualCameras = new WeakMap();
  12856. /**
  12857. * Weak map for managing render targets.
  12858. *
  12859. * @type {WeakMap<Camera, RenderTarget>}
  12860. */
  12861. this.renderTargets = new WeakMap();
  12862. }
  12863. /**
  12864. * Updates the resolution of the internal render target.
  12865. *
  12866. * @private
  12867. * @param {RenderTarget} renderTarget - The render target to resize.
  12868. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  12869. */
  12870. _updateResolution( renderTarget, renderer ) {
  12871. const resolution = this.resolution;
  12872. renderer.getDrawingBufferSize( _size$2 );
  12873. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  12874. }
  12875. setup( builder ) {
  12876. this._updateResolution( _defaultRT, builder.renderer );
  12877. return super.setup( builder );
  12878. }
  12879. /**
  12880. * Returns a virtual camera for the given camera. The virtual camera is used to
  12881. * render the scene from the reflector's view so correct reflections can be produced.
  12882. *
  12883. * @param {Camera} camera - The scene's camera.
  12884. * @return {Camera} The corresponding virtual camera.
  12885. */
  12886. getVirtualCamera( camera ) {
  12887. let virtualCamera = this.virtualCameras.get( camera );
  12888. if ( virtualCamera === undefined ) {
  12889. virtualCamera = camera.clone();
  12890. this.virtualCameras.set( camera, virtualCamera );
  12891. }
  12892. return virtualCamera;
  12893. }
  12894. /**
  12895. * Returns a render target for the given camera. The reflections are rendered
  12896. * into this render target.
  12897. *
  12898. * @param {Camera} camera - The scene's camera.
  12899. * @return {RenderTarget} The render target.
  12900. */
  12901. getRenderTarget( camera ) {
  12902. let renderTarget = this.renderTargets.get( camera );
  12903. if ( renderTarget === undefined ) {
  12904. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  12905. if ( this.generateMipmaps === true ) {
  12906. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  12907. renderTarget.texture.generateMipmaps = true;
  12908. }
  12909. if ( this.depth === true ) {
  12910. renderTarget.depthTexture = new DepthTexture();
  12911. }
  12912. this.renderTargets.set( camera, renderTarget );
  12913. }
  12914. return renderTarget;
  12915. }
  12916. updateBefore( frame ) {
  12917. if ( this.bounces === false && _inReflector ) return;
  12918. _inReflector = true;
  12919. const { scene, camera, renderer, material } = frame;
  12920. const { target } = this;
  12921. const virtualCamera = this.getVirtualCamera( camera );
  12922. const renderTarget = this.getRenderTarget( virtualCamera );
  12923. renderer.getDrawingBufferSize( _size$2 );
  12924. this._updateResolution( renderTarget, renderer );
  12925. //
  12926. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  12927. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  12928. _rotationMatrix.extractRotation( target.matrixWorld );
  12929. _normal.set( 0, 0, 1 );
  12930. _normal.applyMatrix4( _rotationMatrix );
  12931. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  12932. // Avoid rendering when reflector is facing away
  12933. if ( _view.dot( _normal ) > 0 ) return;
  12934. _view.reflect( _normal ).negate();
  12935. _view.add( _reflectorWorldPosition );
  12936. _rotationMatrix.extractRotation( camera.matrixWorld );
  12937. _lookAtPosition.set( 0, 0, - 1 );
  12938. _lookAtPosition.applyMatrix4( _rotationMatrix );
  12939. _lookAtPosition.add( _cameraWorldPosition );
  12940. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  12941. _target.reflect( _normal ).negate();
  12942. _target.add( _reflectorWorldPosition );
  12943. //
  12944. virtualCamera.coordinateSystem = camera.coordinateSystem;
  12945. virtualCamera.position.copy( _view );
  12946. virtualCamera.up.set( 0, 1, 0 );
  12947. virtualCamera.up.applyMatrix4( _rotationMatrix );
  12948. virtualCamera.up.reflect( _normal );
  12949. virtualCamera.lookAt( _target );
  12950. virtualCamera.near = camera.near;
  12951. virtualCamera.far = camera.far;
  12952. virtualCamera.updateMatrixWorld();
  12953. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  12954. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  12955. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  12956. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  12957. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  12958. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  12959. const projectionMatrix = virtualCamera.projectionMatrix;
  12960. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  12961. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  12962. _q.z = - 1.0;
  12963. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  12964. // Calculate the scaled plane vector
  12965. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  12966. const clipBias = 0;
  12967. // Replacing the third row of the projection matrix
  12968. projectionMatrix.elements[ 2 ] = clipPlane.x;
  12969. projectionMatrix.elements[ 6 ] = clipPlane.y;
  12970. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  12971. projectionMatrix.elements[ 14 ] = clipPlane.w;
  12972. //
  12973. this.textureNode.value = renderTarget.texture;
  12974. if ( this.depth === true ) {
  12975. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  12976. }
  12977. material.visible = false;
  12978. const currentRenderTarget = renderer.getRenderTarget();
  12979. const currentMRT = renderer.getMRT();
  12980. renderer.setMRT( null );
  12981. renderer.setRenderTarget( renderTarget );
  12982. renderer.render( scene, virtualCamera );
  12983. renderer.setMRT( currentMRT );
  12984. renderer.setRenderTarget( currentRenderTarget );
  12985. material.visible = true;
  12986. _inReflector = false;
  12987. }
  12988. }
  12989. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  12990. // Helper for passes that need to fill the viewport with a single quad.
  12991. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12992. // https://github.com/mrdoob/three.js/pull/21358
  12993. class QuadGeometry extends BufferGeometry {
  12994. constructor( flipY = false ) {
  12995. super();
  12996. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  12997. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  12998. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  12999. }
  13000. }
  13001. const _geometry = /*@__PURE__*/ new QuadGeometry();
  13002. class QuadMesh extends Mesh {
  13003. constructor( material = null ) {
  13004. super( _geometry, material );
  13005. this.camera = _camera;
  13006. this.isQuadMesh = true;
  13007. }
  13008. renderAsync( renderer ) {
  13009. return renderer.renderAsync( this, _camera );
  13010. }
  13011. render( renderer ) {
  13012. renderer.render( this, _camera );
  13013. }
  13014. }
  13015. const _size$1 = /*@__PURE__*/ new Vector2();
  13016. /**
  13017. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  13018. * This module is especially relevant in context of post processing where certain nodes require
  13019. * texture input for their effects. With the helper function `convertToTexture()` which is based
  13020. * on this module, the node system can automatically ensure texture input if required.
  13021. *
  13022. * @augments TextureNode
  13023. */
  13024. class RTTNode extends TextureNode {
  13025. static get type() {
  13026. return 'RTTNode';
  13027. }
  13028. /**
  13029. * Constructs a new RTT node.
  13030. *
  13031. * @param {Node} node - The node to render a texture with.
  13032. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  13033. * @param {Number?} [height=null] - The height of the internal render target.
  13034. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  13035. */
  13036. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  13037. const renderTarget = new RenderTarget( width, height, options );
  13038. super( renderTarget.texture, uv() );
  13039. /**
  13040. * The node to render a texture with.
  13041. *
  13042. * @type {Node}
  13043. */
  13044. this.node = node;
  13045. /**
  13046. * The width of the internal render target.
  13047. * If not width is applied, the render target is automatically resized.
  13048. *
  13049. * @type {Number?}
  13050. * @default null
  13051. */
  13052. this.width = width;
  13053. /**
  13054. * The height of the internal render target.
  13055. *
  13056. * @type {Number?}
  13057. * @default null
  13058. */
  13059. this.height = height;
  13060. /**
  13061. * The pixel ratio
  13062. *
  13063. * @type {Number}
  13064. * @default 1
  13065. */
  13066. this.pixelRatio = 1;
  13067. /**
  13068. * The render target
  13069. *
  13070. * @type {RenderTarget}
  13071. */
  13072. this.renderTarget = renderTarget;
  13073. /**
  13074. * Whether the texture requires an update or not.
  13075. *
  13076. * @type {Boolean}
  13077. * @default true
  13078. */
  13079. this.textureNeedsUpdate = true;
  13080. /**
  13081. * Whether the texture should automatically be updated or not.
  13082. *
  13083. * @type {Boolean}
  13084. * @default true
  13085. */
  13086. this.autoUpdate = true;
  13087. /**
  13088. * The node which is used with the quad mesh for RTT.
  13089. *
  13090. * @private
  13091. * @type {Node}
  13092. * @default null
  13093. */
  13094. this._rttNode = null;
  13095. /**
  13096. * The internal quad mesh for RTT.
  13097. *
  13098. * @private
  13099. * @type {QuadMesh}
  13100. */
  13101. this._quadMesh = new QuadMesh( new NodeMaterial() );
  13102. /**
  13103. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  13104. * the texture once per render in its {@link RTTNode#updateBefore} method.
  13105. *
  13106. * @type {String}
  13107. * @default 'render'
  13108. */
  13109. this.updateBeforeType = NodeUpdateType.RENDER;
  13110. }
  13111. /**
  13112. * Whether the internal render target should automatically be resized or not.
  13113. *
  13114. * @type {Boolean}
  13115. * @readonly
  13116. * @default true
  13117. */
  13118. get autoSize() {
  13119. return this.width === null;
  13120. }
  13121. setup( builder ) {
  13122. this._rttNode = this.node.context( builder.getSharedContext() );
  13123. this._quadMesh.material.name = 'RTT';
  13124. this._quadMesh.material.needsUpdate = true;
  13125. return super.setup( builder );
  13126. }
  13127. /**
  13128. * Sets the size of the internal render target
  13129. *
  13130. * @param {Number} width - The width to set.
  13131. * @param {Number} height - The width to set.
  13132. */
  13133. setSize( width, height ) {
  13134. this.width = width;
  13135. this.height = height;
  13136. const effectiveWidth = width * this.pixelRatio;
  13137. const effectiveHeight = height * this.pixelRatio;
  13138. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  13139. this.textureNeedsUpdate = true;
  13140. }
  13141. /**
  13142. * Sets the pixel ratio. This will also resize the render target.
  13143. *
  13144. * @param {Number} pixelRatio - The pixel ratio to set.
  13145. */
  13146. setPixelRatio( pixelRatio ) {
  13147. this.pixelRatio = pixelRatio;
  13148. this.setSize( this.width, this.height );
  13149. }
  13150. updateBefore( { renderer } ) {
  13151. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  13152. this.textureNeedsUpdate = false;
  13153. //
  13154. if ( this.autoSize === true ) {
  13155. this.pixelRatio = renderer.getPixelRatio();
  13156. const size = renderer.getSize( _size$1 );
  13157. this.setSize( size.width, size.height );
  13158. }
  13159. //
  13160. this._quadMesh.material.fragmentNode = this._rttNode;
  13161. //
  13162. const currentRenderTarget = renderer.getRenderTarget();
  13163. renderer.setRenderTarget( this.renderTarget );
  13164. this._quadMesh.render( renderer );
  13165. renderer.setRenderTarget( currentRenderTarget );
  13166. }
  13167. clone() {
  13168. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  13169. newNode.sampler = this.sampler;
  13170. newNode.referenceNode = this;
  13171. return newNode;
  13172. }
  13173. }
  13174. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  13175. const convertToTexture = ( node, ...params ) => {
  13176. if ( node.isTextureNode ) return node;
  13177. if ( node.isPassNode ) return node.getTextureNode();
  13178. return rtt( node, ...params );
  13179. };
  13180. /** @module PostProcessingUtils **/
  13181. /**
  13182. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  13183. * depth value and the camera's inverse projection matrix.
  13184. *
  13185. * @method
  13186. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  13187. * @param {Node<float>} depth - The fragment's depth value.
  13188. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  13189. * @return {Node<vec3>} The fragments position in view space.
  13190. */
  13191. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  13192. let clipSpacePosition;
  13193. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  13194. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  13195. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  13196. } else {
  13197. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  13198. }
  13199. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  13200. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  13201. } );
  13202. /**
  13203. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  13204. * and the camera's projection matrix
  13205. *
  13206. * @method
  13207. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  13208. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  13209. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  13210. */
  13211. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  13212. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  13213. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  13214. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  13215. } );
  13216. /**
  13217. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  13218. * target is available or if flat surface normals are required.
  13219. *
  13220. * @method
  13221. * @param {Node<vec2>} uv - The texture coordinate.
  13222. * @param {DepthTexture} depthTexture - The depth texture.
  13223. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  13224. * @return {Node<vec3>} The computed normal vector.
  13225. */
  13226. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  13227. const size = textureSize( textureLoad( depthTexture ) );
  13228. const p = ivec2( uv.mul( size ) ).toVar();
  13229. const c0 = textureLoad( depthTexture, p ).toVar();
  13230. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  13231. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  13232. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  13233. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  13234. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  13235. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  13236. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  13237. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  13238. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  13239. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  13240. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  13241. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  13242. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  13243. 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 ) ) );
  13244. 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 ) ) );
  13245. return normalize( cross( dpdx, dpdy ) );
  13246. } );
  13247. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  13248. constructor( array, itemSize, typeClass = Float32Array ) {
  13249. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  13250. super( array, itemSize );
  13251. this.isStorageInstancedBufferAttribute = true;
  13252. }
  13253. }
  13254. class StorageBufferAttribute extends BufferAttribute {
  13255. constructor( array, itemSize, typeClass = Float32Array ) {
  13256. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  13257. super( array, itemSize );
  13258. this.isStorageBufferAttribute = true;
  13259. }
  13260. }
  13261. /**
  13262. * This class enables element access on instances of {@link StorageBufferNode}.
  13263. * In most cases, it is indirectly used when accessing elements with the
  13264. * {@link StorageBufferNode#element} method.
  13265. *
  13266. * ```js
  13267. * const position = positionStorage.element( instanceIndex );
  13268. * ```
  13269. *
  13270. * @augments ArrayElementNode
  13271. */
  13272. class StorageArrayElementNode extends ArrayElementNode {
  13273. static get type() {
  13274. return 'StorageArrayElementNode';
  13275. }
  13276. /**
  13277. * Constructs storage buffer element node.
  13278. *
  13279. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  13280. * @param {Node} indexNode - The index node that defines the element access.
  13281. */
  13282. constructor( storageBufferNode, indexNode ) {
  13283. super( storageBufferNode, indexNode );
  13284. /**
  13285. * This flag can be used for type testing.
  13286. *
  13287. * @type {Boolean}
  13288. * @readonly
  13289. * @default true
  13290. */
  13291. this.isStorageArrayElementNode = true;
  13292. }
  13293. /**
  13294. * The storage buffer node.
  13295. *
  13296. * @param {Node} value
  13297. * @type {StorageBufferNode}
  13298. */
  13299. set storageBufferNode( value ) {
  13300. this.node = value;
  13301. }
  13302. get storageBufferNode() {
  13303. return this.node;
  13304. }
  13305. setup( builder ) {
  13306. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  13307. if ( this.node.isPBO === true ) {
  13308. builder.setupPBO( this.node );
  13309. }
  13310. }
  13311. return super.setup( builder );
  13312. }
  13313. generate( builder, output ) {
  13314. let snippet;
  13315. const isAssignContext = builder.context.assign;
  13316. //
  13317. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  13318. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  13319. snippet = builder.generatePBO( this );
  13320. } else {
  13321. snippet = this.node.build( builder );
  13322. }
  13323. } else {
  13324. snippet = super.generate( builder );
  13325. }
  13326. if ( isAssignContext !== true ) {
  13327. const type = this.getNodeType( builder );
  13328. snippet = builder.format( snippet, type, output );
  13329. }
  13330. return snippet;
  13331. }
  13332. }
  13333. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  13334. class StorageBufferNode extends BufferNode {
  13335. static get type() {
  13336. return 'StorageBufferNode';
  13337. }
  13338. constructor( value, bufferType = null, bufferCount = 0 ) {
  13339. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  13340. bufferType = getTypeFromLength( value.itemSize );
  13341. bufferCount = value.count;
  13342. }
  13343. super( value, bufferType, bufferCount );
  13344. this.isStorageBufferNode = true;
  13345. this.access = NodeAccess.READ_WRITE;
  13346. this.isAtomic = false;
  13347. this.isPBO = false;
  13348. this.bufferCount = bufferCount;
  13349. this._attribute = null;
  13350. this._varying = null;
  13351. this.global = true;
  13352. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  13353. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  13354. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  13355. else value.isStorageBufferAttribute = true;
  13356. }
  13357. }
  13358. getHash( builder ) {
  13359. if ( this.bufferCount === 0 ) {
  13360. let bufferData = builder.globalCache.getData( this.value );
  13361. if ( bufferData === undefined ) {
  13362. bufferData = {
  13363. node: this
  13364. };
  13365. builder.globalCache.setData( this.value, bufferData );
  13366. }
  13367. return bufferData.node.uuid;
  13368. }
  13369. return this.uuid;
  13370. }
  13371. getInputType( /*builder*/ ) {
  13372. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  13373. }
  13374. element( indexNode ) {
  13375. return storageElement( this, indexNode );
  13376. }
  13377. setPBO( value ) {
  13378. this.isPBO = value;
  13379. return this;
  13380. }
  13381. getPBO() {
  13382. return this.isPBO;
  13383. }
  13384. setAccess( value ) {
  13385. this.access = value;
  13386. return this;
  13387. }
  13388. toReadOnly() {
  13389. return this.setAccess( NodeAccess.READ_ONLY );
  13390. }
  13391. setAtomic( value ) {
  13392. this.isAtomic = value;
  13393. return this;
  13394. }
  13395. toAtomic() {
  13396. return this.setAtomic( true );
  13397. }
  13398. getAttributeData() {
  13399. if ( this._attribute === null ) {
  13400. this._attribute = bufferAttribute( this.value );
  13401. this._varying = varying( this._attribute );
  13402. }
  13403. return {
  13404. attribute: this._attribute,
  13405. varying: this._varying
  13406. };
  13407. }
  13408. getNodeType( builder ) {
  13409. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  13410. return super.getNodeType( builder );
  13411. }
  13412. const { attribute } = this.getAttributeData();
  13413. return attribute.getNodeType( builder );
  13414. }
  13415. generate( builder ) {
  13416. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  13417. return super.generate( builder );
  13418. }
  13419. const { attribute, varying } = this.getAttributeData();
  13420. const output = varying.build( builder );
  13421. builder.registerTransform( output, attribute );
  13422. return output;
  13423. }
  13424. }
  13425. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  13426. const storageObject = ( value, type, count ) => { // @deprecated, r171
  13427. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  13428. return storage( value, type, count ).setPBO( true );
  13429. };
  13430. const attributeArray = ( count, type = 'float' ) => {
  13431. const itemSize = getLengthFromType( type );
  13432. const buffer = new StorageBufferAttribute( count, itemSize );
  13433. const node = storage( buffer, type, count );
  13434. return node;
  13435. };
  13436. const instancedArray = ( count, type = 'float' ) => {
  13437. const itemSize = getLengthFromType( type );
  13438. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  13439. const node = storage( buffer, type, count );
  13440. return node;
  13441. };
  13442. class VertexColorNode extends AttributeNode {
  13443. static get type() {
  13444. return 'VertexColorNode';
  13445. }
  13446. constructor( index = 0 ) {
  13447. super( null, 'vec4' );
  13448. this.isVertexColorNode = true;
  13449. this.index = index;
  13450. }
  13451. getAttributeName( /*builder*/ ) {
  13452. const index = this.index;
  13453. return 'color' + ( index > 0 ? index : '' );
  13454. }
  13455. generate( builder ) {
  13456. const attributeName = this.getAttributeName( builder );
  13457. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13458. let result;
  13459. if ( geometryAttribute === true ) {
  13460. result = super.generate( builder );
  13461. } else {
  13462. // Vertex color fallback should be white
  13463. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13464. }
  13465. return result;
  13466. }
  13467. serialize( data ) {
  13468. super.serialize( data );
  13469. data.index = this.index;
  13470. }
  13471. deserialize( data ) {
  13472. super.deserialize( data );
  13473. this.index = data.index;
  13474. }
  13475. }
  13476. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  13477. class PointUVNode extends Node {
  13478. static get type() {
  13479. return 'PointUVNode';
  13480. }
  13481. constructor() {
  13482. super( 'vec2' );
  13483. this.isPointUVNode = true;
  13484. }
  13485. generate( /*builder*/ ) {
  13486. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  13487. }
  13488. }
  13489. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  13490. const _e1 = /*@__PURE__*/ new Euler();
  13491. const _m1 = /*@__PURE__*/ new Matrix4();
  13492. class SceneNode extends Node {
  13493. static get type() {
  13494. return 'SceneNode';
  13495. }
  13496. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  13497. super();
  13498. this.scope = scope;
  13499. this.scene = scene;
  13500. }
  13501. setup( builder ) {
  13502. const scope = this.scope;
  13503. const scene = this.scene !== null ? this.scene : builder.scene;
  13504. let output;
  13505. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  13506. output = reference( 'backgroundBlurriness', 'float', scene );
  13507. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  13508. output = reference( 'backgroundIntensity', 'float', scene );
  13509. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  13510. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  13511. const background = scene.background;
  13512. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  13513. _e1.copy( scene.backgroundRotation );
  13514. // accommodate left-handed frame
  13515. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  13516. _m1.makeRotationFromEuler( _e1 );
  13517. } else {
  13518. _m1.identity();
  13519. }
  13520. return _m1;
  13521. } );
  13522. } else {
  13523. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  13524. }
  13525. return output;
  13526. }
  13527. }
  13528. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  13529. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  13530. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  13531. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  13532. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  13533. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  13534. class StorageTextureNode extends TextureNode {
  13535. static get type() {
  13536. return 'StorageTextureNode';
  13537. }
  13538. constructor( value, uvNode, storeNode = null ) {
  13539. super( value, uvNode );
  13540. this.storeNode = storeNode;
  13541. this.isStorageTextureNode = true;
  13542. this.access = NodeAccess.WRITE_ONLY;
  13543. }
  13544. getInputType( /*builder*/ ) {
  13545. return 'storageTexture';
  13546. }
  13547. setup( builder ) {
  13548. super.setup( builder );
  13549. const properties = builder.getNodeProperties( this );
  13550. properties.storeNode = this.storeNode;
  13551. }
  13552. setAccess( value ) {
  13553. this.access = value;
  13554. return this;
  13555. }
  13556. generate( builder, output ) {
  13557. let snippet;
  13558. if ( this.storeNode !== null ) {
  13559. snippet = this.generateStore( builder );
  13560. } else {
  13561. snippet = super.generate( builder, output );
  13562. }
  13563. return snippet;
  13564. }
  13565. toReadWrite() {
  13566. return this.setAccess( NodeAccess.READ_WRITE );
  13567. }
  13568. toReadOnly() {
  13569. return this.setAccess( NodeAccess.READ_ONLY );
  13570. }
  13571. toWriteOnly() {
  13572. return this.setAccess( NodeAccess.WRITE_ONLY );
  13573. }
  13574. generateStore( builder ) {
  13575. const properties = builder.getNodeProperties( this );
  13576. const { uvNode, storeNode } = properties;
  13577. const textureProperty = super.generate( builder, 'property' );
  13578. const uvSnippet = uvNode.build( builder, 'uvec2' );
  13579. const storeSnippet = storeNode.build( builder, 'vec4' );
  13580. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  13581. builder.addLineFlowCode( snippet, this );
  13582. }
  13583. }
  13584. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  13585. const textureStore = ( value, uvNode, storeNode ) => {
  13586. const node = storageTexture( value, uvNode, storeNode );
  13587. if ( storeNode !== null ) node.append();
  13588. return node;
  13589. };
  13590. class UserDataNode extends ReferenceNode {
  13591. static get type() {
  13592. return 'UserDataNode';
  13593. }
  13594. constructor( property, inputType, userData = null ) {
  13595. super( property, inputType, userData );
  13596. this.userData = userData;
  13597. }
  13598. updateReference( state ) {
  13599. this.reference = this.userData !== null ? this.userData : state.object.userData;
  13600. return this.reference;
  13601. }
  13602. }
  13603. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  13604. const _objectData = new WeakMap();
  13605. class VelocityNode extends TempNode {
  13606. static get type() {
  13607. return 'VelocityNode';
  13608. }
  13609. constructor() {
  13610. super( 'vec2' );
  13611. this.projectionMatrix = null;
  13612. this.updateType = NodeUpdateType.OBJECT;
  13613. this.updateAfterType = NodeUpdateType.OBJECT;
  13614. this.previousModelWorldMatrix = uniform( new Matrix4() );
  13615. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  13616. this.previousCameraViewMatrix = uniform( new Matrix4() );
  13617. }
  13618. setProjectionMatrix( projectionMatrix ) {
  13619. this.projectionMatrix = projectionMatrix;
  13620. }
  13621. update( { frameId, camera, object } ) {
  13622. const previousModelMatrix = getPreviousMatrix( object );
  13623. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  13624. //
  13625. const cameraData = getData( camera );
  13626. if ( cameraData.frameId !== frameId ) {
  13627. cameraData.frameId = frameId;
  13628. if ( cameraData.previousProjectionMatrix === undefined ) {
  13629. cameraData.previousProjectionMatrix = new Matrix4();
  13630. cameraData.previousCameraViewMatrix = new Matrix4();
  13631. cameraData.currentProjectionMatrix = new Matrix4();
  13632. cameraData.currentCameraViewMatrix = new Matrix4();
  13633. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13634. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  13635. } else {
  13636. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  13637. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  13638. }
  13639. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13640. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  13641. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  13642. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  13643. }
  13644. }
  13645. updateAfter( { object } ) {
  13646. getPreviousMatrix( object ).copy( object.matrixWorld );
  13647. }
  13648. setup( /*builder*/ ) {
  13649. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  13650. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  13651. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  13652. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  13653. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  13654. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  13655. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  13656. return velocity;
  13657. }
  13658. }
  13659. function getData( object ) {
  13660. let objectData = _objectData.get( object );
  13661. if ( objectData === undefined ) {
  13662. objectData = {};
  13663. _objectData.set( object, objectData );
  13664. }
  13665. return objectData;
  13666. }
  13667. function getPreviousMatrix( object, index = 0 ) {
  13668. const objectData = getData( object );
  13669. let matrix = objectData[ index ];
  13670. if ( matrix === undefined ) {
  13671. objectData[ index ] = matrix = new Matrix4();
  13672. }
  13673. return matrix;
  13674. }
  13675. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  13676. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13677. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13678. } ).setLayout( {
  13679. name: 'blendBurn',
  13680. type: 'vec3',
  13681. inputs: [
  13682. { name: 'base', type: 'vec3' },
  13683. { name: 'blend', type: 'vec3' }
  13684. ]
  13685. } );
  13686. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13687. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13688. } ).setLayout( {
  13689. name: 'blendDodge',
  13690. type: 'vec3',
  13691. inputs: [
  13692. { name: 'base', type: 'vec3' },
  13693. { name: 'blend', type: 'vec3' }
  13694. ]
  13695. } );
  13696. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13697. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13698. } ).setLayout( {
  13699. name: 'blendScreen',
  13700. type: 'vec3',
  13701. inputs: [
  13702. { name: 'base', type: 'vec3' },
  13703. { name: 'blend', type: 'vec3' }
  13704. ]
  13705. } );
  13706. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13707. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13708. } ).setLayout( {
  13709. name: 'blendOverlay',
  13710. type: 'vec3',
  13711. inputs: [
  13712. { name: 'base', type: 'vec3' },
  13713. { name: 'blend', type: 'vec3' }
  13714. ]
  13715. } );
  13716. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13717. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13718. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13719. } ).setLayout( {
  13720. name: 'blendColor',
  13721. type: 'vec4',
  13722. inputs: [
  13723. { name: 'base', type: 'vec4' },
  13724. { name: 'blend', type: 'vec4' }
  13725. ]
  13726. } );
  13727. // deprecated
  13728. const burn = ( ...params ) => { // @deprecated, r171
  13729. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13730. return blendBurn( params );
  13731. };
  13732. const dodge = ( ...params ) => { // @deprecated, r171
  13733. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13734. return blendDodge( params );
  13735. };
  13736. const screen = ( ...params ) => { // @deprecated, r171
  13737. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13738. return blendScreen( params );
  13739. };
  13740. const overlay = ( ...params ) => { // @deprecated, r171
  13741. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13742. return blendOverlay( params );
  13743. };
  13744. /** @module ColorAdjustment **/
  13745. /**
  13746. * Computes a grayscale value for the given RGB color value.
  13747. *
  13748. * @method
  13749. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  13750. * @return {Node<vec3>} The grayscale color.
  13751. */
  13752. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13753. return luminance( color.rgb );
  13754. } );
  13755. /**
  13756. * Super-saturates or desaturates the given RGB color.
  13757. *
  13758. * @method
  13759. * @param {Node<vec3>} color - The input color.
  13760. * @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.
  13761. * @return {Node<vec3>} The saturated color.
  13762. */
  13763. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13764. return adjustment.mix( luminance( color.rgb ), color.rgb );
  13765. } );
  13766. /**
  13767. * Selectively enhance the intensity of less saturated RGB colors. Can result
  13768. * in a more natural and visually appealing image with enhanced color depth
  13769. * compared to {@link ColorAdjustment#saturation}.
  13770. *
  13771. * @method
  13772. * @param {Node<vec3>} color - The input color.
  13773. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  13774. * @return {Node<vec3>} The updated color.
  13775. */
  13776. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13777. const average = add( color.r, color.g, color.b ).div( 3.0 );
  13778. const mx = color.r.max( color.g.max( color.b ) );
  13779. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  13780. return mix( color.rgb, mx, amt );
  13781. } );
  13782. /**
  13783. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  13784. *
  13785. * @method
  13786. * @param {Node<vec3>} color - The input color.
  13787. * @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.
  13788. * @return {Node<vec3>} The updated color.
  13789. */
  13790. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13791. const k = vec3( 0.57735, 0.57735, 0.57735 );
  13792. const cosAngle = adjustment.cos();
  13793. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  13794. } );
  13795. /**
  13796. * Computes the luminance for the given RGB color value.
  13797. *
  13798. * @method
  13799. * @param {Node<vec3>} color - The color value to compute the luminance for.
  13800. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  13801. * @return {Node<vec3>} The luminance.
  13802. */
  13803. const luminance = (
  13804. color,
  13805. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  13806. ) => dot( color, luminanceCoefficients );
  13807. /**
  13808. * Color Decision List (CDL) v1.2
  13809. *
  13810. * Compact representation of color grading information, defined by slope, offset, power, and
  13811. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  13812. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  13813. *
  13814. * @method
  13815. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  13816. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  13817. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  13818. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  13819. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  13820. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  13821. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  13822. *
  13823. * References:
  13824. * - ASC CDL v1.2
  13825. * - {@link https://blender.stackexchange.com/a/55239/43930}
  13826. * - {@link https://docs.acescentral.com/specifications/acescc/}
  13827. */
  13828. const cdl = /*@__PURE__*/ Fn( ( [
  13829. color,
  13830. slope = vec3( 1 ),
  13831. offset = vec3( 0 ),
  13832. power = vec3( 1 ),
  13833. saturation = float( 1 ),
  13834. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  13835. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  13836. ] ) => {
  13837. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  13838. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  13839. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  13840. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  13841. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  13842. const pv = v.pow( power ).toVar();
  13843. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  13844. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  13845. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  13846. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  13847. return vec4( v.rgb, color.a );
  13848. } );
  13849. /**
  13850. * Represents a posterize effect which reduces the number of colors
  13851. * in an image, resulting in a more blocky and stylized appearance.
  13852. *
  13853. * @augments TempNode
  13854. */
  13855. class PosterizeNode extends TempNode {
  13856. static get type() {
  13857. return 'PosterizeNode';
  13858. }
  13859. /**
  13860. * Constructs a new posterize node.
  13861. *
  13862. * @param {Node} sourceNode - The input color.
  13863. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13864. */
  13865. constructor( sourceNode, stepsNode ) {
  13866. super();
  13867. /**
  13868. * The input color.
  13869. *
  13870. * @type {Node}
  13871. */
  13872. this.sourceNode = sourceNode;
  13873. /**
  13874. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13875. *
  13876. * @type {Node}
  13877. */
  13878. this.stepsNode = stepsNode;
  13879. }
  13880. setup() {
  13881. const { sourceNode, stepsNode } = this;
  13882. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  13883. }
  13884. }
  13885. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  13886. const _size = /*@__PURE__*/ new Vector2();
  13887. /**
  13888. * Represents the texture of a pass node.
  13889. *
  13890. * @augments TextureNode
  13891. * @private
  13892. */
  13893. class PassTextureNode extends TextureNode {
  13894. static get type() {
  13895. return 'PassTextureNode';
  13896. }
  13897. /**
  13898. * Constructs a new pass texture node.
  13899. *
  13900. * @param {PassNode} passNode - The pass node.
  13901. * @param {Texture} texture - The output texture.
  13902. */
  13903. constructor( passNode, texture ) {
  13904. super( texture );
  13905. /**
  13906. * A reference to the pass node.
  13907. *
  13908. * @type {PassNode}
  13909. */
  13910. this.passNode = passNode;
  13911. this.setUpdateMatrix( false );
  13912. }
  13913. setup( builder ) {
  13914. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  13915. return super.setup( builder );
  13916. }
  13917. clone() {
  13918. return new this.constructor( this.passNode, this.value );
  13919. }
  13920. }
  13921. /**
  13922. * An extension of `PassTextureNode` which allows to manage more than one
  13923. * internal texture. Relevant for the `getPreviousTexture()` related API.
  13924. *
  13925. * @augments PassTextureNode
  13926. * @private
  13927. */
  13928. class PassMultipleTextureNode extends PassTextureNode {
  13929. static get type() {
  13930. return 'PassMultipleTextureNode';
  13931. }
  13932. /**
  13933. * Constructs a new pass texture node.
  13934. *
  13935. * @param {PassNode} passNode - The pass node.
  13936. * @param {String} textureName - The output texture name.
  13937. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  13938. */
  13939. constructor( passNode, textureName, previousTexture = false ) {
  13940. // null is passed to the super call since this class does not
  13941. // use an external texture for rendering pass data into. Instead
  13942. // the texture is managed by the pass node itself
  13943. super( passNode, null );
  13944. /**
  13945. * The output texture name.
  13946. *
  13947. * @type {String}
  13948. */
  13949. this.textureName = textureName;
  13950. /**
  13951. * Whether previous frame data should be used or not.
  13952. *
  13953. * @type {Boolean}
  13954. */
  13955. this.previousTexture = previousTexture;
  13956. }
  13957. /**
  13958. * Updates the texture reference of this node.
  13959. */
  13960. updateTexture() {
  13961. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  13962. }
  13963. setup( builder ) {
  13964. this.updateTexture();
  13965. return super.setup( builder );
  13966. }
  13967. clone() {
  13968. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  13969. }
  13970. }
  13971. /**
  13972. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  13973. * This pass produces a render for the given scene and camera and can provide multiple outputs
  13974. * via MRT for further processing.
  13975. *
  13976. * ```js
  13977. * const postProcessing = new PostProcessing( renderer );
  13978. *
  13979. * const scenePass = pass( scene, camera );
  13980. *
  13981. * postProcessing.outputNode = scenePass;
  13982. * ```
  13983. *
  13984. * @augments TempNode
  13985. */
  13986. class PassNode extends TempNode {
  13987. static get type() {
  13988. return 'PassNode';
  13989. }
  13990. /**
  13991. * Constructs a new pass node.
  13992. *
  13993. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  13994. * @param {Scene} scene - A reference to the scene.
  13995. * @param {Camera} camera - A reference to the camera.
  13996. * @param {Object} options - Options for the internal render target.
  13997. */
  13998. constructor( scope, scene, camera, options = {} ) {
  13999. super( 'vec4' );
  14000. /**
  14001. * The scope of the pass. The scope determines whether the node outputs color or depth.
  14002. *
  14003. * @type {('color'|'depth')}
  14004. */
  14005. this.scope = scope;
  14006. /**
  14007. * A reference to the scene.
  14008. *
  14009. * @type {Scene}
  14010. */
  14011. this.scene = scene;
  14012. /**
  14013. * A reference to the camera.
  14014. *
  14015. * @type {camera}
  14016. */
  14017. this.camera = camera;
  14018. /**
  14019. * Options for the internal render target.
  14020. *
  14021. * @type {Object}
  14022. */
  14023. this.options = options;
  14024. /**
  14025. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  14026. *
  14027. * @private
  14028. * @type {Number}
  14029. * @default 1
  14030. */
  14031. this._pixelRatio = 1;
  14032. /**
  14033. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  14034. * @private
  14035. * @type {Number}
  14036. * @default 1
  14037. */
  14038. this._width = 1;
  14039. /**
  14040. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  14041. * @private
  14042. * @type {Number}
  14043. * @default 1
  14044. */
  14045. this._height = 1;
  14046. const depthTexture = new DepthTexture();
  14047. depthTexture.isRenderTargetTexture = true;
  14048. //depthTexture.type = FloatType;
  14049. depthTexture.name = 'depth';
  14050. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  14051. renderTarget.texture.name = 'output';
  14052. renderTarget.depthTexture = depthTexture;
  14053. /**
  14054. * The pass's render target.
  14055. *
  14056. * @type {RenderTarget}
  14057. */
  14058. this.renderTarget = renderTarget;
  14059. /**
  14060. * A dictionary holding the internal result textures.
  14061. *
  14062. * @private
  14063. * @type {Object}
  14064. */
  14065. this._textures = {
  14066. output: renderTarget.texture,
  14067. depth: depthTexture
  14068. };
  14069. /**
  14070. * A dictionary holding the internal texture nodes.
  14071. *
  14072. * @private
  14073. * @type {Object}
  14074. */
  14075. this._textureNodes = {};
  14076. /**
  14077. * A dictionary holding the internal depth nodes.
  14078. *
  14079. * @private
  14080. * @type {Object}
  14081. */
  14082. this._linearDepthNodes = {};
  14083. /**
  14084. * A dictionary holding the internal viewZ nodes.
  14085. *
  14086. * @private
  14087. * @type {Object}
  14088. */
  14089. this._viewZNodes = {};
  14090. /**
  14091. * A dictionary holding the texture data of the previous frame.
  14092. * Used for computing velocity/motion vectors.
  14093. *
  14094. * @private
  14095. * @type {Object}
  14096. */
  14097. this._previousTextures = {};
  14098. /**
  14099. * A dictionary holding the texture nodes of the previous frame.
  14100. * Used for computing velocity/motion vectors.
  14101. *
  14102. * @private
  14103. * @type {Object}
  14104. */
  14105. this._previousTextureNodes = {};
  14106. /**
  14107. * The `near` property of the camera as a uniform.
  14108. *
  14109. * @private
  14110. * @type {UniformNode}
  14111. */
  14112. this._cameraNear = uniform( 0 );
  14113. /**
  14114. * The `far` property of the camera as a uniform.
  14115. *
  14116. * @private
  14117. * @type {UniformNode}
  14118. */
  14119. this._cameraFar = uniform( 0 );
  14120. /**
  14121. * A MRT node configuring the MRT settings.
  14122. *
  14123. * @private
  14124. * @type {MRTNode?}
  14125. * @default null
  14126. */
  14127. this._mrt = null;
  14128. /**
  14129. * This flag can be used for type testing.
  14130. *
  14131. * @type {Boolean}
  14132. * @readonly
  14133. * @default true
  14134. */
  14135. this.isPassNode = true;
  14136. /**
  14137. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  14138. * scene once per frame in its {@link PassNode#updateBefore} method.
  14139. *
  14140. * @type {String}
  14141. * @default 'frame'
  14142. */
  14143. this.updateBeforeType = NodeUpdateType.FRAME;
  14144. }
  14145. /**
  14146. * Sets the given MRT node to setup MRT for this pass.
  14147. *
  14148. * @param {MRTNode} mrt - The MRT object.
  14149. * @return {PassNode} A reference to this pass.
  14150. */
  14151. setMRT( mrt ) {
  14152. this._mrt = mrt;
  14153. return this;
  14154. }
  14155. /**
  14156. * Returns the current MRT node.
  14157. *
  14158. * @return {MRTNode} The current MRT node.
  14159. */
  14160. getMRT() {
  14161. return this._mrt;
  14162. }
  14163. /**
  14164. * The method is overwritten so it always returns `true`.
  14165. *
  14166. * @return {Boolean} Whether this node is global or not.
  14167. */
  14168. isGlobal() {
  14169. return true;
  14170. }
  14171. /**
  14172. * Returns the texture for the given output name.
  14173. *
  14174. * @param {String} name - The output name to get the texture for.
  14175. * @return {Texture} The texture.
  14176. */
  14177. getTexture( name ) {
  14178. let texture = this._textures[ name ];
  14179. if ( texture === undefined ) {
  14180. const refTexture = this.renderTarget.texture;
  14181. texture = refTexture.clone();
  14182. texture.name = name;
  14183. this._textures[ name ] = texture;
  14184. this.renderTarget.textures.push( texture );
  14185. }
  14186. return texture;
  14187. }
  14188. /**
  14189. * Returns the texture holding the data of the previous frame for the given output name.
  14190. *
  14191. * @param {String} name - The output name to get the texture for.
  14192. * @return {Texture} The texture holding the data of the previous frame.
  14193. */
  14194. getPreviousTexture( name ) {
  14195. let texture = this._previousTextures[ name ];
  14196. if ( texture === undefined ) {
  14197. texture = this.getTexture( name ).clone();
  14198. this._previousTextures[ name ] = texture;
  14199. }
  14200. return texture;
  14201. }
  14202. /**
  14203. * Switches current and previous textures for the given output name.
  14204. *
  14205. * @param {String} name - The output name.
  14206. */
  14207. toggleTexture( name ) {
  14208. const prevTexture = this._previousTextures[ name ];
  14209. if ( prevTexture !== undefined ) {
  14210. const texture = this._textures[ name ];
  14211. const index = this.renderTarget.textures.indexOf( texture );
  14212. this.renderTarget.textures[ index ] = prevTexture;
  14213. this._textures[ name ] = prevTexture;
  14214. this._previousTextures[ name ] = texture;
  14215. this._textureNodes[ name ].updateTexture();
  14216. this._previousTextureNodes[ name ].updateTexture();
  14217. }
  14218. }
  14219. /**
  14220. * Returns the texture node for the given output name.
  14221. *
  14222. * @param {String} [name='output'] - The output name to get the texture node for.
  14223. * @return {TextureNode} The texture node.
  14224. */
  14225. getTextureNode( name = 'output' ) {
  14226. let textureNode = this._textureNodes[ name ];
  14227. if ( textureNode === undefined ) {
  14228. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  14229. textureNode.updateTexture();
  14230. this._textureNodes[ name ] = textureNode;
  14231. }
  14232. return textureNode;
  14233. }
  14234. /**
  14235. * Returns the previous texture node for the given output name.
  14236. *
  14237. * @param {String} [name='output'] - The output name to get the previous texture node for.
  14238. * @return {TextureNode} The previous texture node.
  14239. */
  14240. getPreviousTextureNode( name = 'output' ) {
  14241. let textureNode = this._previousTextureNodes[ name ];
  14242. if ( textureNode === undefined ) {
  14243. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  14244. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  14245. textureNode.updateTexture();
  14246. this._previousTextureNodes[ name ] = textureNode;
  14247. }
  14248. return textureNode;
  14249. }
  14250. /**
  14251. * Returns a viewZ node of this pass.
  14252. *
  14253. * @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.
  14254. * @return {Node} The viewZ node.
  14255. */
  14256. getViewZNode( name = 'depth' ) {
  14257. let viewZNode = this._viewZNodes[ name ];
  14258. if ( viewZNode === undefined ) {
  14259. const cameraNear = this._cameraNear;
  14260. const cameraFar = this._cameraFar;
  14261. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  14262. }
  14263. return viewZNode;
  14264. }
  14265. /**
  14266. * Returns a linear depth node of this pass.
  14267. *
  14268. * @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.
  14269. * @return {Node} The linear depth node.
  14270. */
  14271. getLinearDepthNode( name = 'depth' ) {
  14272. let linearDepthNode = this._linearDepthNodes[ name ];
  14273. if ( linearDepthNode === undefined ) {
  14274. const cameraNear = this._cameraNear;
  14275. const cameraFar = this._cameraFar;
  14276. const viewZNode = this.getViewZNode( name );
  14277. // TODO: just if ( builder.camera.isPerspectiveCamera )
  14278. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  14279. }
  14280. return linearDepthNode;
  14281. }
  14282. setup( { renderer } ) {
  14283. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  14284. // Disable MSAA for WebGL backend for now
  14285. if ( renderer.backend.isWebGLBackend === true ) {
  14286. this.renderTarget.samples = 0;
  14287. }
  14288. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  14289. }
  14290. updateBefore( frame ) {
  14291. const { renderer } = frame;
  14292. const { scene, camera } = this;
  14293. this._pixelRatio = renderer.getPixelRatio();
  14294. const size = renderer.getSize( _size );
  14295. this.setSize( size.width, size.height );
  14296. const currentRenderTarget = renderer.getRenderTarget();
  14297. const currentMRT = renderer.getMRT();
  14298. this._cameraNear.value = camera.near;
  14299. this._cameraFar.value = camera.far;
  14300. for ( const name in this._previousTextures ) {
  14301. this.toggleTexture( name );
  14302. }
  14303. renderer.setRenderTarget( this.renderTarget );
  14304. renderer.setMRT( this._mrt );
  14305. renderer.render( scene, camera );
  14306. renderer.setRenderTarget( currentRenderTarget );
  14307. renderer.setMRT( currentMRT );
  14308. }
  14309. /**
  14310. * Sets the size of the pass's render target. Honors the pixel ratio.
  14311. *
  14312. * @param {Number} width - The width to set.
  14313. * @param {Number} height - The height to set.
  14314. */
  14315. setSize( width, height ) {
  14316. this._width = width;
  14317. this._height = height;
  14318. const effectiveWidth = this._width * this._pixelRatio;
  14319. const effectiveHeight = this._height * this._pixelRatio;
  14320. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  14321. }
  14322. /**
  14323. * Sets the pixel ratio the pass's render target and updates the size.
  14324. *
  14325. * @param {Number} pixelRatio - The pixel ratio to set.
  14326. */
  14327. setPixelRatio( pixelRatio ) {
  14328. this._pixelRatio = pixelRatio;
  14329. this.setSize( this._width, this._height );
  14330. }
  14331. /**
  14332. * Frees internal resources. Should be called when the node is no longer in use.
  14333. */
  14334. dispose() {
  14335. this.renderTarget.dispose();
  14336. }
  14337. }
  14338. PassNode.COLOR = 'color';
  14339. PassNode.DEPTH = 'depth';
  14340. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  14341. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  14342. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  14343. /**
  14344. * Represents a render pass for producing a toon outline effect on compatible objects.
  14345. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  14346. * will receive the outline.
  14347. *
  14348. * ```js
  14349. * const postProcessing = new PostProcessing( renderer );
  14350. *
  14351. * const scenePass = toonOutlinePass( scene, camera );
  14352. *
  14353. * postProcessing.outputNode = scenePass;
  14354. * ```
  14355. * @augments PassNode
  14356. */
  14357. class ToonOutlinePassNode extends PassNode {
  14358. static get type() {
  14359. return 'ToonOutlinePassNode';
  14360. }
  14361. /**
  14362. * Constructs a new outline pass node.
  14363. *
  14364. * @param {Scene} scene - A reference to the scene.
  14365. * @param {Camera} camera - A reference to the camera.
  14366. * @param {Node} colorNode - Defines the outline's color.
  14367. * @param {Node} thicknessNode - Defines the outline's thickness.
  14368. * @param {Node} alphaNode - Defines the outline's alpha.
  14369. */
  14370. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  14371. super( PassNode.COLOR, scene, camera );
  14372. /**
  14373. * Defines the outline's color.
  14374. *
  14375. * @type {Node}
  14376. */
  14377. this.colorNode = colorNode;
  14378. /**
  14379. * Defines the outline's thickness.
  14380. *
  14381. * @type {Node}
  14382. */
  14383. this.thicknessNode = thicknessNode;
  14384. /**
  14385. * Defines the outline's alpha.
  14386. *
  14387. * @type {Node}
  14388. */
  14389. this.alphaNode = alphaNode;
  14390. /**
  14391. * An internal material cache.
  14392. *
  14393. * @private
  14394. * @type {WeakMap<Material, NodeMaterial>}
  14395. */
  14396. this._materialCache = new WeakMap();
  14397. }
  14398. updateBefore( frame ) {
  14399. const { renderer } = frame;
  14400. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  14401. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  14402. // only render outline for supported materials
  14403. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  14404. if ( material.wireframe === false ) {
  14405. const outlineMaterial = this._getOutlineMaterial( material );
  14406. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  14407. }
  14408. }
  14409. // default
  14410. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  14411. } );
  14412. super.updateBefore( frame );
  14413. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  14414. }
  14415. /**
  14416. * Creates the material used for outline rendering.
  14417. *
  14418. * @private
  14419. * @return {NodeMaterial} The outline material.
  14420. */
  14421. _createMaterial() {
  14422. const material = new NodeMaterial();
  14423. material.isMeshToonOutlineMaterial = true;
  14424. material.name = 'Toon_Outline';
  14425. material.side = BackSide;
  14426. // vertex node
  14427. const outlineNormal = normalLocal.negate();
  14428. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  14429. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  14430. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  14431. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  14432. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  14433. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  14434. // color node
  14435. material.colorNode = vec4( this.colorNode, this.alphaNode );
  14436. return material;
  14437. }
  14438. /**
  14439. * For the given toon material, this method returns a correspoding
  14440. * outline material.
  14441. *
  14442. * @private
  14443. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  14444. * @return {NodeMaterial} The outline material.
  14445. */
  14446. _getOutlineMaterial( originalMaterial ) {
  14447. let outlineMaterial = this._materialCache.get( originalMaterial );
  14448. if ( outlineMaterial === undefined ) {
  14449. outlineMaterial = this._createMaterial();
  14450. this._materialCache.set( originalMaterial, outlineMaterial );
  14451. }
  14452. return outlineMaterial;
  14453. }
  14454. }
  14455. 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 ) ) );
  14456. /** @module ToneMappingFunctions **/
  14457. /**
  14458. * Linear tone mapping, exposure only.
  14459. *
  14460. * @method
  14461. * @param {Node<vec3>} color - The color that should be tone mapped.
  14462. * @param {Node<float>} exposure - The exposure.
  14463. * @return {Node<vec3>} The tone mapped color.
  14464. */
  14465. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14466. return color.mul( exposure ).clamp();
  14467. } ).setLayout( {
  14468. name: 'linearToneMapping',
  14469. type: 'vec3',
  14470. inputs: [
  14471. { name: 'color', type: 'vec3' },
  14472. { name: 'exposure', type: 'float' }
  14473. ]
  14474. } );
  14475. /**
  14476. * Reinhard tone mapping.
  14477. *
  14478. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  14479. *
  14480. * @method
  14481. * @param {Node<vec3>} color - The color that should be tone mapped.
  14482. * @param {Node<float>} exposure - The exposure.
  14483. * @return {Node<vec3>} The tone mapped color.
  14484. */
  14485. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14486. color = color.mul( exposure );
  14487. return color.div( color.add( 1.0 ) ).clamp();
  14488. } ).setLayout( {
  14489. name: 'reinhardToneMapping',
  14490. type: 'vec3',
  14491. inputs: [
  14492. { name: 'color', type: 'vec3' },
  14493. { name: 'exposure', type: 'float' }
  14494. ]
  14495. } );
  14496. /**
  14497. * Cineon tone mapping.
  14498. *
  14499. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  14500. *
  14501. * @method
  14502. * @param {Node<vec3>} color - The color that should be tone mapped.
  14503. * @param {Node<float>} exposure - The exposure.
  14504. * @return {Node<vec3>} The tone mapped color.
  14505. */
  14506. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14507. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  14508. color = color.mul( exposure );
  14509. color = color.sub( 0.004 ).max( 0.0 );
  14510. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  14511. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  14512. return a.div( b ).pow( 2.2 );
  14513. } ).setLayout( {
  14514. name: 'cineonToneMapping',
  14515. type: 'vec3',
  14516. inputs: [
  14517. { name: 'color', type: 'vec3' },
  14518. { name: 'exposure', type: 'float' }
  14519. ]
  14520. } );
  14521. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  14522. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14523. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  14524. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  14525. return a.div( b );
  14526. } );
  14527. /**
  14528. * ACESFilmic tone mapping.
  14529. *
  14530. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  14531. *
  14532. * @method
  14533. * @param {Node<vec3>} color - The color that should be tone mapped.
  14534. * @param {Node<float>} exposure - The exposure.
  14535. * @return {Node<vec3>} The tone mapped color.
  14536. */
  14537. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14538. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  14539. const ACESInputMat = mat3(
  14540. 0.59719, 0.35458, 0.04823,
  14541. 0.07600, 0.90834, 0.01566,
  14542. 0.02840, 0.13383, 0.83777
  14543. );
  14544. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  14545. const ACESOutputMat = mat3(
  14546. 1.60475, - 0.53108, - 0.07367,
  14547. - 0.10208, 1.10813, - 0.00605,
  14548. - 0.00327, - 0.07276, 1.07602
  14549. );
  14550. color = color.mul( exposure ).div( 0.6 );
  14551. color = ACESInputMat.mul( color );
  14552. // Apply RRT and ODT
  14553. color = RRTAndODTFit( color );
  14554. color = ACESOutputMat.mul( color );
  14555. // Clamp to [0, 1]
  14556. return color.clamp();
  14557. } ).setLayout( {
  14558. name: 'acesFilmicToneMapping',
  14559. type: 'vec3',
  14560. inputs: [
  14561. { name: 'color', type: 'vec3' },
  14562. { name: 'exposure', type: 'float' }
  14563. ]
  14564. } );
  14565. 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 ) );
  14566. 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 ) );
  14567. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  14568. const x = vec3( x_immutable ).toVar();
  14569. const x2 = vec3( x.mul( x ) ).toVar();
  14570. const x4 = vec3( x2.mul( x2 ) ).toVar();
  14571. 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 ) ) ) );
  14572. } );
  14573. /**
  14574. * AgX tone mapping.
  14575. *
  14576. * @method
  14577. * @param {Node<vec3>} color - The color that should be tone mapped.
  14578. * @param {Node<float>} exposure - The exposure.
  14579. * @return {Node<vec3>} The tone mapped color.
  14580. */
  14581. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14582. const colortone = vec3( color ).toVar();
  14583. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  14584. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  14585. const AgxMinEv = float( - 12.47393 );
  14586. const AgxMaxEv = float( 4.026069 );
  14587. colortone.mulAssign( exposure );
  14588. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  14589. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  14590. colortone.assign( max$1( colortone, 1e-10 ) );
  14591. colortone.assign( log2( colortone ) );
  14592. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  14593. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14594. colortone.assign( agxDefaultContrastApprox( colortone ) );
  14595. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  14596. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  14597. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  14598. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14599. return colortone;
  14600. } ).setLayout( {
  14601. name: 'agxToneMapping',
  14602. type: 'vec3',
  14603. inputs: [
  14604. { name: 'color', type: 'vec3' },
  14605. { name: 'exposure', type: 'float' }
  14606. ]
  14607. } );
  14608. /**
  14609. * Neutral tone mapping.
  14610. *
  14611. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  14612. *
  14613. * @method
  14614. * @param {Node<vec3>} color - The color that should be tone mapped.
  14615. * @param {Node<float>} exposure - The exposure.
  14616. * @return {Node<vec3>} The tone mapped color.
  14617. */
  14618. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14619. const StartCompression = float( 0.8 - 0.04 );
  14620. const Desaturation = float( 0.15 );
  14621. color = color.mul( exposure );
  14622. const x = min$1( color.r, min$1( color.g, color.b ) );
  14623. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  14624. color.subAssign( offset );
  14625. const peak = max$1( color.r, max$1( color.g, color.b ) );
  14626. If( peak.lessThan( StartCompression ), () => {
  14627. return color;
  14628. } );
  14629. const d = sub( 1, StartCompression );
  14630. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  14631. color.mulAssign( newPeak.div( peak ) );
  14632. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  14633. return mix( color, vec3( newPeak ), g );
  14634. } ).setLayout( {
  14635. name: 'neutralToneMapping',
  14636. type: 'vec3',
  14637. inputs: [
  14638. { name: 'color', type: 'vec3' },
  14639. { name: 'exposure', type: 'float' }
  14640. ]
  14641. } );
  14642. /**
  14643. * This class represents native code sections. It is the base
  14644. * class for modules like {@link FunctionNode} which allows to implement
  14645. * functions with native shader languages.
  14646. *
  14647. * @augments Node
  14648. */
  14649. class CodeNode extends Node {
  14650. static get type() {
  14651. return 'CodeNode';
  14652. }
  14653. /**
  14654. * Constructs a new code node.
  14655. *
  14656. * @param {String} [code=''] - The native code.
  14657. * @param {Array<Node>} [includes=[]] - An array of includes.
  14658. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14659. */
  14660. constructor( code = '', includes = [], language = '' ) {
  14661. super( 'code' );
  14662. /**
  14663. * This flag can be used for type testing.
  14664. *
  14665. * @type {Boolean}
  14666. * @readonly
  14667. * @default true
  14668. */
  14669. this.isCodeNode = true;
  14670. /**
  14671. * The native code.
  14672. *
  14673. * @type {String}
  14674. * @default ''
  14675. */
  14676. this.code = code;
  14677. /**
  14678. * An array of includes
  14679. *
  14680. * @type {Array<Node>}
  14681. * @default []
  14682. */
  14683. this.includes = includes;
  14684. /**
  14685. * The used language.
  14686. *
  14687. * @type {('js'|'wgsl'|'glsl')}
  14688. * @default ''
  14689. */
  14690. this.language = language;
  14691. }
  14692. /**
  14693. * The method is overwritten so it always returns `true`.
  14694. *
  14695. * @return {Boolean} Whether this node is global or not.
  14696. */
  14697. isGlobal() {
  14698. return true;
  14699. }
  14700. /**
  14701. * Sets the includes of this code node.
  14702. *
  14703. * @param {Array<Node>} includes - The includes to set.
  14704. * @return {CodeNode} A reference to this node.
  14705. */
  14706. setIncludes( includes ) {
  14707. this.includes = includes;
  14708. return this;
  14709. }
  14710. /**
  14711. * Returns the includes of this code node.
  14712. *
  14713. * @param {NodeBuilder} builder - The current node builder.
  14714. * @return {Array<Node>} The includes.
  14715. */
  14716. getIncludes( /*builder*/ ) {
  14717. return this.includes;
  14718. }
  14719. generate( builder ) {
  14720. const includes = this.getIncludes( builder );
  14721. for ( const include of includes ) {
  14722. include.build( builder );
  14723. }
  14724. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  14725. nodeCode.code = this.code;
  14726. return nodeCode.code;
  14727. }
  14728. serialize( data ) {
  14729. super.serialize( data );
  14730. data.code = this.code;
  14731. data.language = this.language;
  14732. }
  14733. deserialize( data ) {
  14734. super.deserialize( data );
  14735. this.code = data.code;
  14736. this.language = data.language;
  14737. }
  14738. }
  14739. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  14740. const js = ( src, includes ) => code( src, includes, 'js' );
  14741. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  14742. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  14743. /**
  14744. * This class represents a native shader function. It can be used to implement
  14745. * certain aspects of a node material with native shader code. There are two predefined
  14746. * TSL functions for easier usage.
  14747. *
  14748. * - `wgslFn`: Creates a WGSL function node.
  14749. * - `glslFn`: Creates a GLSL function node.
  14750. *
  14751. * A basic example with one include looks like so:
  14752. *
  14753. * ```js
  14754. * const desaturateWGSLFn = wgslFn( `
  14755. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  14756. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  14757. * return vec3<f32>( dot( lum, color ) );
  14758. * }`
  14759. *);
  14760. * const someWGSLFn = wgslFn( `
  14761. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  14762. * return desaturate( color );
  14763. * }
  14764. * `, [ desaturateWGSLFn ] );
  14765. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  14766. *```
  14767. * @augments CodeNode
  14768. */
  14769. class FunctionNode extends CodeNode {
  14770. static get type() {
  14771. return 'FunctionNode';
  14772. }
  14773. /**
  14774. * Constructs a new function node.
  14775. *
  14776. * @param {String} [code=''] - The native code.
  14777. * @param {Array<Node>} [includes=[]] - An array of includes.
  14778. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14779. */
  14780. constructor( code = '', includes = [], language = '' ) {
  14781. super( code, includes, language );
  14782. }
  14783. getNodeType( builder ) {
  14784. return this.getNodeFunction( builder ).type;
  14785. }
  14786. /**
  14787. * Returns the inputs of this function node.
  14788. *
  14789. * @param {NodeBuilder} builder - The current node builder.
  14790. * @return {Array<NodeFunctionInput>} The inputs.
  14791. */
  14792. getInputs( builder ) {
  14793. return this.getNodeFunction( builder ).inputs;
  14794. }
  14795. /**
  14796. * Returns the node function for this function node.
  14797. *
  14798. * @param {NodeBuilder} builder - The current node builder.
  14799. * @return {NodeFunction} The node function.
  14800. */
  14801. getNodeFunction( builder ) {
  14802. const nodeData = builder.getDataFromNode( this );
  14803. let nodeFunction = nodeData.nodeFunction;
  14804. if ( nodeFunction === undefined ) {
  14805. nodeFunction = builder.parser.parseFunction( this.code );
  14806. nodeData.nodeFunction = nodeFunction;
  14807. }
  14808. return nodeFunction;
  14809. }
  14810. generate( builder, output ) {
  14811. super.generate( builder );
  14812. const nodeFunction = this.getNodeFunction( builder );
  14813. const name = nodeFunction.name;
  14814. const type = nodeFunction.type;
  14815. const nodeCode = builder.getCodeFromNode( this, type );
  14816. if ( name !== '' ) {
  14817. // use a custom property name
  14818. nodeCode.name = name;
  14819. }
  14820. const propertyName = builder.getPropertyName( nodeCode );
  14821. const code = this.getNodeFunction( builder ).getCode( propertyName );
  14822. nodeCode.code = code + '\n';
  14823. if ( output === 'property' ) {
  14824. return propertyName;
  14825. } else {
  14826. return builder.format( `${ propertyName }()`, type, output );
  14827. }
  14828. }
  14829. }
  14830. const nativeFn = ( code, includes = [], language = '' ) => {
  14831. for ( let i = 0; i < includes.length; i ++ ) {
  14832. const include = includes[ i ];
  14833. // TSL Function: glslFn, wgslFn
  14834. if ( typeof include === 'function' ) {
  14835. includes[ i ] = include.functionNode;
  14836. }
  14837. }
  14838. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  14839. const fn = ( ...params ) => functionNode.call( ...params );
  14840. fn.functionNode = functionNode;
  14841. return fn;
  14842. };
  14843. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  14844. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  14845. class ScriptableValueNode extends Node {
  14846. static get type() {
  14847. return 'ScriptableValueNode';
  14848. }
  14849. constructor( value = null ) {
  14850. super();
  14851. this._value = value;
  14852. this._cache = null;
  14853. this.inputType = null;
  14854. this.outputType = null;
  14855. this.events = new EventDispatcher();
  14856. this.isScriptableValueNode = true;
  14857. }
  14858. get isScriptableOutputNode() {
  14859. return this.outputType !== null;
  14860. }
  14861. set value( val ) {
  14862. if ( this._value === val ) return;
  14863. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  14864. URL.revokeObjectURL( this._cache );
  14865. this._cache = null;
  14866. }
  14867. this._value = val;
  14868. this.events.dispatchEvent( { type: 'change' } );
  14869. this.refresh();
  14870. }
  14871. get value() {
  14872. return this._value;
  14873. }
  14874. refresh() {
  14875. this.events.dispatchEvent( { type: 'refresh' } );
  14876. }
  14877. getValue() {
  14878. const value = this.value;
  14879. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  14880. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  14881. } else if ( value && value.value !== null && value.value !== undefined && (
  14882. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  14883. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  14884. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  14885. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  14886. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  14887. ( this.inputType === 'Color' && value.value.isColor ) ||
  14888. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  14889. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  14890. ) ) {
  14891. return value.value;
  14892. }
  14893. return this._cache || value;
  14894. }
  14895. getNodeType( builder ) {
  14896. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  14897. }
  14898. setup() {
  14899. return this.value && this.value.isNode ? this.value : float();
  14900. }
  14901. serialize( data ) {
  14902. super.serialize( data );
  14903. if ( this.value !== null ) {
  14904. if ( this.inputType === 'ArrayBuffer' ) {
  14905. data.value = arrayBufferToBase64( this.value );
  14906. } else {
  14907. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  14908. }
  14909. } else {
  14910. data.value = null;
  14911. }
  14912. data.inputType = this.inputType;
  14913. data.outputType = this.outputType;
  14914. }
  14915. deserialize( data ) {
  14916. super.deserialize( data );
  14917. let value = null;
  14918. if ( data.value !== null ) {
  14919. if ( data.inputType === 'ArrayBuffer' ) {
  14920. value = base64ToArrayBuffer( data.value );
  14921. } else if ( data.inputType === 'Texture' ) {
  14922. value = data.meta.textures[ data.value ];
  14923. } else {
  14924. value = data.meta.nodes[ data.value ] || null;
  14925. }
  14926. }
  14927. this.value = value;
  14928. this.inputType = data.inputType;
  14929. this.outputType = data.outputType;
  14930. }
  14931. }
  14932. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  14933. class Resources extends Map {
  14934. get( key, callback = null, ...params ) {
  14935. if ( this.has( key ) ) return super.get( key );
  14936. if ( callback !== null ) {
  14937. const value = callback( ...params );
  14938. this.set( key, value );
  14939. return value;
  14940. }
  14941. }
  14942. }
  14943. class Parameters {
  14944. constructor( scriptableNode ) {
  14945. this.scriptableNode = scriptableNode;
  14946. }
  14947. get parameters() {
  14948. return this.scriptableNode.parameters;
  14949. }
  14950. get layout() {
  14951. return this.scriptableNode.getLayout();
  14952. }
  14953. getInputLayout( id ) {
  14954. return this.scriptableNode.getInputLayout( id );
  14955. }
  14956. get( name ) {
  14957. const param = this.parameters[ name ];
  14958. const value = param ? param.getValue() : null;
  14959. return value;
  14960. }
  14961. }
  14962. const ScriptableNodeResources = new Resources();
  14963. class ScriptableNode extends Node {
  14964. static get type() {
  14965. return 'ScriptableNode';
  14966. }
  14967. constructor( codeNode = null, parameters = {} ) {
  14968. super();
  14969. this.codeNode = codeNode;
  14970. this.parameters = parameters;
  14971. this._local = new Resources();
  14972. this._output = scriptableValue();
  14973. this._outputs = {};
  14974. this._source = this.source;
  14975. this._method = null;
  14976. this._object = null;
  14977. this._value = null;
  14978. this._needsOutputUpdate = true;
  14979. this.onRefresh = this.onRefresh.bind( this );
  14980. this.isScriptableNode = true;
  14981. }
  14982. get source() {
  14983. return this.codeNode ? this.codeNode.code : '';
  14984. }
  14985. setLocal( name, value ) {
  14986. return this._local.set( name, value );
  14987. }
  14988. getLocal( name ) {
  14989. return this._local.get( name );
  14990. }
  14991. onRefresh() {
  14992. this._refresh();
  14993. }
  14994. getInputLayout( id ) {
  14995. for ( const element of this.getLayout() ) {
  14996. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  14997. return element;
  14998. }
  14999. }
  15000. }
  15001. getOutputLayout( id ) {
  15002. for ( const element of this.getLayout() ) {
  15003. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  15004. return element;
  15005. }
  15006. }
  15007. }
  15008. setOutput( name, value ) {
  15009. const outputs = this._outputs;
  15010. if ( outputs[ name ] === undefined ) {
  15011. outputs[ name ] = scriptableValue( value );
  15012. } else {
  15013. outputs[ name ].value = value;
  15014. }
  15015. return this;
  15016. }
  15017. getOutput( name ) {
  15018. return this._outputs[ name ];
  15019. }
  15020. getParameter( name ) {
  15021. return this.parameters[ name ];
  15022. }
  15023. setParameter( name, value ) {
  15024. const parameters = this.parameters;
  15025. if ( value && value.isScriptableNode ) {
  15026. this.deleteParameter( name );
  15027. parameters[ name ] = value;
  15028. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  15029. } else if ( value && value.isScriptableValueNode ) {
  15030. this.deleteParameter( name );
  15031. parameters[ name ] = value;
  15032. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  15033. } else if ( parameters[ name ] === undefined ) {
  15034. parameters[ name ] = scriptableValue( value );
  15035. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  15036. } else {
  15037. parameters[ name ].value = value;
  15038. }
  15039. return this;
  15040. }
  15041. getValue() {
  15042. return this.getDefaultOutput().getValue();
  15043. }
  15044. deleteParameter( name ) {
  15045. let valueNode = this.parameters[ name ];
  15046. if ( valueNode ) {
  15047. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  15048. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  15049. }
  15050. return this;
  15051. }
  15052. clearParameters() {
  15053. for ( const name of Object.keys( this.parameters ) ) {
  15054. this.deleteParameter( name );
  15055. }
  15056. this.needsUpdate = true;
  15057. return this;
  15058. }
  15059. call( name, ...params ) {
  15060. const object = this.getObject();
  15061. const method = object[ name ];
  15062. if ( typeof method === 'function' ) {
  15063. return method( ...params );
  15064. }
  15065. }
  15066. async callAsync( name, ...params ) {
  15067. const object = this.getObject();
  15068. const method = object[ name ];
  15069. if ( typeof method === 'function' ) {
  15070. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  15071. }
  15072. }
  15073. getNodeType( builder ) {
  15074. return this.getDefaultOutputNode().getNodeType( builder );
  15075. }
  15076. refresh( output = null ) {
  15077. if ( output !== null ) {
  15078. this.getOutput( output ).refresh();
  15079. } else {
  15080. this._refresh();
  15081. }
  15082. }
  15083. getObject() {
  15084. if ( this.needsUpdate ) this.dispose();
  15085. if ( this._object !== null ) return this._object;
  15086. //
  15087. const refresh = () => this.refresh();
  15088. const setOutput = ( id, value ) => this.setOutput( id, value );
  15089. const parameters = new Parameters( this );
  15090. const THREE = ScriptableNodeResources.get( 'THREE' );
  15091. const TSL = ScriptableNodeResources.get( 'TSL' );
  15092. const method = this.getMethod( this.codeNode );
  15093. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  15094. this._object = method( ...params );
  15095. const layout = this._object.layout;
  15096. if ( layout ) {
  15097. if ( layout.cache === false ) {
  15098. this._local.clear();
  15099. }
  15100. // default output
  15101. this._output.outputType = layout.outputType || null;
  15102. if ( Array.isArray( layout.elements ) ) {
  15103. for ( const element of layout.elements ) {
  15104. const id = element.id || element.name;
  15105. if ( element.inputType ) {
  15106. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  15107. this.getParameter( id ).inputType = element.inputType;
  15108. }
  15109. if ( element.outputType ) {
  15110. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  15111. this.getOutput( id ).outputType = element.outputType;
  15112. }
  15113. }
  15114. }
  15115. }
  15116. return this._object;
  15117. }
  15118. deserialize( data ) {
  15119. super.deserialize( data );
  15120. for ( const name in this.parameters ) {
  15121. let valueNode = this.parameters[ name ];
  15122. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  15123. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  15124. }
  15125. }
  15126. getLayout() {
  15127. return this.getObject().layout;
  15128. }
  15129. getDefaultOutputNode() {
  15130. const output = this.getDefaultOutput().value;
  15131. if ( output && output.isNode ) {
  15132. return output;
  15133. }
  15134. return float();
  15135. }
  15136. getDefaultOutput() {
  15137. return this._exec()._output;
  15138. }
  15139. getMethod() {
  15140. if ( this.needsUpdate ) this.dispose();
  15141. if ( this._method !== null ) return this._method;
  15142. //
  15143. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  15144. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  15145. const properties = interfaceProps.join( ', ' );
  15146. const declarations = 'var ' + properties + '; var output = {};\n';
  15147. const returns = '\nreturn { ...output, ' + properties + ' };';
  15148. const code = declarations + this.codeNode.code + returns;
  15149. //
  15150. this._method = new Function( ...parametersProps, code );
  15151. return this._method;
  15152. }
  15153. dispose() {
  15154. if ( this._method === null ) return;
  15155. if ( this._object && typeof this._object.dispose === 'function' ) {
  15156. this._object.dispose();
  15157. }
  15158. this._method = null;
  15159. this._object = null;
  15160. this._source = null;
  15161. this._value = null;
  15162. this._needsOutputUpdate = true;
  15163. this._output.value = null;
  15164. this._outputs = {};
  15165. }
  15166. setup() {
  15167. return this.getDefaultOutputNode();
  15168. }
  15169. getCacheKey( force ) {
  15170. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  15171. for ( const param in this.parameters ) {
  15172. values.push( this.parameters[ param ].getCacheKey( force ) );
  15173. }
  15174. return hashArray( values );
  15175. }
  15176. set needsUpdate( value ) {
  15177. if ( value === true ) this.dispose();
  15178. }
  15179. get needsUpdate() {
  15180. return this.source !== this._source;
  15181. }
  15182. _exec() {
  15183. if ( this.codeNode === null ) return this;
  15184. if ( this._needsOutputUpdate === true ) {
  15185. this._value = this.call( 'main' );
  15186. this._needsOutputUpdate = false;
  15187. }
  15188. this._output.value = this._value;
  15189. return this;
  15190. }
  15191. _refresh() {
  15192. this.needsUpdate = true;
  15193. this._exec();
  15194. this._output.refresh();
  15195. }
  15196. }
  15197. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  15198. /**
  15199. * This class can be used to configure a fog for the scene.
  15200. * Nodes of this type are assigned to `Scene.fogNode`.
  15201. *
  15202. * @augments Node
  15203. */
  15204. class FogNode extends Node {
  15205. static get type() {
  15206. return 'FogNode';
  15207. }
  15208. /**
  15209. * Constructs a new fog node.
  15210. *
  15211. * @param {Node} colorNode - Defines the color of the fog.
  15212. * @param {Node} factorNode - Defines how the fog is factored in the scene.
  15213. */
  15214. constructor( colorNode, factorNode ) {
  15215. super( 'float' );
  15216. /**
  15217. * This flag can be used for type testing.
  15218. *
  15219. * @type {Boolean}
  15220. * @readonly
  15221. * @default true
  15222. */
  15223. this.isFogNode = true;
  15224. /**
  15225. * Defines the color of the fog.
  15226. *
  15227. * @type {Node?}
  15228. */
  15229. this.colorNode = colorNode;
  15230. /**
  15231. * Defines how the fog is factored in the scene.
  15232. *
  15233. * @type {Node?}
  15234. */
  15235. this.factorNode = factorNode;
  15236. }
  15237. /**
  15238. * Returns a node that represents the `z` coordinate in view space
  15239. * for the current fragment. It's a different representation of the
  15240. * default depth value.
  15241. *
  15242. * This value can be part of a computation that defines how the fog
  15243. * density increases when moving away from the camera.
  15244. *
  15245. * @param {NodeBuilder} builder - The current node builder.
  15246. * @return {Node} The viewZ node.
  15247. */
  15248. getViewZNode( builder ) {
  15249. let viewZ;
  15250. const getViewZ = builder.context.getViewZ;
  15251. if ( getViewZ !== undefined ) {
  15252. viewZ = getViewZ( this );
  15253. }
  15254. return ( viewZ || positionView.z ).negate();
  15255. }
  15256. setup() {
  15257. return this.factorNode;
  15258. }
  15259. }
  15260. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  15261. /**
  15262. * Represents a range fog. The fog is smoothly interpolated
  15263. * between a range defined via near and far values.
  15264. *
  15265. * @augments FogNode
  15266. */
  15267. class FogRangeNode extends FogNode {
  15268. static get type() {
  15269. return 'FogRangeNode';
  15270. }
  15271. /**
  15272. * Constructs a new range node.
  15273. *
  15274. * @param {Node} colorNode - Defines the color of the fog.
  15275. * @param {Node} nearNode - Defines the near value.
  15276. * @param {Node} farNode - Defines the far value.
  15277. */
  15278. constructor( colorNode, nearNode, farNode ) {
  15279. super( colorNode, null );
  15280. /**
  15281. * This flag can be used for type testing.
  15282. *
  15283. * @type {Boolean}
  15284. * @readonly
  15285. * @default true
  15286. */
  15287. this.isFogRangeNode = true;
  15288. /**
  15289. * Defines the near value.
  15290. *
  15291. * @type {Node}
  15292. */
  15293. this.nearNode = nearNode;
  15294. /**
  15295. * Defines the far value.
  15296. *
  15297. * @type {Node}
  15298. */
  15299. this.farNode = farNode;
  15300. }
  15301. setup( builder ) {
  15302. const viewZ = this.getViewZNode( builder );
  15303. return smoothstep( this.nearNode, this.farNode, viewZ );
  15304. }
  15305. }
  15306. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  15307. /**
  15308. * Represents an exponential squared fog. This type of fog gives
  15309. * a clear view near the camera and a faster than exponentially
  15310. * densening fog farther from the camera.
  15311. *
  15312. * @augments FogNode
  15313. */
  15314. class FogExp2Node extends FogNode {
  15315. static get type() {
  15316. return 'FogExp2Node';
  15317. }
  15318. /**
  15319. * Constructs a new exponential squared fog node.
  15320. *
  15321. * @param {Node} colorNode - Defines the color of the fog.
  15322. * @param {Node} densityNode - Defines the fog density.
  15323. */
  15324. constructor( colorNode, densityNode ) {
  15325. super( colorNode, null );
  15326. /**
  15327. * This flag can be used for type testing.
  15328. *
  15329. * @type {Boolean}
  15330. * @readonly
  15331. * @default true
  15332. */
  15333. this.isFogExp2Node = true;
  15334. /**
  15335. * Defines the fog density.
  15336. *
  15337. * @type {Node}
  15338. */
  15339. this.densityNode = densityNode;
  15340. }
  15341. setup( builder ) {
  15342. const viewZ = this.getViewZNode( builder );
  15343. const density = this.densityNode;
  15344. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  15345. }
  15346. }
  15347. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  15348. let min = null;
  15349. let max = null;
  15350. /**
  15351. * `RangeNode` generates random instanced attribute data in a defined range.
  15352. * An exemplary use case for this utility node is to generate random per-instance
  15353. * colors:
  15354. * ```js
  15355. * const material = new MeshBasicNodeMaterial();
  15356. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  15357. * const mesh = new InstancedMesh( geometry, material, count );
  15358. * ```
  15359. * @augments Node
  15360. */
  15361. class RangeNode extends Node {
  15362. static get type() {
  15363. return 'RangeNode';
  15364. }
  15365. /**
  15366. * Constructs a new range node.
  15367. *
  15368. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  15369. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  15370. */
  15371. constructor( minNode = float(), maxNode = float() ) {
  15372. super();
  15373. /**
  15374. * A node defining the lower bound of the range.
  15375. *
  15376. * @type {Node<any>}
  15377. * @default float()
  15378. */
  15379. this.minNode = minNode;
  15380. /**
  15381. * A node defining the upper bound of the range.
  15382. *
  15383. * @type {Node<any>}
  15384. * @default float()
  15385. */
  15386. this.maxNode = maxNode;
  15387. }
  15388. /**
  15389. * Returns the vector length which is computed based on the range definition.
  15390. *
  15391. * @param {NodeBuilder} builder - The current node builder.
  15392. * @return {Number} The vector length.
  15393. */
  15394. getVectorLength( builder ) {
  15395. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  15396. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  15397. return minLength > maxLength ? minLength : maxLength;
  15398. }
  15399. /**
  15400. * This method is overwritten since the node type is inferred from range definition.
  15401. *
  15402. * @param {NodeBuilder} builder - The current node builder.
  15403. * @return {String} The node type.
  15404. */
  15405. getNodeType( builder ) {
  15406. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  15407. }
  15408. setup( builder ) {
  15409. const object = builder.object;
  15410. let output = null;
  15411. if ( object.count > 1 ) {
  15412. const minValue = this.minNode.value;
  15413. const maxValue = this.maxNode.value;
  15414. const minLength = builder.getTypeLength( getValueType( minValue ) );
  15415. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  15416. min = min || new Vector4();
  15417. max = max || new Vector4();
  15418. min.setScalar( 0 );
  15419. max.setScalar( 0 );
  15420. if ( minLength === 1 ) min.setScalar( minValue );
  15421. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  15422. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  15423. if ( maxLength === 1 ) max.setScalar( maxValue );
  15424. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  15425. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  15426. const stride = 4;
  15427. const length = stride * object.count;
  15428. const array = new Float32Array( length );
  15429. for ( let i = 0; i < length; i ++ ) {
  15430. const index = i % stride;
  15431. const minElementValue = min.getComponent( index );
  15432. const maxElementValue = max.getComponent( index );
  15433. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  15434. }
  15435. const nodeType = this.getNodeType( builder );
  15436. if ( object.count <= 4096 ) {
  15437. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  15438. } else {
  15439. // TODO: Improve anonymous buffer attribute creation removing this part
  15440. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  15441. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  15442. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  15443. }
  15444. } else {
  15445. output = float( 0 );
  15446. }
  15447. return output;
  15448. }
  15449. }
  15450. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  15451. class ComputeBuiltinNode extends Node {
  15452. static get type() {
  15453. return 'ComputeBuiltinNode';
  15454. }
  15455. constructor( builtinName, nodeType ) {
  15456. super( nodeType );
  15457. this._builtinName = builtinName;
  15458. }
  15459. getHash( builder ) {
  15460. return this.getBuiltinName( builder );
  15461. }
  15462. getNodeType( /*builder*/ ) {
  15463. return this.nodeType;
  15464. }
  15465. setBuiltinName( builtinName ) {
  15466. this._builtinName = builtinName;
  15467. return this;
  15468. }
  15469. getBuiltinName( /*builder*/ ) {
  15470. return this._builtinName;
  15471. }
  15472. hasBuiltin( builder ) {
  15473. builder.hasBuiltin( this._builtinName );
  15474. }
  15475. generate( builder, output ) {
  15476. const builtinName = this.getBuiltinName( builder );
  15477. const nodeType = this.getNodeType( builder );
  15478. if ( builder.shaderStage === 'compute' ) {
  15479. return builder.format( builtinName, nodeType, output );
  15480. } else {
  15481. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  15482. return builder.generateConst( nodeType );
  15483. }
  15484. }
  15485. serialize( data ) {
  15486. super.serialize( data );
  15487. data.global = this.global;
  15488. data._builtinName = this._builtinName;
  15489. }
  15490. deserialize( data ) {
  15491. super.deserialize( data );
  15492. this.global = data.global;
  15493. this._builtinName = data._builtinName;
  15494. }
  15495. }
  15496. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  15497. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  15498. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  15499. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  15500. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  15501. class BarrierNode extends Node {
  15502. constructor( scope ) {
  15503. super();
  15504. this.scope = scope;
  15505. }
  15506. generate( builder ) {
  15507. const { scope } = this;
  15508. const { renderer } = builder;
  15509. if ( renderer.backend.isWebGLBackend === true ) {
  15510. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  15511. } else {
  15512. builder.addLineFlowCode( `${scope}Barrier()`, this );
  15513. }
  15514. }
  15515. }
  15516. const barrier = nodeProxy( BarrierNode );
  15517. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  15518. const storageBarrier = () => barrier( 'storage' ).append();
  15519. const textureBarrier = () => barrier( 'texture' ).append();
  15520. class WorkgroupInfoElementNode extends ArrayElementNode {
  15521. constructor( workgroupInfoNode, indexNode ) {
  15522. super( workgroupInfoNode, indexNode );
  15523. this.isWorkgroupInfoElementNode = true;
  15524. }
  15525. generate( builder, output ) {
  15526. let snippet;
  15527. const isAssignContext = builder.context.assign;
  15528. snippet = super.generate( builder );
  15529. if ( isAssignContext !== true ) {
  15530. const type = this.getNodeType( builder );
  15531. snippet = builder.format( snippet, type, output );
  15532. }
  15533. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  15534. return snippet;
  15535. }
  15536. }
  15537. class WorkgroupInfoNode extends Node {
  15538. constructor( scope, bufferType, bufferCount = 0 ) {
  15539. super( bufferType );
  15540. this.bufferType = bufferType;
  15541. this.bufferCount = bufferCount;
  15542. this.isWorkgroupInfoNode = true;
  15543. this.scope = scope;
  15544. }
  15545. label( name ) {
  15546. this.name = name;
  15547. return this;
  15548. }
  15549. getHash() {
  15550. return this.uuid;
  15551. }
  15552. setScope( scope ) {
  15553. this.scope = scope;
  15554. return this;
  15555. }
  15556. getInputType( /*builder*/ ) {
  15557. return `${this.scope}Array`;
  15558. }
  15559. element( indexNode ) {
  15560. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  15561. }
  15562. generate( builder ) {
  15563. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  15564. }
  15565. }
  15566. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  15567. class AtomicFunctionNode extends TempNode {
  15568. static get type() {
  15569. return 'AtomicFunctionNode';
  15570. }
  15571. constructor( method, pointerNode, valueNode, storeNode = null ) {
  15572. super( 'uint' );
  15573. this.method = method;
  15574. this.pointerNode = pointerNode;
  15575. this.valueNode = valueNode;
  15576. this.storeNode = storeNode;
  15577. }
  15578. getInputType( builder ) {
  15579. return this.pointerNode.getNodeType( builder );
  15580. }
  15581. getNodeType( builder ) {
  15582. return this.getInputType( builder );
  15583. }
  15584. generate( builder ) {
  15585. const method = this.method;
  15586. const type = this.getNodeType( builder );
  15587. const inputType = this.getInputType( builder );
  15588. const a = this.pointerNode;
  15589. const b = this.valueNode;
  15590. const params = [];
  15591. params.push( `&${ a.build( builder, inputType ) }` );
  15592. params.push( b.build( builder, inputType ) );
  15593. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  15594. if ( this.storeNode !== null ) {
  15595. const varSnippet = this.storeNode.build( builder, inputType );
  15596. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  15597. } else {
  15598. builder.addLineFlowCode( methodSnippet, this );
  15599. }
  15600. }
  15601. }
  15602. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  15603. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  15604. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  15605. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  15606. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  15607. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  15608. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  15609. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  15610. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  15611. const atomicNode = nodeProxy( AtomicFunctionNode );
  15612. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  15613. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  15614. node.append();
  15615. return node;
  15616. };
  15617. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  15618. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  15619. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  15620. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  15621. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  15622. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  15623. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  15624. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  15625. let uniformsLib;
  15626. function getLightData( light ) {
  15627. uniformsLib = uniformsLib || new WeakMap();
  15628. let uniforms = uniformsLib.get( light );
  15629. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  15630. return uniforms;
  15631. }
  15632. function lightShadowMatrix( light ) {
  15633. const data = getLightData( light );
  15634. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  15635. if ( light.castShadow !== true ) {
  15636. light.shadow.updateMatrices( light );
  15637. }
  15638. return light.shadow.matrix;
  15639. } ) );
  15640. }
  15641. function lightProjectionUV( light ) {
  15642. const data = getLightData( light );
  15643. if ( data.projectionUV === undefined ) {
  15644. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  15645. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  15646. }
  15647. return data.projectionUV;
  15648. }
  15649. function lightPosition( light ) {
  15650. const data = getLightData( light );
  15651. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  15652. }
  15653. function lightTargetPosition( light ) {
  15654. const data = getLightData( light );
  15655. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  15656. }
  15657. function lightViewPosition( light ) {
  15658. const data = getLightData( light );
  15659. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  15660. self.value = self.value || new Vector3();
  15661. self.value.setFromMatrixPosition( light.matrixWorld );
  15662. self.value.applyMatrix4( camera.matrixWorldInverse );
  15663. } ) );
  15664. }
  15665. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  15666. const sortLights = ( lights ) => {
  15667. return lights.sort( ( a, b ) => a.id - b.id );
  15668. };
  15669. const getLightNodeById = ( id, lightNodes ) => {
  15670. for ( const lightNode of lightNodes ) {
  15671. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  15672. return lightNode;
  15673. }
  15674. }
  15675. return null;
  15676. };
  15677. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  15678. class LightsNode extends Node {
  15679. static get type() {
  15680. return 'LightsNode';
  15681. }
  15682. constructor() {
  15683. super( 'vec3' );
  15684. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  15685. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  15686. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  15687. this._lights = [];
  15688. this._lightNodes = null;
  15689. this._lightNodesHash = null;
  15690. this.global = true;
  15691. }
  15692. /**
  15693. * Overwrites the default `customCacheKey()` implementation by including the
  15694. * light IDs into the cache key.
  15695. *
  15696. * @return {Number} The hash.
  15697. */
  15698. customCacheKey() {
  15699. const lightIDs = [];
  15700. for ( let i = 0; i < lights.length; i ++ ) {
  15701. lightIDs.push( lights[ i ].id );
  15702. }
  15703. return hashArray( lightIDs );
  15704. }
  15705. getHash( builder ) {
  15706. if ( this._lightNodesHash === null ) {
  15707. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15708. const hash = [];
  15709. for ( const lightNode of this._lightNodes ) {
  15710. hash.push( lightNode.getSelf().getHash() );
  15711. }
  15712. this._lightNodesHash = 'lights-' + hash.join( ',' );
  15713. }
  15714. return this._lightNodesHash;
  15715. }
  15716. analyze( builder ) {
  15717. const properties = builder.getDataFromNode( this );
  15718. for ( const node of properties.nodes ) {
  15719. node.build( builder );
  15720. }
  15721. }
  15722. setupLightsNode( builder ) {
  15723. const lightNodes = [];
  15724. const previousLightNodes = this._lightNodes;
  15725. const lights = sortLights( this._lights );
  15726. const nodeLibrary = builder.renderer.library;
  15727. for ( const light of lights ) {
  15728. if ( light.isNode ) {
  15729. lightNodes.push( nodeObject( light ) );
  15730. } else {
  15731. let lightNode = null;
  15732. if ( previousLightNodes !== null ) {
  15733. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  15734. }
  15735. if ( lightNode === null ) {
  15736. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  15737. if ( lightNodeClass === null ) {
  15738. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  15739. continue;
  15740. }
  15741. let lightNode = null;
  15742. if ( ! _lightsNodeRef.has( light ) ) {
  15743. lightNode = nodeObject( new lightNodeClass( light ) );
  15744. _lightsNodeRef.set( light, lightNode );
  15745. } else {
  15746. lightNode = _lightsNodeRef.get( light );
  15747. }
  15748. lightNodes.push( lightNode );
  15749. }
  15750. }
  15751. }
  15752. this._lightNodes = lightNodes;
  15753. }
  15754. setupLights( builder, lightNodes ) {
  15755. for ( const lightNode of lightNodes ) {
  15756. lightNode.build( builder );
  15757. }
  15758. }
  15759. setup( builder ) {
  15760. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15761. const context = builder.context;
  15762. const lightingModel = context.lightingModel;
  15763. let outgoingLightNode = this.outgoingLightNode;
  15764. if ( lightingModel ) {
  15765. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  15766. context.outgoingLight = outgoingLightNode;
  15767. const stack = builder.addStack();
  15768. //
  15769. const properties = builder.getDataFromNode( this );
  15770. properties.nodes = stack.nodes;
  15771. //
  15772. lightingModel.start( context, stack, builder );
  15773. // lights
  15774. this.setupLights( builder, _lightNodes );
  15775. //
  15776. lightingModel.indirect( context, stack, builder );
  15777. //
  15778. const { backdrop, backdropAlpha } = context;
  15779. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  15780. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  15781. if ( backdrop !== null ) {
  15782. if ( backdropAlpha !== null ) {
  15783. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  15784. } else {
  15785. totalDiffuse = vec3( backdrop );
  15786. }
  15787. context.material.transparent = true;
  15788. }
  15789. totalDiffuseNode.assign( totalDiffuse );
  15790. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  15791. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  15792. //
  15793. lightingModel.finish( context, stack, builder );
  15794. //
  15795. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  15796. }
  15797. return outgoingLightNode;
  15798. }
  15799. setLights( lights ) {
  15800. this._lights = lights;
  15801. this._lightNodes = null;
  15802. this._lightNodesHash = null;
  15803. return this;
  15804. }
  15805. getLights() {
  15806. return this._lights;
  15807. }
  15808. get hasLights() {
  15809. return this._lights.length > 0;
  15810. }
  15811. }
  15812. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  15813. class ShadowBaseNode extends Node {
  15814. static get type() {
  15815. return 'ShadowBaseNode';
  15816. }
  15817. constructor( light ) {
  15818. super();
  15819. this.light = light;
  15820. this.updateBeforeType = NodeUpdateType.RENDER;
  15821. this.isShadowBaseNode = true;
  15822. }
  15823. setupShadowPosition( { material } ) {
  15824. // Use assign inside an Fn()
  15825. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  15826. }
  15827. dispose() {
  15828. this.updateBeforeType = NodeUpdateType.NONE;
  15829. }
  15830. }
  15831. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  15832. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  15833. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  15834. let dist = positionWorld.sub( position ).length();
  15835. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  15836. dist = dist.saturate(); // clamp to [ 0, 1 ]
  15837. return dist;
  15838. } );
  15839. const linearShadowDistance = ( light ) => {
  15840. const camera = light.shadow.camera;
  15841. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  15842. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  15843. const referencePosition = objectPosition( light );
  15844. return linearDistance( referencePosition, nearDistance, farDistance );
  15845. };
  15846. const getShadowMaterial = ( light ) => {
  15847. let material = shadowMaterialLib.get( light );
  15848. if ( material === undefined ) {
  15849. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  15850. material = new NodeMaterial();
  15851. material.colorNode = vec4( 0, 0, 0, 1 );
  15852. material.depthNode = depthNode;
  15853. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  15854. material.name = 'ShadowMaterial';
  15855. shadowMaterialLib.set( light, material );
  15856. }
  15857. return material;
  15858. };
  15859. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15860. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  15861. } );
  15862. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15863. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15864. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15865. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15866. const texelSize = vec2( 1 ).div( mapSize );
  15867. const dx0 = texelSize.x.negate().mul( radius );
  15868. const dy0 = texelSize.y.negate().mul( radius );
  15869. const dx1 = texelSize.x.mul( radius );
  15870. const dy1 = texelSize.y.mul( radius );
  15871. const dx2 = dx0.div( 2 );
  15872. const dy2 = dy0.div( 2 );
  15873. const dx3 = dx1.div( 2 );
  15874. const dy3 = dy1.div( 2 );
  15875. return add(
  15876. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  15877. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  15878. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  15879. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  15880. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  15881. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  15882. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  15883. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  15884. depthCompare( shadowCoord.xy, shadowCoord.z ),
  15885. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  15886. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  15887. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  15888. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  15889. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  15890. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  15891. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  15892. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  15893. ).mul( 1 / 17 );
  15894. } );
  15895. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15896. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15897. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15898. const texelSize = vec2( 1 ).div( mapSize );
  15899. const dx = texelSize.x;
  15900. const dy = texelSize.y;
  15901. const uv = shadowCoord.xy;
  15902. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  15903. uv.subAssign( f.mul( texelSize ) );
  15904. return add(
  15905. depthCompare( uv, shadowCoord.z ),
  15906. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  15907. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  15908. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  15909. mix(
  15910. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  15911. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  15912. f.x
  15913. ),
  15914. mix(
  15915. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  15916. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  15917. f.x
  15918. ),
  15919. mix(
  15920. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  15921. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  15922. f.y
  15923. ),
  15924. mix(
  15925. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  15926. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  15927. f.y
  15928. ),
  15929. mix(
  15930. mix(
  15931. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  15932. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  15933. f.x
  15934. ),
  15935. mix(
  15936. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  15937. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  15938. f.x
  15939. ),
  15940. f.y
  15941. )
  15942. ).mul( 1 / 9 );
  15943. } );
  15944. // VSM
  15945. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15946. const occlusion = float( 1 ).toVar();
  15947. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  15948. const hardShadow = step( shadowCoord.z, distribution.x );
  15949. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  15950. const distance = shadowCoord.z.sub( distribution.x );
  15951. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  15952. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  15953. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  15954. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  15955. } );
  15956. return occlusion;
  15957. } );
  15958. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15959. const mean = float( 0 ).toVar();
  15960. const squaredMean = float( 0 ).toVar();
  15961. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15962. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15963. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15964. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15965. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  15966. mean.addAssign( depth );
  15967. squaredMean.addAssign( depth.mul( depth ) );
  15968. } );
  15969. mean.divAssign( samples );
  15970. squaredMean.divAssign( samples );
  15971. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15972. return vec2( mean, std_dev );
  15973. } );
  15974. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15975. const mean = float( 0 ).toVar();
  15976. const squaredMean = float( 0 ).toVar();
  15977. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15978. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15979. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15980. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15981. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  15982. mean.addAssign( distribution.x );
  15983. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  15984. } );
  15985. mean.divAssign( samples );
  15986. squaredMean.divAssign( samples );
  15987. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15988. return vec2( mean, std_dev );
  15989. } );
  15990. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  15991. //
  15992. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  15993. class ShadowNode extends ShadowBaseNode {
  15994. static get type() {
  15995. return 'ShadowNode';
  15996. }
  15997. constructor( light, shadow = null ) {
  15998. super( light );
  15999. this.shadow = shadow || light.shadow;
  16000. this.shadowMap = null;
  16001. this.vsmShadowMapVertical = null;
  16002. this.vsmShadowMapHorizontal = null;
  16003. this.vsmMaterialVertical = null;
  16004. this.vsmMaterialHorizontal = null;
  16005. this._node = null;
  16006. this.isShadowNode = true;
  16007. }
  16008. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  16009. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  16010. .and( shadowCoord.x.lessThanEqual( 1 ) )
  16011. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  16012. .and( shadowCoord.y.lessThanEqual( 1 ) )
  16013. .and( shadowCoord.z.lessThanEqual( 1 ) );
  16014. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  16015. return frustumTest.select( shadowNode, float( 1 ) );
  16016. }
  16017. setupShadowCoord( builder, shadowPosition ) {
  16018. const { shadow } = this;
  16019. const { renderer } = builder;
  16020. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  16021. let shadowCoord = shadowPosition;
  16022. let coordZ;
  16023. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  16024. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  16025. coordZ = shadowCoord.z;
  16026. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  16027. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  16028. }
  16029. } else {
  16030. const w = shadowCoord.w;
  16031. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  16032. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  16033. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  16034. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  16035. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  16036. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  16037. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  16038. }
  16039. shadowCoord = vec3(
  16040. shadowCoord.x,
  16041. shadowCoord.y.oneMinus(), // follow webgpu standards
  16042. coordZ.add( bias )
  16043. );
  16044. return shadowCoord;
  16045. }
  16046. getShadowFilterFn( type ) {
  16047. return _shadowFilterLib[ type ];
  16048. }
  16049. setupShadow( builder ) {
  16050. const { renderer } = builder;
  16051. const { light, shadow } = this;
  16052. const shadowMapType = renderer.shadowMap.type;
  16053. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  16054. depthTexture.compareFunction = LessCompare;
  16055. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  16056. shadowMap.depthTexture = depthTexture;
  16057. shadow.camera.updateProjectionMatrix();
  16058. // VSM
  16059. if ( shadowMapType === VSMShadowMap ) {
  16060. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  16061. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  16062. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  16063. const shadowPassVertical = texture( depthTexture );
  16064. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  16065. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  16066. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  16067. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  16068. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  16069. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  16070. material.name = 'VSMVertical';
  16071. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  16072. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  16073. material.name = 'VSMHorizontal';
  16074. }
  16075. //
  16076. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  16077. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  16078. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  16079. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  16080. //
  16081. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  16082. if ( filterFn === null ) {
  16083. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  16084. }
  16085. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  16086. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  16087. const shadowColor = texture( shadowMap.texture, shadowCoord );
  16088. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  16089. this.shadowMap = shadowMap;
  16090. this.shadow.map = shadowMap;
  16091. return shadowOutput;
  16092. }
  16093. setup( builder ) {
  16094. if ( builder.renderer.shadowMap.enabled === false ) return;
  16095. return Fn( () => {
  16096. let node = this._node;
  16097. this.setupShadowPosition( builder );
  16098. if ( node === null ) {
  16099. this._node = node = this.setupShadow( builder );
  16100. }
  16101. if ( builder.material.shadowNode ) { // @deprecated, r171
  16102. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  16103. }
  16104. if ( builder.material.receivedShadowNode ) {
  16105. node = builder.material.receivedShadowNode( node );
  16106. }
  16107. return node;
  16108. } )();
  16109. }
  16110. renderShadow( frame ) {
  16111. const { shadow, shadowMap, light } = this;
  16112. const { renderer, scene } = frame;
  16113. shadow.updateMatrices( light );
  16114. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  16115. renderer.render( scene, shadow.camera );
  16116. }
  16117. updateShadow( frame ) {
  16118. const { shadowMap, light, shadow } = this;
  16119. const { renderer, scene, camera } = frame;
  16120. const shadowType = renderer.shadowMap.type;
  16121. const depthVersion = shadowMap.depthTexture.version;
  16122. this._depthVersionCached = depthVersion;
  16123. const currentOverrideMaterial = scene.overrideMaterial;
  16124. scene.overrideMaterial = getShadowMaterial( light );
  16125. shadow.camera.layers.mask = camera.layers.mask;
  16126. const currentRenderTarget = renderer.getRenderTarget();
  16127. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  16128. const currentMRT = renderer.getMRT();
  16129. renderer.setMRT( null );
  16130. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  16131. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  16132. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  16133. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  16134. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  16135. }
  16136. } );
  16137. renderer.setRenderTarget( shadowMap );
  16138. this.renderShadow( frame );
  16139. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  16140. // vsm blur pass
  16141. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  16142. this.vsmPass( renderer );
  16143. }
  16144. renderer.setRenderTarget( currentRenderTarget );
  16145. renderer.setMRT( currentMRT );
  16146. scene.overrideMaterial = currentOverrideMaterial;
  16147. }
  16148. vsmPass( renderer ) {
  16149. const { shadow } = this;
  16150. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  16151. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  16152. renderer.setRenderTarget( this.vsmShadowMapVertical );
  16153. _quadMesh$1.material = this.vsmMaterialVertical;
  16154. _quadMesh$1.render( renderer );
  16155. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  16156. _quadMesh$1.material = this.vsmMaterialHorizontal;
  16157. _quadMesh$1.render( renderer );
  16158. }
  16159. dispose() {
  16160. this.shadowMap.dispose();
  16161. this.shadowMap = null;
  16162. if ( this.vsmShadowMapVertical !== null ) {
  16163. this.vsmShadowMapVertical.dispose();
  16164. this.vsmShadowMapVertical = null;
  16165. this.vsmMaterialVertical.dispose();
  16166. this.vsmMaterialVertical = null;
  16167. }
  16168. if ( this.vsmShadowMapHorizontal !== null ) {
  16169. this.vsmShadowMapHorizontal.dispose();
  16170. this.vsmShadowMapHorizontal = null;
  16171. this.vsmMaterialHorizontal.dispose();
  16172. this.vsmMaterialHorizontal = null;
  16173. }
  16174. super.dispose();
  16175. }
  16176. updateBefore( frame ) {
  16177. const { shadow } = this;
  16178. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  16179. if ( needsUpdate ) {
  16180. this.updateShadow( frame );
  16181. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  16182. shadow.needsUpdate = false;
  16183. }
  16184. }
  16185. }
  16186. }
  16187. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  16188. /**
  16189. * Base class for analytic light nodes.
  16190. *
  16191. * @augments LightingNode
  16192. */
  16193. class AnalyticLightNode extends LightingNode {
  16194. static get type() {
  16195. return 'AnalyticLightNode';
  16196. }
  16197. /**
  16198. * Constructs a new analytic light node.
  16199. *
  16200. * @param {Light?} [light=null] - The light source.
  16201. */
  16202. constructor( light = null ) {
  16203. super();
  16204. /**
  16205. * The light source.
  16206. *
  16207. * @type {Light}
  16208. * @default null
  16209. */
  16210. this.light = light;
  16211. /**
  16212. * The light's color value.
  16213. *
  16214. * @type {Color}
  16215. */
  16216. this.color = new Color();
  16217. /**
  16218. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  16219. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  16220. *
  16221. * @type {Node}
  16222. */
  16223. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  16224. /**
  16225. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  16226. * The final color node is represented by a differnt node when using shadows.
  16227. *
  16228. * @type {Node}
  16229. */
  16230. this.baseColorNode = null;
  16231. /**
  16232. * Represents the light's shadow.
  16233. *
  16234. * @type {ShadowNode}
  16235. */
  16236. this.shadowNode = null;
  16237. /**
  16238. * Represents the light's shadow color.
  16239. *
  16240. * @type {Node}
  16241. */
  16242. this.shadowColorNode = null;
  16243. /**
  16244. * This flag can be used for type testing.
  16245. *
  16246. * @type {Boolean}
  16247. * @readonly
  16248. * @default true
  16249. */
  16250. this.isAnalyticLightNode = true;
  16251. /**
  16252. * Overwritten since analytic light nodes are updated
  16253. * once per frame.
  16254. *
  16255. * @type {String}
  16256. * @default 'frame'
  16257. */
  16258. this.updateType = NodeUpdateType.FRAME;
  16259. }
  16260. /**
  16261. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  16262. * `light.id` and `light.castShadow` into the cache key.
  16263. *
  16264. * @return {Number} The custom cache key.
  16265. */
  16266. customCacheKey() {
  16267. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  16268. }
  16269. getHash() {
  16270. return this.light.uuid;
  16271. }
  16272. /**
  16273. * Setups the shadow node for this light. The method exists so concrete light classes
  16274. * can setup different types of shadow nodes.
  16275. *
  16276. * @return {ShadowNode} The created shadow node.
  16277. */
  16278. setupShadowNode() {
  16279. return shadow( this.light );
  16280. }
  16281. /**
  16282. * Setups the shadow for this light. This method is only executed if the light
  16283. * cast shadows and the current build object receives shadows.
  16284. *
  16285. * @param {NodeBuilder} builder - The current node builder.
  16286. */
  16287. setupShadow( builder ) {
  16288. const { renderer } = builder;
  16289. if ( renderer.shadowMap.enabled === false ) return;
  16290. let shadowColorNode = this.shadowColorNode;
  16291. if ( shadowColorNode === null ) {
  16292. const customShadowNode = this.light.shadow.shadowNode;
  16293. let shadowNode;
  16294. if ( customShadowNode !== undefined ) {
  16295. shadowNode = nodeObject( customShadowNode );
  16296. } else {
  16297. shadowNode = this.setupShadowNode( builder );
  16298. }
  16299. this.shadowNode = shadowNode;
  16300. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  16301. this.baseColorNode = this.colorNode;
  16302. }
  16303. //
  16304. this.colorNode = shadowColorNode;
  16305. }
  16306. /**
  16307. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  16308. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  16309. * invocate the respecitve interface methods.
  16310. *
  16311. * @param {NodeBuilder} builder - The current node builder.
  16312. */
  16313. setup( builder ) {
  16314. this.colorNode = this.baseColorNode || this.colorNode;
  16315. if ( this.light.castShadow ) {
  16316. if ( builder.object.receiveShadow ) {
  16317. this.setupShadow( builder );
  16318. }
  16319. } else if ( this.shadowNode !== null ) {
  16320. this.shadowNode.dispose();
  16321. this.shadowNode = null;
  16322. this.shadowColorNode = null;
  16323. }
  16324. }
  16325. /**
  16326. * The update method is used to update light uniforms per frame.
  16327. * Potentially overwritten in concrete light nodes to update light
  16328. * specific uniforms.
  16329. *
  16330. * @param {NodeFrame} frame - A reference to the current node frame.
  16331. */
  16332. update( /*frame*/ ) {
  16333. const { light } = this;
  16334. this.color.copy( light.color ).multiplyScalar( light.intensity );
  16335. }
  16336. }
  16337. /** @module LightUtils **/
  16338. /**
  16339. * Represents a `discard` shader operation in TSL.
  16340. *
  16341. * @method
  16342. * @param {Object} inputs - The input parameter object.
  16343. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  16344. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  16345. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  16346. * @return {Node<float>} The distance falloff.
  16347. */
  16348. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  16349. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  16350. // based upon Frostbite 3 Moving to Physically-based Rendering
  16351. // page 32, equation 26: E[window1]
  16352. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16353. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  16354. return cutoffDistance.greaterThan( 0 ).select(
  16355. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  16356. distanceFalloff
  16357. );
  16358. } ); // validated
  16359. const _clearColor$2 = /*@__PURE__*/ new Color();
  16360. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  16361. // vector suitable for 2D texture mapping. This code uses the following layout for the
  16362. // 2D texture:
  16363. //
  16364. // xzXZ
  16365. // y Y
  16366. //
  16367. // Y - Positive y direction
  16368. // y - Negative y direction
  16369. // X - Positive x direction
  16370. // x - Negative x direction
  16371. // Z - Positive z direction
  16372. // z - Negative z direction
  16373. //
  16374. // Source and test bed:
  16375. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  16376. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  16377. const v = pos.toVar();
  16378. // Number of texels to avoid at the edge of each square
  16379. const absV = abs( v );
  16380. // Intersect unit cube
  16381. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  16382. absV.mulAssign( scaleToCube );
  16383. // Apply scale to avoid seams
  16384. // two texels less per square (one texel will do for NEAREST)
  16385. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  16386. // Unwrap
  16387. // space: -1 ... 1 range for each square
  16388. //
  16389. // #X## dim := ( 4 , 2 )
  16390. // # # center := ( 1 , 1 )
  16391. const planar = vec2( v.xy ).toVar();
  16392. const almostATexel = texelSizeY.mul( 1.5 );
  16393. const almostOne = almostATexel.oneMinus();
  16394. If( absV.z.greaterThanEqual( almostOne ), () => {
  16395. If( v.z.greaterThan( 0.0 ), () => {
  16396. planar.x.assign( sub( 4.0, v.x ) );
  16397. } );
  16398. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  16399. const signX = sign( v.x );
  16400. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  16401. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  16402. const signY = sign( v.y );
  16403. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  16404. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  16405. } );
  16406. // Transform to UV space
  16407. // scale := 0.5 / dim
  16408. // translate := ( center + 0.5 ) / dim
  16409. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  16410. } ).setLayout( {
  16411. name: 'cubeToUV',
  16412. type: 'vec2',
  16413. inputs: [
  16414. { name: 'pos', type: 'vec3' },
  16415. { name: 'texelSizeY', type: 'float' }
  16416. ]
  16417. } );
  16418. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  16419. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  16420. } );
  16421. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  16422. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  16423. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  16424. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  16425. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  16426. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  16427. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  16428. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  16429. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  16430. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  16431. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  16432. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  16433. .mul( 1.0 / 9.0 );
  16434. } );
  16435. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  16436. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  16437. // the vector from the light to the world-space position of the fragment.
  16438. const lightToPosition = shadowCoord.xyz.toVar();
  16439. const lightToPositionLength = lightToPosition.length();
  16440. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  16441. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  16442. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  16443. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  16444. const result = float( 1.0 ).toVar();
  16445. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  16446. // dp = normalized distance from light to fragment position
  16447. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  16448. dp.addAssign( bias );
  16449. // bd3D = base direction 3D
  16450. const bd3D = lightToPosition.normalize();
  16451. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  16452. // percentage-closer filtering
  16453. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  16454. } );
  16455. return result;
  16456. } );
  16457. const _viewport = /*@__PURE__*/ new Vector4();
  16458. const _viewportSize = /*@__PURE__*/ new Vector2();
  16459. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  16460. //
  16461. class PointShadowNode extends ShadowNode {
  16462. static get type() {
  16463. return 'PointShadowNode';
  16464. }
  16465. constructor( light, shadow = null ) {
  16466. super( light, shadow );
  16467. }
  16468. getShadowFilterFn( type ) {
  16469. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  16470. }
  16471. setupShadowCoord( builder, shadowPosition ) {
  16472. return shadowPosition;
  16473. }
  16474. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  16475. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  16476. }
  16477. renderShadow( frame ) {
  16478. const { shadow, shadowMap, light } = this;
  16479. const { renderer, scene } = frame;
  16480. const shadowFrameExtents = shadow.getFrameExtents();
  16481. _shadowMapSize.copy( shadow.mapSize );
  16482. _shadowMapSize.multiply( shadowFrameExtents );
  16483. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  16484. _viewportSize.copy( shadow.mapSize );
  16485. //
  16486. const previousAutoClear = renderer.autoClear;
  16487. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  16488. const previousClearAlpha = renderer.getClearAlpha();
  16489. renderer.autoClear = false;
  16490. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  16491. renderer.clear();
  16492. const viewportCount = shadow.getViewportCount();
  16493. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  16494. const viewport = shadow.getViewport( vp );
  16495. const x = _viewportSize.x * viewport.x;
  16496. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  16497. _viewport.set(
  16498. x,
  16499. y,
  16500. _viewportSize.x * viewport.z,
  16501. _viewportSize.y * viewport.w
  16502. );
  16503. shadowMap.viewport.copy( _viewport );
  16504. shadow.updateMatrices( light, vp );
  16505. renderer.render( scene, shadow.camera );
  16506. }
  16507. //
  16508. renderer.autoClear = previousAutoClear;
  16509. renderer.setClearColor( previousClearColor, previousClearAlpha );
  16510. }
  16511. }
  16512. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  16513. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  16514. const lightingModel = builder.context.lightingModel;
  16515. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  16516. const lightDirection = lVector.normalize();
  16517. const lightDistance = lVector.length();
  16518. const lightAttenuation = getDistanceAttenuation( {
  16519. lightDistance,
  16520. cutoffDistance,
  16521. decayExponent
  16522. } );
  16523. const lightColor = color.mul( lightAttenuation );
  16524. const reflectedLight = builder.context.reflectedLight;
  16525. lightingModel.direct( {
  16526. lightDirection,
  16527. lightColor,
  16528. reflectedLight
  16529. }, builder.stack, builder );
  16530. } );
  16531. /**
  16532. * Module for representing point lights as nodes.
  16533. *
  16534. * @augments AnalyticLightNode
  16535. */
  16536. class PointLightNode extends AnalyticLightNode {
  16537. static get type() {
  16538. return 'PointLightNode';
  16539. }
  16540. /**
  16541. * Constructs a new point light node.
  16542. *
  16543. * @param {PointLight?} [light=null] - The point light source.
  16544. */
  16545. constructor( light = null ) {
  16546. super( light );
  16547. /**
  16548. * Uniform node representing the cutoff distance.
  16549. *
  16550. * @type {UniformNode<float>}
  16551. */
  16552. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  16553. /**
  16554. * Uniform node representing the decay exponent.
  16555. *
  16556. * @type {UniformNode<float>}
  16557. */
  16558. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  16559. }
  16560. /**
  16561. * Overwritten to updated point light specific uniforms.
  16562. *
  16563. * @param {NodeFrame} frame - A reference to the current node frame.
  16564. */
  16565. update( frame ) {
  16566. const { light } = this;
  16567. super.update( frame );
  16568. this.cutoffDistanceNode.value = light.distance;
  16569. this.decayExponentNode.value = light.decay;
  16570. }
  16571. /**
  16572. * Overwritten to setup point light specific shadow.
  16573. *
  16574. * @return {PointShadowNode}
  16575. */
  16576. setupShadowNode() {
  16577. return pointShadow( this.light );
  16578. }
  16579. setup( builder ) {
  16580. super.setup( builder );
  16581. directPointLight( {
  16582. color: this.colorNode,
  16583. lightViewPosition: lightViewPosition( this.light ),
  16584. cutoffDistance: this.cutoffDistanceNode,
  16585. decayExponent: this.decayExponentNode
  16586. } ).append();
  16587. }
  16588. }
  16589. /** @module Procedural **/
  16590. /**
  16591. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  16592. *
  16593. * @method
  16594. * @param {Node<vec2>} uv - The uv coordinates.
  16595. * @return {Node<float>} The result data.
  16596. */
  16597. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  16598. const uv = coord.mul( 2.0 );
  16599. const cx = uv.x.floor();
  16600. const cy = uv.y.floor();
  16601. const result = cx.add( cy ).mod( 2.0 );
  16602. return result.sign();
  16603. } );
  16604. // Three.js Transpiler
  16605. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  16606. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  16607. const f = float( f_immutable ).toVar();
  16608. const t = float( t_immutable ).toVar();
  16609. const b = bool( b_immutable ).toVar();
  16610. return select( b, t, f );
  16611. } ).setLayout( {
  16612. name: 'mx_select',
  16613. type: 'float',
  16614. inputs: [
  16615. { name: 'b', type: 'bool' },
  16616. { name: 't', type: 'float' },
  16617. { name: 'f', type: 'float' }
  16618. ]
  16619. } );
  16620. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  16621. const b = bool( b_immutable ).toVar();
  16622. const val = float( val_immutable ).toVar();
  16623. return select( b, val.negate(), val );
  16624. } ).setLayout( {
  16625. name: 'mx_negate_if',
  16626. type: 'float',
  16627. inputs: [
  16628. { name: 'val', type: 'float' },
  16629. { name: 'b', type: 'bool' }
  16630. ]
  16631. } );
  16632. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  16633. const x = float( x_immutable ).toVar();
  16634. return int( floor( x ) );
  16635. } ).setLayout( {
  16636. name: 'mx_floor',
  16637. type: 'int',
  16638. inputs: [
  16639. { name: 'x', type: 'float' }
  16640. ]
  16641. } );
  16642. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  16643. const x = float( x_immutable ).toVar();
  16644. i.assign( mx_floor( x ) );
  16645. return x.sub( float( i ) );
  16646. } );
  16647. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  16648. const t = float( t_immutable ).toVar();
  16649. const s = float( s_immutable ).toVar();
  16650. const v3 = float( v3_immutable ).toVar();
  16651. const v2 = float( v2_immutable ).toVar();
  16652. const v1 = float( v1_immutable ).toVar();
  16653. const v0 = float( v0_immutable ).toVar();
  16654. const s1 = float( sub( 1.0, s ) ).toVar();
  16655. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  16656. } ).setLayout( {
  16657. name: 'mx_bilerp_0',
  16658. type: 'float',
  16659. inputs: [
  16660. { name: 'v0', type: 'float' },
  16661. { name: 'v1', type: 'float' },
  16662. { name: 'v2', type: 'float' },
  16663. { name: 'v3', type: 'float' },
  16664. { name: 's', type: 'float' },
  16665. { name: 't', type: 'float' }
  16666. ]
  16667. } );
  16668. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  16669. const t = float( t_immutable ).toVar();
  16670. const s = float( s_immutable ).toVar();
  16671. const v3 = vec3( v3_immutable ).toVar();
  16672. const v2 = vec3( v2_immutable ).toVar();
  16673. const v1 = vec3( v1_immutable ).toVar();
  16674. const v0 = vec3( v0_immutable ).toVar();
  16675. const s1 = float( sub( 1.0, s ) ).toVar();
  16676. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  16677. } ).setLayout( {
  16678. name: 'mx_bilerp_1',
  16679. type: 'vec3',
  16680. inputs: [
  16681. { name: 'v0', type: 'vec3' },
  16682. { name: 'v1', type: 'vec3' },
  16683. { name: 'v2', type: 'vec3' },
  16684. { name: 'v3', type: 'vec3' },
  16685. { name: 's', type: 'float' },
  16686. { name: 't', type: 'float' }
  16687. ]
  16688. } );
  16689. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  16690. 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 ] ) => {
  16691. const r = float( r_immutable ).toVar();
  16692. const t = float( t_immutable ).toVar();
  16693. const s = float( s_immutable ).toVar();
  16694. const v7 = float( v7_immutable ).toVar();
  16695. const v6 = float( v6_immutable ).toVar();
  16696. const v5 = float( v5_immutable ).toVar();
  16697. const v4 = float( v4_immutable ).toVar();
  16698. const v3 = float( v3_immutable ).toVar();
  16699. const v2 = float( v2_immutable ).toVar();
  16700. const v1 = float( v1_immutable ).toVar();
  16701. const v0 = float( v0_immutable ).toVar();
  16702. const s1 = float( sub( 1.0, s ) ).toVar();
  16703. const t1 = float( sub( 1.0, t ) ).toVar();
  16704. const r1 = float( sub( 1.0, r ) ).toVar();
  16705. 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 ) ) ) ) ) );
  16706. } ).setLayout( {
  16707. name: 'mx_trilerp_0',
  16708. type: 'float',
  16709. inputs: [
  16710. { name: 'v0', type: 'float' },
  16711. { name: 'v1', type: 'float' },
  16712. { name: 'v2', type: 'float' },
  16713. { name: 'v3', type: 'float' },
  16714. { name: 'v4', type: 'float' },
  16715. { name: 'v5', type: 'float' },
  16716. { name: 'v6', type: 'float' },
  16717. { name: 'v7', type: 'float' },
  16718. { name: 's', type: 'float' },
  16719. { name: 't', type: 'float' },
  16720. { name: 'r', type: 'float' }
  16721. ]
  16722. } );
  16723. 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 ] ) => {
  16724. const r = float( r_immutable ).toVar();
  16725. const t = float( t_immutable ).toVar();
  16726. const s = float( s_immutable ).toVar();
  16727. const v7 = vec3( v7_immutable ).toVar();
  16728. const v6 = vec3( v6_immutable ).toVar();
  16729. const v5 = vec3( v5_immutable ).toVar();
  16730. const v4 = vec3( v4_immutable ).toVar();
  16731. const v3 = vec3( v3_immutable ).toVar();
  16732. const v2 = vec3( v2_immutable ).toVar();
  16733. const v1 = vec3( v1_immutable ).toVar();
  16734. const v0 = vec3( v0_immutable ).toVar();
  16735. const s1 = float( sub( 1.0, s ) ).toVar();
  16736. const t1 = float( sub( 1.0, t ) ).toVar();
  16737. const r1 = float( sub( 1.0, r ) ).toVar();
  16738. 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 ) ) ) ) ) );
  16739. } ).setLayout( {
  16740. name: 'mx_trilerp_1',
  16741. type: 'vec3',
  16742. inputs: [
  16743. { name: 'v0', type: 'vec3' },
  16744. { name: 'v1', type: 'vec3' },
  16745. { name: 'v2', type: 'vec3' },
  16746. { name: 'v3', type: 'vec3' },
  16747. { name: 'v4', type: 'vec3' },
  16748. { name: 'v5', type: 'vec3' },
  16749. { name: 'v6', type: 'vec3' },
  16750. { name: 'v7', type: 'vec3' },
  16751. { name: 's', type: 'float' },
  16752. { name: 't', type: 'float' },
  16753. { name: 'r', type: 'float' }
  16754. ]
  16755. } );
  16756. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  16757. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16758. const y = float( y_immutable ).toVar();
  16759. const x = float( x_immutable ).toVar();
  16760. const hash = uint( hash_immutable ).toVar();
  16761. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  16762. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  16763. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  16764. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16765. } ).setLayout( {
  16766. name: 'mx_gradient_float_0',
  16767. type: 'float',
  16768. inputs: [
  16769. { name: 'hash', type: 'uint' },
  16770. { name: 'x', type: 'float' },
  16771. { name: 'y', type: 'float' }
  16772. ]
  16773. } );
  16774. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16775. const z = float( z_immutable ).toVar();
  16776. const y = float( y_immutable ).toVar();
  16777. const x = float( x_immutable ).toVar();
  16778. const hash = uint( hash_immutable ).toVar();
  16779. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  16780. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  16781. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  16782. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16783. } ).setLayout( {
  16784. name: 'mx_gradient_float_1',
  16785. type: 'float',
  16786. inputs: [
  16787. { name: 'hash', type: 'uint' },
  16788. { name: 'x', type: 'float' },
  16789. { name: 'y', type: 'float' },
  16790. { name: 'z', type: 'float' }
  16791. ]
  16792. } );
  16793. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  16794. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16795. const y = float( y_immutable ).toVar();
  16796. const x = float( x_immutable ).toVar();
  16797. const hash = uvec3( hash_immutable ).toVar();
  16798. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  16799. } ).setLayout( {
  16800. name: 'mx_gradient_vec3_0',
  16801. type: 'vec3',
  16802. inputs: [
  16803. { name: 'hash', type: 'uvec3' },
  16804. { name: 'x', type: 'float' },
  16805. { name: 'y', type: 'float' }
  16806. ]
  16807. } );
  16808. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16809. const z = float( z_immutable ).toVar();
  16810. const y = float( y_immutable ).toVar();
  16811. const x = float( x_immutable ).toVar();
  16812. const hash = uvec3( hash_immutable ).toVar();
  16813. 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 ) );
  16814. } ).setLayout( {
  16815. name: 'mx_gradient_vec3_1',
  16816. type: 'vec3',
  16817. inputs: [
  16818. { name: 'hash', type: 'uvec3' },
  16819. { name: 'x', type: 'float' },
  16820. { name: 'y', type: 'float' },
  16821. { name: 'z', type: 'float' }
  16822. ]
  16823. } );
  16824. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  16825. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16826. const v = float( v_immutable ).toVar();
  16827. return mul( 0.6616, v );
  16828. } ).setLayout( {
  16829. name: 'mx_gradient_scale2d_0',
  16830. type: 'float',
  16831. inputs: [
  16832. { name: 'v', type: 'float' }
  16833. ]
  16834. } );
  16835. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16836. const v = float( v_immutable ).toVar();
  16837. return mul( 0.9820, v );
  16838. } ).setLayout( {
  16839. name: 'mx_gradient_scale3d_0',
  16840. type: 'float',
  16841. inputs: [
  16842. { name: 'v', type: 'float' }
  16843. ]
  16844. } );
  16845. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16846. const v = vec3( v_immutable ).toVar();
  16847. return mul( 0.6616, v );
  16848. } ).setLayout( {
  16849. name: 'mx_gradient_scale2d_1',
  16850. type: 'vec3',
  16851. inputs: [
  16852. { name: 'v', type: 'vec3' }
  16853. ]
  16854. } );
  16855. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  16856. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16857. const v = vec3( v_immutable ).toVar();
  16858. return mul( 0.9820, v );
  16859. } ).setLayout( {
  16860. name: 'mx_gradient_scale3d_1',
  16861. type: 'vec3',
  16862. inputs: [
  16863. { name: 'v', type: 'vec3' }
  16864. ]
  16865. } );
  16866. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  16867. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  16868. const k = int( k_immutable ).toVar();
  16869. const x = uint( x_immutable ).toVar();
  16870. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  16871. } ).setLayout( {
  16872. name: 'mx_rotl32',
  16873. type: 'uint',
  16874. inputs: [
  16875. { name: 'x', type: 'uint' },
  16876. { name: 'k', type: 'int' }
  16877. ]
  16878. } );
  16879. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  16880. a.subAssign( c );
  16881. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  16882. c.addAssign( b );
  16883. b.subAssign( a );
  16884. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  16885. a.addAssign( c );
  16886. c.subAssign( b );
  16887. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  16888. b.addAssign( a );
  16889. a.subAssign( c );
  16890. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  16891. c.addAssign( b );
  16892. b.subAssign( a );
  16893. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  16894. a.addAssign( c );
  16895. c.subAssign( b );
  16896. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  16897. b.addAssign( a );
  16898. } );
  16899. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  16900. const c = uint( c_immutable ).toVar();
  16901. const b = uint( b_immutable ).toVar();
  16902. const a = uint( a_immutable ).toVar();
  16903. c.bitXorAssign( b );
  16904. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  16905. a.bitXorAssign( c );
  16906. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  16907. b.bitXorAssign( a );
  16908. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  16909. c.bitXorAssign( b );
  16910. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  16911. a.bitXorAssign( c );
  16912. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  16913. b.bitXorAssign( a );
  16914. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  16915. c.bitXorAssign( b );
  16916. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  16917. return c;
  16918. } ).setLayout( {
  16919. name: 'mx_bjfinal',
  16920. type: 'uint',
  16921. inputs: [
  16922. { name: 'a', type: 'uint' },
  16923. { name: 'b', type: 'uint' },
  16924. { name: 'c', type: 'uint' }
  16925. ]
  16926. } );
  16927. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  16928. const bits = uint( bits_immutable ).toVar();
  16929. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  16930. } ).setLayout( {
  16931. name: 'mx_bits_to_01',
  16932. type: 'float',
  16933. inputs: [
  16934. { name: 'bits', type: 'uint' }
  16935. ]
  16936. } );
  16937. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  16938. const t = float( t_immutable ).toVar();
  16939. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  16940. } ).setLayout( {
  16941. name: 'mx_fade',
  16942. type: 'float',
  16943. inputs: [
  16944. { name: 't', type: 'float' }
  16945. ]
  16946. } );
  16947. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  16948. const x = int( x_immutable ).toVar();
  16949. const len = uint( uint( 1 ) ).toVar();
  16950. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  16951. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  16952. } ).setLayout( {
  16953. name: 'mx_hash_int_0',
  16954. type: 'uint',
  16955. inputs: [
  16956. { name: 'x', type: 'int' }
  16957. ]
  16958. } );
  16959. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  16960. const y = int( y_immutable ).toVar();
  16961. const x = int( x_immutable ).toVar();
  16962. const len = uint( uint( 2 ) ).toVar();
  16963. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16964. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16965. a.addAssign( uint( x ) );
  16966. b.addAssign( uint( y ) );
  16967. return mx_bjfinal( a, b, c );
  16968. } ).setLayout( {
  16969. name: 'mx_hash_int_1',
  16970. type: 'uint',
  16971. inputs: [
  16972. { name: 'x', type: 'int' },
  16973. { name: 'y', type: 'int' }
  16974. ]
  16975. } );
  16976. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  16977. const z = int( z_immutable ).toVar();
  16978. const y = int( y_immutable ).toVar();
  16979. const x = int( x_immutable ).toVar();
  16980. const len = uint( uint( 3 ) ).toVar();
  16981. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16982. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16983. a.addAssign( uint( x ) );
  16984. b.addAssign( uint( y ) );
  16985. c.addAssign( uint( z ) );
  16986. return mx_bjfinal( a, b, c );
  16987. } ).setLayout( {
  16988. name: 'mx_hash_int_2',
  16989. type: 'uint',
  16990. inputs: [
  16991. { name: 'x', type: 'int' },
  16992. { name: 'y', type: 'int' },
  16993. { name: 'z', type: 'int' }
  16994. ]
  16995. } );
  16996. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  16997. const xx = int( xx_immutable ).toVar();
  16998. const z = int( z_immutable ).toVar();
  16999. const y = int( y_immutable ).toVar();
  17000. const x = int( x_immutable ).toVar();
  17001. const len = uint( uint( 4 ) ).toVar();
  17002. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  17003. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  17004. a.addAssign( uint( x ) );
  17005. b.addAssign( uint( y ) );
  17006. c.addAssign( uint( z ) );
  17007. mx_bjmix( a, b, c );
  17008. a.addAssign( uint( xx ) );
  17009. return mx_bjfinal( a, b, c );
  17010. } ).setLayout( {
  17011. name: 'mx_hash_int_3',
  17012. type: 'uint',
  17013. inputs: [
  17014. { name: 'x', type: 'int' },
  17015. { name: 'y', type: 'int' },
  17016. { name: 'z', type: 'int' },
  17017. { name: 'xx', type: 'int' }
  17018. ]
  17019. } );
  17020. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  17021. const yy = int( yy_immutable ).toVar();
  17022. const xx = int( xx_immutable ).toVar();
  17023. const z = int( z_immutable ).toVar();
  17024. const y = int( y_immutable ).toVar();
  17025. const x = int( x_immutable ).toVar();
  17026. const len = uint( uint( 5 ) ).toVar();
  17027. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  17028. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  17029. a.addAssign( uint( x ) );
  17030. b.addAssign( uint( y ) );
  17031. c.addAssign( uint( z ) );
  17032. mx_bjmix( a, b, c );
  17033. a.addAssign( uint( xx ) );
  17034. b.addAssign( uint( yy ) );
  17035. return mx_bjfinal( a, b, c );
  17036. } ).setLayout( {
  17037. name: 'mx_hash_int_4',
  17038. type: 'uint',
  17039. inputs: [
  17040. { name: 'x', type: 'int' },
  17041. { name: 'y', type: 'int' },
  17042. { name: 'z', type: 'int' },
  17043. { name: 'xx', type: 'int' },
  17044. { name: 'yy', type: 'int' }
  17045. ]
  17046. } );
  17047. 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 ] );
  17048. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  17049. const y = int( y_immutable ).toVar();
  17050. const x = int( x_immutable ).toVar();
  17051. const h = uint( mx_hash_int( x, y ) ).toVar();
  17052. const result = uvec3().toVar();
  17053. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  17054. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  17055. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  17056. return result;
  17057. } ).setLayout( {
  17058. name: 'mx_hash_vec3_0',
  17059. type: 'uvec3',
  17060. inputs: [
  17061. { name: 'x', type: 'int' },
  17062. { name: 'y', type: 'int' }
  17063. ]
  17064. } );
  17065. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  17066. const z = int( z_immutable ).toVar();
  17067. const y = int( y_immutable ).toVar();
  17068. const x = int( x_immutable ).toVar();
  17069. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  17070. const result = uvec3().toVar();
  17071. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  17072. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  17073. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  17074. return result;
  17075. } ).setLayout( {
  17076. name: 'mx_hash_vec3_1',
  17077. type: 'uvec3',
  17078. inputs: [
  17079. { name: 'x', type: 'int' },
  17080. { name: 'y', type: 'int' },
  17081. { name: 'z', type: 'int' }
  17082. ]
  17083. } );
  17084. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  17085. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17086. const p = vec2( p_immutable ).toVar();
  17087. const X = int().toVar(), Y = int().toVar();
  17088. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  17089. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  17090. const u = float( mx_fade( fx ) ).toVar();
  17091. const v = float( mx_fade( fy ) ).toVar();
  17092. 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();
  17093. return mx_gradient_scale2d( result );
  17094. } ).setLayout( {
  17095. name: 'mx_perlin_noise_float_0',
  17096. type: 'float',
  17097. inputs: [
  17098. { name: 'p', type: 'vec2' }
  17099. ]
  17100. } );
  17101. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17102. const p = vec3( p_immutable ).toVar();
  17103. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  17104. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  17105. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  17106. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  17107. const u = float( mx_fade( fx ) ).toVar();
  17108. const v = float( mx_fade( fy ) ).toVar();
  17109. const w = float( mx_fade( fz ) ).toVar();
  17110. 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();
  17111. return mx_gradient_scale3d( result );
  17112. } ).setLayout( {
  17113. name: 'mx_perlin_noise_float_1',
  17114. type: 'float',
  17115. inputs: [
  17116. { name: 'p', type: 'vec3' }
  17117. ]
  17118. } );
  17119. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  17120. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17121. const p = vec2( p_immutable ).toVar();
  17122. const X = int().toVar(), Y = int().toVar();
  17123. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  17124. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  17125. const u = float( mx_fade( fx ) ).toVar();
  17126. const v = float( mx_fade( fy ) ).toVar();
  17127. 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();
  17128. return mx_gradient_scale2d( result );
  17129. } ).setLayout( {
  17130. name: 'mx_perlin_noise_vec3_0',
  17131. type: 'vec3',
  17132. inputs: [
  17133. { name: 'p', type: 'vec2' }
  17134. ]
  17135. } );
  17136. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17137. const p = vec3( p_immutable ).toVar();
  17138. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  17139. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  17140. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  17141. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  17142. const u = float( mx_fade( fx ) ).toVar();
  17143. const v = float( mx_fade( fy ) ).toVar();
  17144. const w = float( mx_fade( fz ) ).toVar();
  17145. 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();
  17146. return mx_gradient_scale3d( result );
  17147. } ).setLayout( {
  17148. name: 'mx_perlin_noise_vec3_1',
  17149. type: 'vec3',
  17150. inputs: [
  17151. { name: 'p', type: 'vec3' }
  17152. ]
  17153. } );
  17154. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  17155. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17156. const p = float( p_immutable ).toVar();
  17157. const ix = int( mx_floor( p ) ).toVar();
  17158. return mx_bits_to_01( mx_hash_int( ix ) );
  17159. } ).setLayout( {
  17160. name: 'mx_cell_noise_float_0',
  17161. type: 'float',
  17162. inputs: [
  17163. { name: 'p', type: 'float' }
  17164. ]
  17165. } );
  17166. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17167. const p = vec2( p_immutable ).toVar();
  17168. const ix = int( mx_floor( p.x ) ).toVar();
  17169. const iy = int( mx_floor( p.y ) ).toVar();
  17170. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  17171. } ).setLayout( {
  17172. name: 'mx_cell_noise_float_1',
  17173. type: 'float',
  17174. inputs: [
  17175. { name: 'p', type: 'vec2' }
  17176. ]
  17177. } );
  17178. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17179. const p = vec3( p_immutable ).toVar();
  17180. const ix = int( mx_floor( p.x ) ).toVar();
  17181. const iy = int( mx_floor( p.y ) ).toVar();
  17182. const iz = int( mx_floor( p.z ) ).toVar();
  17183. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  17184. } ).setLayout( {
  17185. name: 'mx_cell_noise_float_2',
  17186. type: 'float',
  17187. inputs: [
  17188. { name: 'p', type: 'vec3' }
  17189. ]
  17190. } );
  17191. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17192. const p = vec4( p_immutable ).toVar();
  17193. const ix = int( mx_floor( p.x ) ).toVar();
  17194. const iy = int( mx_floor( p.y ) ).toVar();
  17195. const iz = int( mx_floor( p.z ) ).toVar();
  17196. const iw = int( mx_floor( p.w ) ).toVar();
  17197. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  17198. } ).setLayout( {
  17199. name: 'mx_cell_noise_float_3',
  17200. type: 'float',
  17201. inputs: [
  17202. { name: 'p', type: 'vec4' }
  17203. ]
  17204. } );
  17205. 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 ] );
  17206. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17207. const p = float( p_immutable ).toVar();
  17208. const ix = int( mx_floor( p ) ).toVar();
  17209. 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 ) ) ) );
  17210. } ).setLayout( {
  17211. name: 'mx_cell_noise_vec3_0',
  17212. type: 'vec3',
  17213. inputs: [
  17214. { name: 'p', type: 'float' }
  17215. ]
  17216. } );
  17217. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17218. const p = vec2( p_immutable ).toVar();
  17219. const ix = int( mx_floor( p.x ) ).toVar();
  17220. const iy = int( mx_floor( p.y ) ).toVar();
  17221. 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 ) ) ) );
  17222. } ).setLayout( {
  17223. name: 'mx_cell_noise_vec3_1',
  17224. type: 'vec3',
  17225. inputs: [
  17226. { name: 'p', type: 'vec2' }
  17227. ]
  17228. } );
  17229. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17230. const p = vec3( p_immutable ).toVar();
  17231. const ix = int( mx_floor( p.x ) ).toVar();
  17232. const iy = int( mx_floor( p.y ) ).toVar();
  17233. const iz = int( mx_floor( p.z ) ).toVar();
  17234. 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 ) ) ) );
  17235. } ).setLayout( {
  17236. name: 'mx_cell_noise_vec3_2',
  17237. type: 'vec3',
  17238. inputs: [
  17239. { name: 'p', type: 'vec3' }
  17240. ]
  17241. } );
  17242. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  17243. const p = vec4( p_immutable ).toVar();
  17244. const ix = int( mx_floor( p.x ) ).toVar();
  17245. const iy = int( mx_floor( p.y ) ).toVar();
  17246. const iz = int( mx_floor( p.z ) ).toVar();
  17247. const iw = int( mx_floor( p.w ) ).toVar();
  17248. 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 ) ) ) );
  17249. } ).setLayout( {
  17250. name: 'mx_cell_noise_vec3_3',
  17251. type: 'vec3',
  17252. inputs: [
  17253. { name: 'p', type: 'vec4' }
  17254. ]
  17255. } );
  17256. 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 ] );
  17257. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  17258. const diminish = float( diminish_immutable ).toVar();
  17259. const lacunarity = float( lacunarity_immutable ).toVar();
  17260. const octaves = int( octaves_immutable ).toVar();
  17261. const p = vec3( p_immutable ).toVar();
  17262. const result = float( 0.0 ).toVar();
  17263. const amplitude = float( 1.0 ).toVar();
  17264. Loop( octaves, () => {
  17265. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  17266. amplitude.mulAssign( diminish );
  17267. p.mulAssign( lacunarity );
  17268. } );
  17269. return result;
  17270. } ).setLayout( {
  17271. name: 'mx_fractal_noise_float',
  17272. type: 'float',
  17273. inputs: [
  17274. { name: 'p', type: 'vec3' },
  17275. { name: 'octaves', type: 'int' },
  17276. { name: 'lacunarity', type: 'float' },
  17277. { name: 'diminish', type: 'float' }
  17278. ]
  17279. } );
  17280. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  17281. const diminish = float( diminish_immutable ).toVar();
  17282. const lacunarity = float( lacunarity_immutable ).toVar();
  17283. const octaves = int( octaves_immutable ).toVar();
  17284. const p = vec3( p_immutable ).toVar();
  17285. const result = vec3( 0.0 ).toVar();
  17286. const amplitude = float( 1.0 ).toVar();
  17287. Loop( octaves, () => {
  17288. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  17289. amplitude.mulAssign( diminish );
  17290. p.mulAssign( lacunarity );
  17291. } );
  17292. return result;
  17293. } ).setLayout( {
  17294. name: 'mx_fractal_noise_vec3',
  17295. type: 'vec3',
  17296. inputs: [
  17297. { name: 'p', type: 'vec3' },
  17298. { name: 'octaves', type: 'int' },
  17299. { name: 'lacunarity', type: 'float' },
  17300. { name: 'diminish', type: 'float' }
  17301. ]
  17302. } );
  17303. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  17304. const diminish = float( diminish_immutable ).toVar();
  17305. const lacunarity = float( lacunarity_immutable ).toVar();
  17306. const octaves = int( octaves_immutable ).toVar();
  17307. const p = vec3( p_immutable ).toVar();
  17308. 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 ) );
  17309. } ).setLayout( {
  17310. name: 'mx_fractal_noise_vec2',
  17311. type: 'vec2',
  17312. inputs: [
  17313. { name: 'p', type: 'vec3' },
  17314. { name: 'octaves', type: 'int' },
  17315. { name: 'lacunarity', type: 'float' },
  17316. { name: 'diminish', type: 'float' }
  17317. ]
  17318. } );
  17319. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  17320. const diminish = float( diminish_immutable ).toVar();
  17321. const lacunarity = float( lacunarity_immutable ).toVar();
  17322. const octaves = int( octaves_immutable ).toVar();
  17323. const p = vec3( p_immutable ).toVar();
  17324. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  17325. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  17326. return vec4( c, f );
  17327. } ).setLayout( {
  17328. name: 'mx_fractal_noise_vec4',
  17329. type: 'vec4',
  17330. inputs: [
  17331. { name: 'p', type: 'vec3' },
  17332. { name: 'octaves', type: 'int' },
  17333. { name: 'lacunarity', type: 'float' },
  17334. { name: 'diminish', type: 'float' }
  17335. ]
  17336. } );
  17337. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  17338. const metric = int( metric_immutable ).toVar();
  17339. const jitter = float( jitter_immutable ).toVar();
  17340. const yoff = int( yoff_immutable ).toVar();
  17341. const xoff = int( xoff_immutable ).toVar();
  17342. const y = int( y_immutable ).toVar();
  17343. const x = int( x_immutable ).toVar();
  17344. const p = vec2( p_immutable ).toVar();
  17345. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  17346. const off = vec2( tmp.x, tmp.y ).toVar();
  17347. off.subAssign( 0.5 );
  17348. off.mulAssign( jitter );
  17349. off.addAssign( 0.5 );
  17350. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  17351. const diff = vec2( cellpos.sub( p ) ).toVar();
  17352. If( metric.equal( int( 2 ) ), () => {
  17353. return abs( diff.x ).add( abs( diff.y ) );
  17354. } );
  17355. If( metric.equal( int( 3 ) ), () => {
  17356. return max$1( abs( diff.x ), abs( diff.y ) );
  17357. } );
  17358. return dot( diff, diff );
  17359. } ).setLayout( {
  17360. name: 'mx_worley_distance_0',
  17361. type: 'float',
  17362. inputs: [
  17363. { name: 'p', type: 'vec2' },
  17364. { name: 'x', type: 'int' },
  17365. { name: 'y', type: 'int' },
  17366. { name: 'xoff', type: 'int' },
  17367. { name: 'yoff', type: 'int' },
  17368. { name: 'jitter', type: 'float' },
  17369. { name: 'metric', type: 'int' }
  17370. ]
  17371. } );
  17372. 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 ] ) => {
  17373. const metric = int( metric_immutable ).toVar();
  17374. const jitter = float( jitter_immutable ).toVar();
  17375. const zoff = int( zoff_immutable ).toVar();
  17376. const yoff = int( yoff_immutable ).toVar();
  17377. const xoff = int( xoff_immutable ).toVar();
  17378. const z = int( z_immutable ).toVar();
  17379. const y = int( y_immutable ).toVar();
  17380. const x = int( x_immutable ).toVar();
  17381. const p = vec3( p_immutable ).toVar();
  17382. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  17383. off.subAssign( 0.5 );
  17384. off.mulAssign( jitter );
  17385. off.addAssign( 0.5 );
  17386. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  17387. const diff = vec3( cellpos.sub( p ) ).toVar();
  17388. If( metric.equal( int( 2 ) ), () => {
  17389. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  17390. } );
  17391. If( metric.equal( int( 3 ) ), () => {
  17392. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  17393. } );
  17394. return dot( diff, diff );
  17395. } ).setLayout( {
  17396. name: 'mx_worley_distance_1',
  17397. type: 'float',
  17398. inputs: [
  17399. { name: 'p', type: 'vec3' },
  17400. { name: 'x', type: 'int' },
  17401. { name: 'y', type: 'int' },
  17402. { name: 'z', type: 'int' },
  17403. { name: 'xoff', type: 'int' },
  17404. { name: 'yoff', type: 'int' },
  17405. { name: 'zoff', type: 'int' },
  17406. { name: 'jitter', type: 'float' },
  17407. { name: 'metric', type: 'int' }
  17408. ]
  17409. } );
  17410. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  17411. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17412. const metric = int( metric_immutable ).toVar();
  17413. const jitter = float( jitter_immutable ).toVar();
  17414. const p = vec2( p_immutable ).toVar();
  17415. const X = int().toVar(), Y = int().toVar();
  17416. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  17417. const sqdist = float( 1e6 ).toVar();
  17418. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17419. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17420. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  17421. sqdist.assign( min$1( sqdist, dist ) );
  17422. } );
  17423. } );
  17424. If( metric.equal( int( 0 ) ), () => {
  17425. sqdist.assign( sqrt( sqdist ) );
  17426. } );
  17427. return sqdist;
  17428. } ).setLayout( {
  17429. name: 'mx_worley_noise_float_0',
  17430. type: 'float',
  17431. inputs: [
  17432. { name: 'p', type: 'vec2' },
  17433. { name: 'jitter', type: 'float' },
  17434. { name: 'metric', type: 'int' }
  17435. ]
  17436. } );
  17437. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17438. const metric = int( metric_immutable ).toVar();
  17439. const jitter = float( jitter_immutable ).toVar();
  17440. const p = vec2( p_immutable ).toVar();
  17441. const X = int().toVar(), Y = int().toVar();
  17442. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  17443. const sqdist = vec2( 1e6, 1e6 ).toVar();
  17444. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17445. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17446. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  17447. If( dist.lessThan( sqdist.x ), () => {
  17448. sqdist.y.assign( sqdist.x );
  17449. sqdist.x.assign( dist );
  17450. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  17451. sqdist.y.assign( dist );
  17452. } );
  17453. } );
  17454. } );
  17455. If( metric.equal( int( 0 ) ), () => {
  17456. sqdist.assign( sqrt( sqdist ) );
  17457. } );
  17458. return sqdist;
  17459. } ).setLayout( {
  17460. name: 'mx_worley_noise_vec2_0',
  17461. type: 'vec2',
  17462. inputs: [
  17463. { name: 'p', type: 'vec2' },
  17464. { name: 'jitter', type: 'float' },
  17465. { name: 'metric', type: 'int' }
  17466. ]
  17467. } );
  17468. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17469. const metric = int( metric_immutable ).toVar();
  17470. const jitter = float( jitter_immutable ).toVar();
  17471. const p = vec2( p_immutable ).toVar();
  17472. const X = int().toVar(), Y = int().toVar();
  17473. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  17474. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  17475. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17476. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17477. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  17478. If( dist.lessThan( sqdist.x ), () => {
  17479. sqdist.z.assign( sqdist.y );
  17480. sqdist.y.assign( sqdist.x );
  17481. sqdist.x.assign( dist );
  17482. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  17483. sqdist.z.assign( sqdist.y );
  17484. sqdist.y.assign( dist );
  17485. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  17486. sqdist.z.assign( dist );
  17487. } );
  17488. } );
  17489. } );
  17490. If( metric.equal( int( 0 ) ), () => {
  17491. sqdist.assign( sqrt( sqdist ) );
  17492. } );
  17493. return sqdist;
  17494. } ).setLayout( {
  17495. name: 'mx_worley_noise_vec3_0',
  17496. type: 'vec3',
  17497. inputs: [
  17498. { name: 'p', type: 'vec2' },
  17499. { name: 'jitter', type: 'float' },
  17500. { name: 'metric', type: 'int' }
  17501. ]
  17502. } );
  17503. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17504. const metric = int( metric_immutable ).toVar();
  17505. const jitter = float( jitter_immutable ).toVar();
  17506. const p = vec3( p_immutable ).toVar();
  17507. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  17508. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  17509. const sqdist = float( 1e6 ).toVar();
  17510. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17511. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17512. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  17513. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  17514. sqdist.assign( min$1( sqdist, dist ) );
  17515. } );
  17516. } );
  17517. } );
  17518. If( metric.equal( int( 0 ) ), () => {
  17519. sqdist.assign( sqrt( sqdist ) );
  17520. } );
  17521. return sqdist;
  17522. } ).setLayout( {
  17523. name: 'mx_worley_noise_float_1',
  17524. type: 'float',
  17525. inputs: [
  17526. { name: 'p', type: 'vec3' },
  17527. { name: 'jitter', type: 'float' },
  17528. { name: 'metric', type: 'int' }
  17529. ]
  17530. } );
  17531. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  17532. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17533. const metric = int( metric_immutable ).toVar();
  17534. const jitter = float( jitter_immutable ).toVar();
  17535. const p = vec3( p_immutable ).toVar();
  17536. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  17537. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  17538. const sqdist = vec2( 1e6, 1e6 ).toVar();
  17539. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17540. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17541. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  17542. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  17543. If( dist.lessThan( sqdist.x ), () => {
  17544. sqdist.y.assign( sqdist.x );
  17545. sqdist.x.assign( dist );
  17546. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  17547. sqdist.y.assign( dist );
  17548. } );
  17549. } );
  17550. } );
  17551. } );
  17552. If( metric.equal( int( 0 ) ), () => {
  17553. sqdist.assign( sqrt( sqdist ) );
  17554. } );
  17555. return sqdist;
  17556. } ).setLayout( {
  17557. name: 'mx_worley_noise_vec2_1',
  17558. type: 'vec2',
  17559. inputs: [
  17560. { name: 'p', type: 'vec3' },
  17561. { name: 'jitter', type: 'float' },
  17562. { name: 'metric', type: 'int' }
  17563. ]
  17564. } );
  17565. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  17566. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  17567. const metric = int( metric_immutable ).toVar();
  17568. const jitter = float( jitter_immutable ).toVar();
  17569. const p = vec3( p_immutable ).toVar();
  17570. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  17571. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  17572. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  17573. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  17574. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  17575. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  17576. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  17577. If( dist.lessThan( sqdist.x ), () => {
  17578. sqdist.z.assign( sqdist.y );
  17579. sqdist.y.assign( sqdist.x );
  17580. sqdist.x.assign( dist );
  17581. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  17582. sqdist.z.assign( sqdist.y );
  17583. sqdist.y.assign( dist );
  17584. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  17585. sqdist.z.assign( dist );
  17586. } );
  17587. } );
  17588. } );
  17589. } );
  17590. If( metric.equal( int( 0 ) ), () => {
  17591. sqdist.assign( sqrt( sqdist ) );
  17592. } );
  17593. return sqdist;
  17594. } ).setLayout( {
  17595. name: 'mx_worley_noise_vec3_1',
  17596. type: 'vec3',
  17597. inputs: [
  17598. { name: 'p', type: 'vec3' },
  17599. { name: 'jitter', type: 'float' },
  17600. { name: 'metric', type: 'int' }
  17601. ]
  17602. } );
  17603. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  17604. // Three.js Transpiler
  17605. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  17606. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  17607. const s = hsv.y;
  17608. const v = hsv.z;
  17609. const result = vec3().toVar();
  17610. If( s.lessThan( 0.0001 ), () => {
  17611. result.assign( vec3( v, v, v ) );
  17612. } ).Else( () => {
  17613. let h = hsv.x;
  17614. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  17615. const hi = int( trunc( h ) );
  17616. const f = h.sub( float( hi ) );
  17617. const p = v.mul( s.oneMinus() );
  17618. const q = v.mul( s.mul( f ).oneMinus() );
  17619. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  17620. If( hi.equal( int( 0 ) ), () => {
  17621. result.assign( vec3( v, t, p ) );
  17622. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  17623. result.assign( vec3( q, v, p ) );
  17624. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  17625. result.assign( vec3( p, v, t ) );
  17626. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  17627. result.assign( vec3( p, q, v ) );
  17628. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  17629. result.assign( vec3( t, p, v ) );
  17630. } ).Else( () => {
  17631. result.assign( vec3( v, p, q ) );
  17632. } );
  17633. } );
  17634. return result;
  17635. } ).setLayout( {
  17636. name: 'mx_hsvtorgb',
  17637. type: 'vec3',
  17638. inputs: [
  17639. { name: 'hsv', type: 'vec3' }
  17640. ]
  17641. } );
  17642. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  17643. const c = vec3( c_immutable ).toVar();
  17644. const r = float( c.x ).toVar();
  17645. const g = float( c.y ).toVar();
  17646. const b = float( c.z ).toVar();
  17647. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  17648. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  17649. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  17650. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  17651. v.assign( maxcomp );
  17652. If( maxcomp.greaterThan( 0.0 ), () => {
  17653. s.assign( delta.div( maxcomp ) );
  17654. } ).Else( () => {
  17655. s.assign( 0.0 );
  17656. } );
  17657. If( s.lessThanEqual( 0.0 ), () => {
  17658. h.assign( 0.0 );
  17659. } ).Else( () => {
  17660. If( r.greaterThanEqual( maxcomp ), () => {
  17661. h.assign( g.sub( b ).div( delta ) );
  17662. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  17663. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  17664. } ).Else( () => {
  17665. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  17666. } );
  17667. h.mulAssign( 1.0 / 6.0 );
  17668. If( h.lessThan( 0.0 ), () => {
  17669. h.addAssign( 1.0 );
  17670. } );
  17671. } );
  17672. return vec3( h, s, v );
  17673. } ).setLayout( {
  17674. name: 'mx_rgbtohsv',
  17675. type: 'vec3',
  17676. inputs: [
  17677. { name: 'c', type: 'vec3' }
  17678. ]
  17679. } );
  17680. // Three.js Transpiler
  17681. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  17682. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  17683. const color = vec3( color_immutable ).toVar();
  17684. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  17685. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  17686. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  17687. return mix( linSeg, powSeg, isAbove );
  17688. } ).setLayout( {
  17689. name: 'mx_srgb_texture_to_lin_rec709',
  17690. type: 'vec3',
  17691. inputs: [
  17692. { name: 'color', type: 'vec3' }
  17693. ]
  17694. } );
  17695. const mx_aastep = ( threshold, value ) => {
  17696. threshold = float( threshold );
  17697. value = float( value );
  17698. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  17699. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  17700. };
  17701. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  17702. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  17703. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  17704. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  17705. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  17706. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  17707. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  17708. const mx_safepower = ( in1, in2 = 1 ) => {
  17709. in1 = float( in1 );
  17710. return in1.abs().pow( in2 ).mul( in1.sign() );
  17711. };
  17712. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  17713. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17714. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17715. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17716. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  17717. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  17718. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  17719. return noise_vec4.mul( amplitude ).add( pivot );
  17720. };
  17721. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17722. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17723. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17724. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  17725. 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 );
  17726. 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 );
  17727. 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 );
  17728. 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 );
  17729. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  17730. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  17731. const nDir = normalize( normal ).toVar( 'nDir' );
  17732. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  17733. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  17734. const rbminmax = vec3().toVar( 'rbminmax' );
  17735. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  17736. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  17737. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  17738. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  17739. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  17740. return boxIntersection.sub( cubePos );
  17741. } );
  17742. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  17743. // normal is assumed to have unit length
  17744. const x = normal.x, y = normal.y, z = normal.z;
  17745. // band 0
  17746. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  17747. // band 1
  17748. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  17749. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  17750. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  17751. // band 2
  17752. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  17753. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  17754. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  17755. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  17756. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  17757. return result;
  17758. } );
  17759. // constants
  17760. var TSL = /*#__PURE__*/Object.freeze({
  17761. __proto__: null,
  17762. BRDF_GGX: BRDF_GGX,
  17763. BRDF_Lambert: BRDF_Lambert,
  17764. BasicShadowFilter: BasicShadowFilter,
  17765. Break: Break,
  17766. Continue: Continue,
  17767. DFGApprox: DFGApprox,
  17768. D_GGX: D_GGX,
  17769. Discard: Discard,
  17770. EPSILON: EPSILON,
  17771. F_Schlick: F_Schlick,
  17772. Fn: Fn,
  17773. INFINITY: INFINITY,
  17774. If: If,
  17775. Loop: Loop,
  17776. NodeAccess: NodeAccess,
  17777. NodeShaderStage: NodeShaderStage,
  17778. NodeType: NodeType,
  17779. NodeUpdateType: NodeUpdateType,
  17780. PCFShadowFilter: PCFShadowFilter,
  17781. PCFSoftShadowFilter: PCFSoftShadowFilter,
  17782. PI: PI,
  17783. PI2: PI2,
  17784. Return: Return,
  17785. Schlick_to_F0: Schlick_to_F0,
  17786. ScriptableNodeResources: ScriptableNodeResources,
  17787. ShaderNode: ShaderNode,
  17788. TBNViewMatrix: TBNViewMatrix,
  17789. VSMShadowFilter: VSMShadowFilter,
  17790. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  17791. abs: abs,
  17792. acesFilmicToneMapping: acesFilmicToneMapping,
  17793. acos: acos,
  17794. add: add,
  17795. addMethodChaining: addMethodChaining,
  17796. addNodeElement: addNodeElement,
  17797. agxToneMapping: agxToneMapping,
  17798. all: all,
  17799. alphaT: alphaT,
  17800. and: and,
  17801. anisotropy: anisotropy,
  17802. anisotropyB: anisotropyB,
  17803. anisotropyT: anisotropyT,
  17804. any: any,
  17805. append: append,
  17806. arrayBuffer: arrayBuffer,
  17807. asin: asin,
  17808. assign: assign,
  17809. atan: atan,
  17810. atan2: atan2,
  17811. atomicAdd: atomicAdd,
  17812. atomicAnd: atomicAnd,
  17813. atomicFunc: atomicFunc,
  17814. atomicMax: atomicMax,
  17815. atomicMin: atomicMin,
  17816. atomicOr: atomicOr,
  17817. atomicStore: atomicStore,
  17818. atomicSub: atomicSub,
  17819. atomicXor: atomicXor,
  17820. attenuationColor: attenuationColor,
  17821. attenuationDistance: attenuationDistance,
  17822. attribute: attribute,
  17823. attributeArray: attributeArray,
  17824. backgroundBlurriness: backgroundBlurriness,
  17825. backgroundIntensity: backgroundIntensity,
  17826. backgroundRotation: backgroundRotation,
  17827. batch: batch,
  17828. billboarding: billboarding,
  17829. bitAnd: bitAnd,
  17830. bitNot: bitNot,
  17831. bitOr: bitOr,
  17832. bitXor: bitXor,
  17833. bitangentGeometry: bitangentGeometry,
  17834. bitangentLocal: bitangentLocal,
  17835. bitangentView: bitangentView,
  17836. bitangentWorld: bitangentWorld,
  17837. bitcast: bitcast,
  17838. blendBurn: blendBurn,
  17839. blendColor: blendColor,
  17840. blendDodge: blendDodge,
  17841. blendOverlay: blendOverlay,
  17842. blendScreen: blendScreen,
  17843. blur: blur,
  17844. bool: bool,
  17845. buffer: buffer,
  17846. bufferAttribute: bufferAttribute,
  17847. bumpMap: bumpMap,
  17848. burn: burn,
  17849. bvec2: bvec2,
  17850. bvec3: bvec3,
  17851. bvec4: bvec4,
  17852. bypass: bypass,
  17853. cache: cache,
  17854. call: call,
  17855. cameraFar: cameraFar,
  17856. cameraNear: cameraNear,
  17857. cameraNormalMatrix: cameraNormalMatrix,
  17858. cameraPosition: cameraPosition,
  17859. cameraProjectionMatrix: cameraProjectionMatrix,
  17860. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  17861. cameraViewMatrix: cameraViewMatrix,
  17862. cameraWorldMatrix: cameraWorldMatrix,
  17863. cbrt: cbrt,
  17864. cdl: cdl,
  17865. ceil: ceil,
  17866. checker: checker,
  17867. cineonToneMapping: cineonToneMapping,
  17868. clamp: clamp,
  17869. clearcoat: clearcoat,
  17870. clearcoatRoughness: clearcoatRoughness,
  17871. code: code,
  17872. color: color,
  17873. colorSpaceToWorking: colorSpaceToWorking,
  17874. colorToDirection: colorToDirection,
  17875. compute: compute,
  17876. cond: cond,
  17877. context: context,
  17878. convert: convert,
  17879. convertColorSpace: convertColorSpace,
  17880. convertToTexture: convertToTexture,
  17881. cos: cos,
  17882. cross: cross,
  17883. cubeTexture: cubeTexture,
  17884. dFdx: dFdx,
  17885. dFdy: dFdy,
  17886. dashSize: dashSize,
  17887. defaultBuildStages: defaultBuildStages,
  17888. defaultShaderStages: defaultShaderStages,
  17889. defined: defined,
  17890. degrees: degrees,
  17891. deltaTime: deltaTime,
  17892. densityFog: densityFog,
  17893. depth: depth,
  17894. depthPass: depthPass,
  17895. difference: difference,
  17896. diffuseColor: diffuseColor,
  17897. directPointLight: directPointLight,
  17898. directionToColor: directionToColor,
  17899. dispersion: dispersion,
  17900. distance: distance,
  17901. div: div,
  17902. dodge: dodge,
  17903. dot: dot,
  17904. drawIndex: drawIndex,
  17905. dynamicBufferAttribute: dynamicBufferAttribute,
  17906. element: element,
  17907. emissive: emissive,
  17908. equal: equal,
  17909. equals: equals,
  17910. equirectUV: equirectUV,
  17911. exp: exp,
  17912. exp2: exp2,
  17913. expression: expression,
  17914. faceDirection: faceDirection,
  17915. faceForward: faceForward,
  17916. float: float,
  17917. floor: floor,
  17918. fog: fog,
  17919. fract: fract,
  17920. frameGroup: frameGroup,
  17921. frameId: frameId,
  17922. frontFacing: frontFacing,
  17923. fwidth: fwidth,
  17924. gain: gain,
  17925. gapSize: gapSize,
  17926. getConstNodeType: getConstNodeType,
  17927. getCurrentStack: getCurrentStack,
  17928. getDirection: getDirection,
  17929. getDistanceAttenuation: getDistanceAttenuation,
  17930. getGeometryRoughness: getGeometryRoughness,
  17931. getNormalFromDepth: getNormalFromDepth,
  17932. getParallaxCorrectNormal: getParallaxCorrectNormal,
  17933. getRoughness: getRoughness,
  17934. getScreenPosition: getScreenPosition,
  17935. getShIrradianceAt: getShIrradianceAt,
  17936. getTextureIndex: getTextureIndex,
  17937. getViewPosition: getViewPosition,
  17938. glsl: glsl,
  17939. glslFn: glslFn,
  17940. grayscale: grayscale,
  17941. greaterThan: greaterThan,
  17942. greaterThanEqual: greaterThanEqual,
  17943. hash: hash,
  17944. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  17945. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  17946. hue: hue,
  17947. instance: instance,
  17948. instanceIndex: instanceIndex,
  17949. instancedArray: instancedArray,
  17950. instancedBufferAttribute: instancedBufferAttribute,
  17951. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  17952. instancedMesh: instancedMesh,
  17953. int: int,
  17954. inverseSqrt: inverseSqrt,
  17955. invocationLocalIndex: invocationLocalIndex,
  17956. invocationSubgroupIndex: invocationSubgroupIndex,
  17957. ior: ior,
  17958. iridescence: iridescence,
  17959. iridescenceIOR: iridescenceIOR,
  17960. iridescenceThickness: iridescenceThickness,
  17961. ivec2: ivec2,
  17962. ivec3: ivec3,
  17963. ivec4: ivec4,
  17964. js: js,
  17965. label: label,
  17966. length: length,
  17967. lengthSq: lengthSq,
  17968. lessThan: lessThan,
  17969. lessThanEqual: lessThanEqual,
  17970. lightPosition: lightPosition,
  17971. lightProjectionUV: lightProjectionUV,
  17972. lightShadowMatrix: lightShadowMatrix,
  17973. lightTargetDirection: lightTargetDirection,
  17974. lightTargetPosition: lightTargetPosition,
  17975. lightViewPosition: lightViewPosition,
  17976. lightingContext: lightingContext,
  17977. lights: lights,
  17978. linearDepth: linearDepth,
  17979. linearToneMapping: linearToneMapping,
  17980. localId: localId,
  17981. log: log,
  17982. log2: log2,
  17983. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  17984. loop: loop,
  17985. luminance: luminance,
  17986. mat2: mat2,
  17987. mat3: mat3,
  17988. mat4: mat4,
  17989. matcapUV: matcapUV,
  17990. materialAOMap: materialAOMap,
  17991. materialAlphaTest: materialAlphaTest,
  17992. materialAnisotropy: materialAnisotropy,
  17993. materialAnisotropyVector: materialAnisotropyVector,
  17994. materialAttenuationColor: materialAttenuationColor,
  17995. materialAttenuationDistance: materialAttenuationDistance,
  17996. materialClearcoat: materialClearcoat,
  17997. materialClearcoatNormal: materialClearcoatNormal,
  17998. materialClearcoatRoughness: materialClearcoatRoughness,
  17999. materialColor: materialColor,
  18000. materialDispersion: materialDispersion,
  18001. materialEmissive: materialEmissive,
  18002. materialIOR: materialIOR,
  18003. materialIridescence: materialIridescence,
  18004. materialIridescenceIOR: materialIridescenceIOR,
  18005. materialIridescenceThickness: materialIridescenceThickness,
  18006. materialLightMap: materialLightMap,
  18007. materialLineDashOffset: materialLineDashOffset,
  18008. materialLineDashSize: materialLineDashSize,
  18009. materialLineGapSize: materialLineGapSize,
  18010. materialLineScale: materialLineScale,
  18011. materialLineWidth: materialLineWidth,
  18012. materialMetalness: materialMetalness,
  18013. materialNormal: materialNormal,
  18014. materialOpacity: materialOpacity,
  18015. materialPointWidth: materialPointWidth,
  18016. materialReference: materialReference,
  18017. materialReflectivity: materialReflectivity,
  18018. materialRefractionRatio: materialRefractionRatio,
  18019. materialRotation: materialRotation,
  18020. materialRoughness: materialRoughness,
  18021. materialSheen: materialSheen,
  18022. materialSheenRoughness: materialSheenRoughness,
  18023. materialShininess: materialShininess,
  18024. materialSpecular: materialSpecular,
  18025. materialSpecularColor: materialSpecularColor,
  18026. materialSpecularIntensity: materialSpecularIntensity,
  18027. materialSpecularStrength: materialSpecularStrength,
  18028. materialThickness: materialThickness,
  18029. materialTransmission: materialTransmission,
  18030. max: max$1,
  18031. maxMipLevel: maxMipLevel,
  18032. metalness: metalness,
  18033. min: min$1,
  18034. mix: mix,
  18035. mixElement: mixElement,
  18036. mod: mod,
  18037. modInt: modInt,
  18038. modelDirection: modelDirection,
  18039. modelNormalMatrix: modelNormalMatrix,
  18040. modelPosition: modelPosition,
  18041. modelScale: modelScale,
  18042. modelViewMatrix: modelViewMatrix,
  18043. modelViewPosition: modelViewPosition,
  18044. modelViewProjection: modelViewProjection,
  18045. modelWorldMatrix: modelWorldMatrix,
  18046. modelWorldMatrixInverse: modelWorldMatrixInverse,
  18047. morphReference: morphReference,
  18048. mrt: mrt,
  18049. mul: mul,
  18050. mx_aastep: mx_aastep,
  18051. mx_cell_noise_float: mx_cell_noise_float,
  18052. mx_contrast: mx_contrast,
  18053. mx_fractal_noise_float: mx_fractal_noise_float,
  18054. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  18055. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  18056. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  18057. mx_hsvtorgb: mx_hsvtorgb,
  18058. mx_noise_float: mx_noise_float,
  18059. mx_noise_vec3: mx_noise_vec3,
  18060. mx_noise_vec4: mx_noise_vec4,
  18061. mx_ramplr: mx_ramplr,
  18062. mx_ramptb: mx_ramptb,
  18063. mx_rgbtohsv: mx_rgbtohsv,
  18064. mx_safepower: mx_safepower,
  18065. mx_splitlr: mx_splitlr,
  18066. mx_splittb: mx_splittb,
  18067. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  18068. mx_transform_uv: mx_transform_uv,
  18069. mx_worley_noise_float: mx_worley_noise_float,
  18070. mx_worley_noise_vec2: mx_worley_noise_vec2,
  18071. mx_worley_noise_vec3: mx_worley_noise_vec3,
  18072. negate: negate,
  18073. neutralToneMapping: neutralToneMapping,
  18074. nodeArray: nodeArray,
  18075. nodeImmutable: nodeImmutable,
  18076. nodeObject: nodeObject,
  18077. nodeObjects: nodeObjects,
  18078. nodeProxy: nodeProxy,
  18079. normalFlat: normalFlat,
  18080. normalGeometry: normalGeometry,
  18081. normalLocal: normalLocal,
  18082. normalMap: normalMap,
  18083. normalView: normalView,
  18084. normalWorld: normalWorld,
  18085. normalize: normalize,
  18086. not: not,
  18087. notEqual: notEqual,
  18088. numWorkgroups: numWorkgroups,
  18089. objectDirection: objectDirection,
  18090. objectGroup: objectGroup,
  18091. objectPosition: objectPosition,
  18092. objectScale: objectScale,
  18093. objectViewPosition: objectViewPosition,
  18094. objectWorldMatrix: objectWorldMatrix,
  18095. oneMinus: oneMinus,
  18096. or: or,
  18097. orthographicDepthToViewZ: orthographicDepthToViewZ,
  18098. oscSawtooth: oscSawtooth,
  18099. oscSine: oscSine,
  18100. oscSquare: oscSquare,
  18101. oscTriangle: oscTriangle,
  18102. output: output,
  18103. outputStruct: outputStruct,
  18104. overlay: overlay,
  18105. overloadingFn: overloadingFn,
  18106. parabola: parabola,
  18107. parallaxDirection: parallaxDirection,
  18108. parallaxUV: parallaxUV,
  18109. parameter: parameter,
  18110. pass: pass,
  18111. passTexture: passTexture,
  18112. pcurve: pcurve,
  18113. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  18114. pmremTexture: pmremTexture,
  18115. pointUV: pointUV,
  18116. pointWidth: pointWidth,
  18117. positionGeometry: positionGeometry,
  18118. positionLocal: positionLocal,
  18119. positionPrevious: positionPrevious,
  18120. positionView: positionView,
  18121. positionViewDirection: positionViewDirection,
  18122. positionWorld: positionWorld,
  18123. positionWorldDirection: positionWorldDirection,
  18124. posterize: posterize,
  18125. pow: pow,
  18126. pow2: pow2,
  18127. pow3: pow3,
  18128. pow4: pow4,
  18129. property: property,
  18130. radians: radians,
  18131. rand: rand,
  18132. range: range,
  18133. rangeFog: rangeFog,
  18134. reciprocal: reciprocal,
  18135. reference: reference,
  18136. referenceBuffer: referenceBuffer,
  18137. reflect: reflect,
  18138. reflectVector: reflectVector,
  18139. reflectView: reflectView,
  18140. reflector: reflector,
  18141. refract: refract,
  18142. refractVector: refractVector,
  18143. refractView: refractView,
  18144. reinhardToneMapping: reinhardToneMapping,
  18145. remainder: remainder,
  18146. remap: remap,
  18147. remapClamp: remapClamp,
  18148. renderGroup: renderGroup,
  18149. renderOutput: renderOutput,
  18150. rendererReference: rendererReference,
  18151. rotate: rotate,
  18152. rotateUV: rotateUV,
  18153. roughness: roughness,
  18154. round: round,
  18155. rtt: rtt,
  18156. sRGBTransferEOTF: sRGBTransferEOTF,
  18157. sRGBTransferOETF: sRGBTransferOETF,
  18158. sampler: sampler,
  18159. saturate: saturate,
  18160. saturation: saturation,
  18161. screen: screen,
  18162. screenCoordinate: screenCoordinate,
  18163. screenSize: screenSize,
  18164. screenUV: screenUV,
  18165. scriptable: scriptable,
  18166. scriptableValue: scriptableValue,
  18167. select: select,
  18168. setCurrentStack: setCurrentStack,
  18169. shaderStages: shaderStages,
  18170. shadow: shadow,
  18171. sharedUniformGroup: sharedUniformGroup,
  18172. sheen: sheen,
  18173. sheenRoughness: sheenRoughness,
  18174. shiftLeft: shiftLeft,
  18175. shiftRight: shiftRight,
  18176. shininess: shininess,
  18177. sign: sign,
  18178. sin: sin,
  18179. sinc: sinc,
  18180. skinning: skinning,
  18181. skinningReference: skinningReference,
  18182. smoothstep: smoothstep,
  18183. smoothstepElement: smoothstepElement,
  18184. specularColor: specularColor,
  18185. specularF90: specularF90,
  18186. spherizeUV: spherizeUV,
  18187. split: split,
  18188. spritesheetUV: spritesheetUV,
  18189. sqrt: sqrt,
  18190. stack: stack,
  18191. step: step,
  18192. storage: storage,
  18193. storageBarrier: storageBarrier,
  18194. storageObject: storageObject,
  18195. storageTexture: storageTexture,
  18196. string: string,
  18197. sub: sub,
  18198. subgroupIndex: subgroupIndex,
  18199. subgroupSize: subgroupSize,
  18200. tan: tan,
  18201. tangentGeometry: tangentGeometry,
  18202. tangentLocal: tangentLocal,
  18203. tangentView: tangentView,
  18204. tangentWorld: tangentWorld,
  18205. temp: temp,
  18206. texture: texture,
  18207. texture3D: texture3D,
  18208. textureBarrier: textureBarrier,
  18209. textureBicubic: textureBicubic,
  18210. textureCubeUV: textureCubeUV,
  18211. textureLoad: textureLoad,
  18212. textureSize: textureSize,
  18213. textureStore: textureStore,
  18214. thickness: thickness,
  18215. time: time,
  18216. timerDelta: timerDelta,
  18217. timerGlobal: timerGlobal,
  18218. timerLocal: timerLocal,
  18219. toOutputColorSpace: toOutputColorSpace,
  18220. toWorkingColorSpace: toWorkingColorSpace,
  18221. toneMapping: toneMapping,
  18222. toneMappingExposure: toneMappingExposure,
  18223. toonOutlinePass: toonOutlinePass,
  18224. transformDirection: transformDirection,
  18225. transformNormal: transformNormal,
  18226. transformNormalToView: transformNormalToView,
  18227. transformedBentNormalView: transformedBentNormalView,
  18228. transformedBitangentView: transformedBitangentView,
  18229. transformedBitangentWorld: transformedBitangentWorld,
  18230. transformedClearcoatNormalView: transformedClearcoatNormalView,
  18231. transformedNormalView: transformedNormalView,
  18232. transformedNormalWorld: transformedNormalWorld,
  18233. transformedTangentView: transformedTangentView,
  18234. transformedTangentWorld: transformedTangentWorld,
  18235. transmission: transmission,
  18236. transpose: transpose,
  18237. triNoise3D: triNoise3D,
  18238. triplanarTexture: triplanarTexture,
  18239. triplanarTextures: triplanarTextures,
  18240. trunc: trunc,
  18241. tslFn: tslFn,
  18242. uint: uint,
  18243. uniform: uniform,
  18244. uniformArray: uniformArray,
  18245. uniformGroup: uniformGroup,
  18246. uniforms: uniforms,
  18247. userData: userData,
  18248. uv: uv,
  18249. uvec2: uvec2,
  18250. uvec3: uvec3,
  18251. uvec4: uvec4,
  18252. varying: varying,
  18253. varyingProperty: varyingProperty,
  18254. vec2: vec2,
  18255. vec3: vec3,
  18256. vec4: vec4,
  18257. vectorComponents: vectorComponents,
  18258. velocity: velocity,
  18259. vertexColor: vertexColor,
  18260. vertexIndex: vertexIndex,
  18261. vibrance: vibrance,
  18262. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  18263. viewZToOrthographicDepth: viewZToOrthographicDepth,
  18264. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  18265. viewport: viewport,
  18266. viewportBottomLeft: viewportBottomLeft,
  18267. viewportCoordinate: viewportCoordinate,
  18268. viewportDepthTexture: viewportDepthTexture,
  18269. viewportLinearDepth: viewportLinearDepth,
  18270. viewportMipTexture: viewportMipTexture,
  18271. viewportResolution: viewportResolution,
  18272. viewportSafeUV: viewportSafeUV,
  18273. viewportSharedTexture: viewportSharedTexture,
  18274. viewportSize: viewportSize,
  18275. viewportTexture: viewportTexture,
  18276. viewportTopLeft: viewportTopLeft,
  18277. viewportUV: viewportUV,
  18278. wgsl: wgsl,
  18279. wgslFn: wgslFn,
  18280. workgroupArray: workgroupArray,
  18281. workgroupBarrier: workgroupBarrier,
  18282. workgroupId: workgroupId,
  18283. workingToColorSpace: workingToColorSpace,
  18284. xor: xor
  18285. });
  18286. const _clearColor$1 = /*@__PURE__*/ new Color4();
  18287. class Background extends DataMap {
  18288. constructor( renderer, nodes ) {
  18289. super();
  18290. this.renderer = renderer;
  18291. this.nodes = nodes;
  18292. }
  18293. update( scene, renderList, renderContext ) {
  18294. const renderer = this.renderer;
  18295. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  18296. let forceClear = false;
  18297. if ( background === null ) {
  18298. // no background settings, use clear color configuration from the renderer
  18299. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  18300. _clearColor$1.a = renderer._clearColor.a;
  18301. } else if ( background.isColor === true ) {
  18302. // background is an opaque color
  18303. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  18304. _clearColor$1.a = 1;
  18305. forceClear = true;
  18306. } else if ( background.isNode === true ) {
  18307. const sceneData = this.get( scene );
  18308. const backgroundNode = background;
  18309. _clearColor$1.copy( renderer._clearColor );
  18310. let backgroundMesh = sceneData.backgroundMesh;
  18311. if ( backgroundMesh === undefined ) {
  18312. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  18313. // @TODO: Add Texture2D support using node context
  18314. getUV: () => backgroundRotation.mul( normalWorld ),
  18315. getTextureLevel: () => backgroundBlurriness
  18316. } );
  18317. let viewProj = modelViewProjection();
  18318. viewProj = viewProj.setZ( viewProj.w );
  18319. const nodeMaterial = new NodeMaterial();
  18320. nodeMaterial.name = 'Background.material';
  18321. nodeMaterial.side = BackSide;
  18322. nodeMaterial.depthTest = false;
  18323. nodeMaterial.depthWrite = false;
  18324. nodeMaterial.fog = false;
  18325. nodeMaterial.lights = false;
  18326. nodeMaterial.vertexNode = viewProj;
  18327. nodeMaterial.colorNode = backgroundMeshNode;
  18328. sceneData.backgroundMeshNode = backgroundMeshNode;
  18329. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  18330. backgroundMesh.frustumCulled = false;
  18331. backgroundMesh.name = 'Background.mesh';
  18332. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  18333. this.matrixWorld.copyPosition( camera.matrixWorld );
  18334. };
  18335. }
  18336. const backgroundCacheKey = backgroundNode.getCacheKey();
  18337. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  18338. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  18339. sceneData.backgroundMeshNode.needsUpdate = true;
  18340. backgroundMesh.material.needsUpdate = true;
  18341. sceneData.backgroundCacheKey = backgroundCacheKey;
  18342. }
  18343. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  18344. } else {
  18345. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  18346. }
  18347. //
  18348. if ( renderer.autoClear === true || forceClear === true ) {
  18349. const clearColorValue = renderContext.clearColorValue;
  18350. clearColorValue.r = _clearColor$1.r;
  18351. clearColorValue.g = _clearColor$1.g;
  18352. clearColorValue.b = _clearColor$1.b;
  18353. clearColorValue.a = _clearColor$1.a;
  18354. // premultiply alpha
  18355. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  18356. clearColorValue.r *= clearColorValue.a;
  18357. clearColorValue.g *= clearColorValue.a;
  18358. clearColorValue.b *= clearColorValue.a;
  18359. }
  18360. //
  18361. renderContext.depthClearValue = renderer._clearDepth;
  18362. renderContext.stencilClearValue = renderer._clearStencil;
  18363. renderContext.clearColor = renderer.autoClearColor === true;
  18364. renderContext.clearDepth = renderer.autoClearDepth === true;
  18365. renderContext.clearStencil = renderer.autoClearStencil === true;
  18366. } else {
  18367. renderContext.clearColor = false;
  18368. renderContext.clearDepth = false;
  18369. renderContext.clearStencil = false;
  18370. }
  18371. }
  18372. }
  18373. let _id$6 = 0;
  18374. class BindGroup {
  18375. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  18376. this.name = name;
  18377. this.bindings = bindings;
  18378. this.index = index;
  18379. this.bindingsReference = bindingsReference;
  18380. this.id = _id$6 ++;
  18381. }
  18382. }
  18383. class NodeBuilderState {
  18384. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  18385. this.vertexShader = vertexShader;
  18386. this.fragmentShader = fragmentShader;
  18387. this.computeShader = computeShader;
  18388. this.transforms = transforms;
  18389. this.nodeAttributes = nodeAttributes;
  18390. this.bindings = bindings;
  18391. this.updateNodes = updateNodes;
  18392. this.updateBeforeNodes = updateBeforeNodes;
  18393. this.updateAfterNodes = updateAfterNodes;
  18394. this.monitor = monitor;
  18395. this.usedTimes = 0;
  18396. }
  18397. createBindings() {
  18398. const bindings = [];
  18399. for ( const instanceGroup of this.bindings ) {
  18400. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  18401. if ( shared !== true ) {
  18402. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  18403. bindings.push( bindingsGroup );
  18404. for ( const instanceBinding of instanceGroup.bindings ) {
  18405. bindingsGroup.bindings.push( instanceBinding.clone() );
  18406. }
  18407. } else {
  18408. bindings.push( instanceGroup );
  18409. }
  18410. }
  18411. return bindings;
  18412. }
  18413. }
  18414. /**
  18415. * {@link NodeBuilder} is going to create instances of this class during the build process
  18416. * of nodes. They represent the final shader attributes that are going to be generated
  18417. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  18418. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  18419. */
  18420. class NodeAttribute {
  18421. /**
  18422. * Constructs a new node attribute.
  18423. *
  18424. * @param {String} name - The name of the attribute.
  18425. * @param {String} type - The type of the attribute.
  18426. * @param {Node?} node - An optional reference to the node.
  18427. */
  18428. constructor( name, type, node = null ) {
  18429. /**
  18430. * This flag can be used for type testing.
  18431. *
  18432. * @type {Boolean}
  18433. * @readonly
  18434. * @default true
  18435. */
  18436. this.isNodeAttribute = true;
  18437. /**
  18438. * The name of the attribute.
  18439. *
  18440. * @type {String}
  18441. */
  18442. this.name = name;
  18443. /**
  18444. * The type of the attribute.
  18445. *
  18446. * @type {String}
  18447. */
  18448. this.type = type;
  18449. /**
  18450. * An optional reference to the node.
  18451. *
  18452. * @type {Node?}
  18453. * @default null
  18454. */
  18455. this.node = node;
  18456. }
  18457. }
  18458. /**
  18459. * {@link NodeBuilder} is going to create instances of this class during the build process
  18460. * of nodes. They represent the final shader uniforms that are going to be generated
  18461. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  18462. * for this purpose.
  18463. */
  18464. class NodeUniform {
  18465. /**
  18466. * Constructs a new node uniform.
  18467. *
  18468. * @param {String} name - The name of the uniform.
  18469. * @param {String} type - The type of the uniform.
  18470. * @param {UniformNode} node - An reference to the node.
  18471. */
  18472. constructor( name, type, node ) {
  18473. /**
  18474. * This flag can be used for type testing.
  18475. *
  18476. * @type {Boolean}
  18477. * @readonly
  18478. * @default true
  18479. */
  18480. this.isNodeUniform = true;
  18481. /**
  18482. * The name of the uniform.
  18483. *
  18484. * @type {String}
  18485. */
  18486. this.name = name;
  18487. /**
  18488. * The type of the uniform.
  18489. *
  18490. * @type {String}
  18491. */
  18492. this.type = type;
  18493. /**
  18494. * An reference to the node.
  18495. *
  18496. * @type {UniformNode}
  18497. */
  18498. this.node = node.getSelf();
  18499. }
  18500. /**
  18501. * The value of the uniform node.
  18502. *
  18503. * @type {Any}
  18504. */
  18505. get value() {
  18506. return this.node.value;
  18507. }
  18508. set value( val ) {
  18509. this.node.value = val;
  18510. }
  18511. /**
  18512. * The id of the uniform node.
  18513. *
  18514. * @type {Number}
  18515. */
  18516. get id() {
  18517. return this.node.id;
  18518. }
  18519. /**
  18520. * The uniform node's group.
  18521. *
  18522. * @type {UniformGroupNode}
  18523. */
  18524. get groupNode() {
  18525. return this.node.groupNode;
  18526. }
  18527. }
  18528. /**
  18529. * {@link NodeBuilder} is going to create instances of this class during the build process
  18530. * of nodes. They represent the final shader variables that are going to be generated
  18531. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  18532. * this purpose.
  18533. */
  18534. class NodeVar {
  18535. /**
  18536. * Constructs a new node variable.
  18537. *
  18538. * @param {String} name - The name of the variable.
  18539. * @param {String} type - The type of the variable.
  18540. */
  18541. constructor( name, type ) {
  18542. /**
  18543. * This flag can be used for type testing.
  18544. *
  18545. * @type {Boolean}
  18546. * @readonly
  18547. * @default true
  18548. */
  18549. this.isNodeVar = true;
  18550. /**
  18551. * The name of the variable.
  18552. *
  18553. * @type {String}
  18554. */
  18555. this.name = name;
  18556. /**
  18557. * The type of the variable.
  18558. *
  18559. * @type {String}
  18560. */
  18561. this.type = type;
  18562. }
  18563. }
  18564. /**
  18565. * {@link NodeBuilder} is going to create instances of this class during the build process
  18566. * of nodes. They represent the final shader varyings that are going to be generated
  18567. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  18568. * this purpose.
  18569. *
  18570. * @augments NodeVar
  18571. */
  18572. class NodeVarying extends NodeVar {
  18573. /**
  18574. * Constructs a new node varying.
  18575. *
  18576. * @param {String} name - The name of the varying.
  18577. * @param {String} type - The type of the varying.
  18578. */
  18579. constructor( name, type ) {
  18580. super( name, type );
  18581. /**
  18582. * Whether this varying requires interpolation or not. This property can be used
  18583. * to check if the varying can be optimized for a variable.
  18584. *
  18585. * @type {Boolean}
  18586. * @default false
  18587. */
  18588. this.needsInterpolation = false;
  18589. /**
  18590. * This flag can be used for type testing.
  18591. *
  18592. * @type {Boolean}
  18593. * @readonly
  18594. * @default true
  18595. */
  18596. this.isNodeVarying = true;
  18597. }
  18598. }
  18599. /**
  18600. * {@link NodeBuilder} is going to create instances of this class during the build process
  18601. * of nodes. They represent user-defined, native shader code portions that are going to be
  18602. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  18603. * for this purpose.
  18604. */
  18605. class NodeCode {
  18606. /**
  18607. * Constructs a new code node.
  18608. *
  18609. * @param {String} name - The name of the code.
  18610. * @param {String} type - The node type.
  18611. * @param {String} [code=''] - The native shader code.
  18612. */
  18613. constructor( name, type, code = '' ) {
  18614. /**
  18615. * The name of the code.
  18616. *
  18617. * @type {String}
  18618. */
  18619. this.name = name;
  18620. /**
  18621. * The node type.
  18622. *
  18623. * @type {String}
  18624. */
  18625. this.type = type;
  18626. /**
  18627. * The native shader code.
  18628. *
  18629. * @type {String}
  18630. * @default ''
  18631. */
  18632. this.code = code;
  18633. Object.defineProperty( this, 'isNodeCode', { value: true } );
  18634. }
  18635. }
  18636. let _id$5 = 0;
  18637. /**
  18638. * This utility class is used in {@link NodeBuilder} as an internal
  18639. * cache data structure for node data.
  18640. */
  18641. class NodeCache {
  18642. /**
  18643. * Constructs a new node cache.
  18644. *
  18645. * @param {NodeCache?} parent - A reference to a parent cache.
  18646. */
  18647. constructor( parent = null ) {
  18648. /**
  18649. * The id of the cache.
  18650. *
  18651. * @type {Number}
  18652. * @readonly
  18653. */
  18654. this.id = _id$5 ++;
  18655. /**
  18656. * A weak map for managing node data.
  18657. *
  18658. * @type {WeakMap<Node, Object>}
  18659. */
  18660. this.nodesData = new WeakMap();
  18661. /**
  18662. * Reference to a parent node cache.
  18663. *
  18664. * @type {NodeCache?}
  18665. * @default null
  18666. */
  18667. this.parent = parent;
  18668. }
  18669. /**
  18670. * Returns the data for the given node.
  18671. *
  18672. * @param {Node} node - The node.
  18673. * @return {Object?} The data for the node.
  18674. */
  18675. getData( node ) {
  18676. let data = this.nodesData.get( node );
  18677. if ( data === undefined && this.parent !== null ) {
  18678. data = this.parent.getData( node );
  18679. }
  18680. return data;
  18681. }
  18682. /**
  18683. * Sets the data for a given node.
  18684. *
  18685. * @param {Node} node - The node.
  18686. * @param {Object} data - The data that should be cached.
  18687. */
  18688. setData( node, data ) {
  18689. this.nodesData.set( node, data );
  18690. }
  18691. }
  18692. /**
  18693. * {@link NodeBuilder} is going to create instances of this class during the build process
  18694. * of nodes. They represent the final shader struct data that are going to be generated
  18695. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  18696. * for this purpose.
  18697. */
  18698. class StructTypeNode extends Node {
  18699. static get type() {
  18700. return 'StructTypeNode';
  18701. }
  18702. /**
  18703. * Constructs a new struct type node.
  18704. *
  18705. * @param {String} name - The name of the struct.
  18706. * @param {Array<String>} types - An array of types.
  18707. */
  18708. constructor( name, types ) {
  18709. super();
  18710. /**
  18711. * The name of the struct.
  18712. *
  18713. * @type {String}
  18714. */
  18715. this.name = name;
  18716. /**
  18717. * An array of types.
  18718. *
  18719. * @type {Array<String>}
  18720. */
  18721. this.types = types;
  18722. /**
  18723. * This flag can be used for type testing.
  18724. *
  18725. * @type {Boolean}
  18726. * @readonly
  18727. * @default true
  18728. */
  18729. this.isStructTypeNode = true;
  18730. }
  18731. /**
  18732. * Returns the member types.
  18733. *
  18734. * @return {Array<String>} The types.
  18735. */
  18736. getMemberTypes() {
  18737. return this.types;
  18738. }
  18739. }
  18740. class Uniform {
  18741. constructor( name, value ) {
  18742. this.name = name;
  18743. this.value = value;
  18744. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  18745. this.itemSize = 0;
  18746. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  18747. }
  18748. setValue( value ) {
  18749. this.value = value;
  18750. }
  18751. getValue() {
  18752. return this.value;
  18753. }
  18754. }
  18755. class NumberUniform extends Uniform {
  18756. constructor( name, value = 0 ) {
  18757. super( name, value );
  18758. this.isNumberUniform = true;
  18759. this.boundary = 4;
  18760. this.itemSize = 1;
  18761. }
  18762. }
  18763. class Vector2Uniform extends Uniform {
  18764. constructor( name, value = new Vector2() ) {
  18765. super( name, value );
  18766. this.isVector2Uniform = true;
  18767. this.boundary = 8;
  18768. this.itemSize = 2;
  18769. }
  18770. }
  18771. class Vector3Uniform extends Uniform {
  18772. constructor( name, value = new Vector3() ) {
  18773. super( name, value );
  18774. this.isVector3Uniform = true;
  18775. this.boundary = 16;
  18776. this.itemSize = 3;
  18777. }
  18778. }
  18779. class Vector4Uniform extends Uniform {
  18780. constructor( name, value = new Vector4() ) {
  18781. super( name, value );
  18782. this.isVector4Uniform = true;
  18783. this.boundary = 16;
  18784. this.itemSize = 4;
  18785. }
  18786. }
  18787. class ColorUniform extends Uniform {
  18788. constructor( name, value = new Color() ) {
  18789. super( name, value );
  18790. this.isColorUniform = true;
  18791. this.boundary = 16;
  18792. this.itemSize = 3;
  18793. }
  18794. }
  18795. class Matrix3Uniform extends Uniform {
  18796. constructor( name, value = new Matrix3() ) {
  18797. super( name, value );
  18798. this.isMatrix3Uniform = true;
  18799. this.boundary = 48;
  18800. this.itemSize = 12;
  18801. }
  18802. }
  18803. class Matrix4Uniform extends Uniform {
  18804. constructor( name, value = new Matrix4() ) {
  18805. super( name, value );
  18806. this.isMatrix4Uniform = true;
  18807. this.boundary = 64;
  18808. this.itemSize = 16;
  18809. }
  18810. }
  18811. class NumberNodeUniform extends NumberUniform {
  18812. constructor( nodeUniform ) {
  18813. super( nodeUniform.name, nodeUniform.value );
  18814. this.nodeUniform = nodeUniform;
  18815. }
  18816. getValue() {
  18817. return this.nodeUniform.value;
  18818. }
  18819. getType() {
  18820. return this.nodeUniform.type;
  18821. }
  18822. }
  18823. class Vector2NodeUniform extends Vector2Uniform {
  18824. constructor( nodeUniform ) {
  18825. super( nodeUniform.name, nodeUniform.value );
  18826. this.nodeUniform = nodeUniform;
  18827. }
  18828. getValue() {
  18829. return this.nodeUniform.value;
  18830. }
  18831. getType() {
  18832. return this.nodeUniform.type;
  18833. }
  18834. }
  18835. class Vector3NodeUniform extends Vector3Uniform {
  18836. constructor( nodeUniform ) {
  18837. super( nodeUniform.name, nodeUniform.value );
  18838. this.nodeUniform = nodeUniform;
  18839. }
  18840. getValue() {
  18841. return this.nodeUniform.value;
  18842. }
  18843. getType() {
  18844. return this.nodeUniform.type;
  18845. }
  18846. }
  18847. class Vector4NodeUniform extends Vector4Uniform {
  18848. constructor( nodeUniform ) {
  18849. super( nodeUniform.name, nodeUniform.value );
  18850. this.nodeUniform = nodeUniform;
  18851. }
  18852. getValue() {
  18853. return this.nodeUniform.value;
  18854. }
  18855. getType() {
  18856. return this.nodeUniform.type;
  18857. }
  18858. }
  18859. class ColorNodeUniform extends ColorUniform {
  18860. constructor( nodeUniform ) {
  18861. super( nodeUniform.name, nodeUniform.value );
  18862. this.nodeUniform = nodeUniform;
  18863. }
  18864. getValue() {
  18865. return this.nodeUniform.value;
  18866. }
  18867. getType() {
  18868. return this.nodeUniform.type;
  18869. }
  18870. }
  18871. class Matrix3NodeUniform extends Matrix3Uniform {
  18872. constructor( nodeUniform ) {
  18873. super( nodeUniform.name, nodeUniform.value );
  18874. this.nodeUniform = nodeUniform;
  18875. }
  18876. getValue() {
  18877. return this.nodeUniform.value;
  18878. }
  18879. getType() {
  18880. return this.nodeUniform.type;
  18881. }
  18882. }
  18883. class Matrix4NodeUniform extends Matrix4Uniform {
  18884. constructor( nodeUniform ) {
  18885. super( nodeUniform.name, nodeUniform.value );
  18886. this.nodeUniform = nodeUniform;
  18887. }
  18888. getValue() {
  18889. return this.nodeUniform.value;
  18890. }
  18891. getType() {
  18892. return this.nodeUniform.type;
  18893. }
  18894. }
  18895. const LOD_MIN = 4;
  18896. // The standard deviations (radians) associated with the extra mips. These are
  18897. // chosen to approximate a Trowbridge-Reitz distribution function times the
  18898. // geometric shadowing function. These sigma values squared must match the
  18899. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  18900. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18901. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18902. // samples and exit early, but not recompile the shader.
  18903. const MAX_SAMPLES = 20;
  18904. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  18905. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18906. const _clearColor = /*@__PURE__*/ new Color();
  18907. let _oldTarget = null;
  18908. let _oldActiveCubeFace = 0;
  18909. let _oldActiveMipmapLevel = 0;
  18910. // Golden Ratio
  18911. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  18912. const INV_PHI = 1 / PHI;
  18913. // Vertices of a dodecahedron (except the opposites, which represent the
  18914. // same axis), used as axis directions evenly spread on a sphere.
  18915. const _axisDirections = [
  18916. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  18917. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  18918. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  18919. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  18920. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  18921. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  18922. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  18923. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  18924. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  18925. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  18926. ];
  18927. //
  18928. // WebGPU Face indices
  18929. const _faceLib = [
  18930. 3, 1, 5,
  18931. 0, 4, 2
  18932. ];
  18933. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  18934. const outputDirection = vec3( direction.x, direction.y, direction.z );
  18935. /**
  18936. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18937. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18938. * blur to be quickly accessed based on material roughness. It is packed into a
  18939. * special CubeUV format that allows us to perform custom interpolation so that
  18940. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18941. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18942. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18943. * higher roughness levels. In this way we maintain resolution to smoothly
  18944. * interpolate diffuse lighting while limiting sampling computation.
  18945. *
  18946. * Paper: Fast, Accurate Image-Based Lighting
  18947. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  18948. */
  18949. class PMREMGenerator {
  18950. constructor( renderer ) {
  18951. this._renderer = renderer;
  18952. this._pingPongRenderTarget = null;
  18953. this._lodMax = 0;
  18954. this._cubeSize = 0;
  18955. this._lodPlanes = [];
  18956. this._sizeLods = [];
  18957. this._sigmas = [];
  18958. this._lodMeshes = [];
  18959. this._blurMaterial = null;
  18960. this._cubemapMaterial = null;
  18961. this._equirectMaterial = null;
  18962. this._backgroundBox = null;
  18963. }
  18964. get _hasInitialized() {
  18965. return this._renderer.hasInitialized();
  18966. }
  18967. /**
  18968. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18969. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18970. * in radians to be applied to the scene before PMREM generation. Optional near
  18971. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18972. * is placed at the origin).
  18973. *
  18974. * @param {Scene} scene - The scene to be captured.
  18975. * @param {Number} [sigma=0] - The blur radius in radians.
  18976. * @param {Number} [near=0.1] - The near plane distance.
  18977. * @param {Number} [far=100] - The far plane distance.
  18978. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  18979. * @return {RenderTarget} The resulting PMREM.
  18980. */
  18981. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  18982. this._setSize( 256 );
  18983. if ( this._hasInitialized === false ) {
  18984. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  18985. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18986. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  18987. return cubeUVRenderTarget;
  18988. }
  18989. _oldTarget = this._renderer.getRenderTarget();
  18990. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18991. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18992. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18993. cubeUVRenderTarget.depthBuffer = true;
  18994. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  18995. if ( sigma > 0 ) {
  18996. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18997. }
  18998. this._applyPMREM( cubeUVRenderTarget );
  18999. this._cleanup( cubeUVRenderTarget );
  19000. return cubeUVRenderTarget;
  19001. }
  19002. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  19003. if ( this._hasInitialized === false ) await this._renderer.init();
  19004. return this.fromScene( scene, sigma, near, far, renderTarget );
  19005. }
  19006. /**
  19007. * Generates a PMREM from an equirectangular texture, which can be either LDR
  19008. * or HDR. The ideal input image size is 1k (1024 x 512),
  19009. * as this matches best with the 256 x 256 cubemap output.
  19010. *
  19011. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  19012. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  19013. * @return {RenderTarget} The resulting PMREM.
  19014. */
  19015. fromEquirectangular( equirectangular, renderTarget = null ) {
  19016. if ( this._hasInitialized === false ) {
  19017. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  19018. this._setSizeFromTexture( equirectangular );
  19019. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  19020. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  19021. return cubeUVRenderTarget;
  19022. }
  19023. return this._fromTexture( equirectangular, renderTarget );
  19024. }
  19025. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  19026. if ( this._hasInitialized === false ) await this._renderer.init();
  19027. return this._fromTexture( equirectangular, renderTarget );
  19028. }
  19029. /**
  19030. * Generates a PMREM from an cubemap texture, which can be either LDR
  19031. * or HDR. The ideal input cube size is 256 x 256,
  19032. * as this matches best with the 256 x 256 cubemap output.
  19033. *
  19034. * @param {Texture} cubemap - The cubemap texture to be converted.
  19035. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  19036. * @return {RenderTarget} The resulting PMREM.
  19037. */
  19038. fromCubemap( cubemap, renderTarget = null ) {
  19039. if ( this._hasInitialized === false ) {
  19040. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  19041. this._setSizeFromTexture( cubemap );
  19042. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  19043. this.fromCubemapAsync( cubemap, renderTarget );
  19044. return cubeUVRenderTarget;
  19045. }
  19046. return this._fromTexture( cubemap, renderTarget );
  19047. }
  19048. async fromCubemapAsync( cubemap, renderTarget = null ) {
  19049. if ( this._hasInitialized === false ) await this._renderer.init();
  19050. return this._fromTexture( cubemap, renderTarget );
  19051. }
  19052. /**
  19053. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  19054. * your texture's network fetch for increased concurrency.
  19055. */
  19056. async compileCubemapShader() {
  19057. if ( this._cubemapMaterial === null ) {
  19058. this._cubemapMaterial = _getCubemapMaterial();
  19059. await this._compileMaterial( this._cubemapMaterial );
  19060. }
  19061. }
  19062. /**
  19063. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  19064. * your texture's network fetch for increased concurrency.
  19065. */
  19066. async compileEquirectangularShader() {
  19067. if ( this._equirectMaterial === null ) {
  19068. this._equirectMaterial = _getEquirectMaterial();
  19069. await this._compileMaterial( this._equirectMaterial );
  19070. }
  19071. }
  19072. /**
  19073. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  19074. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  19075. * one of them will cause any others to also become unusable.
  19076. */
  19077. dispose() {
  19078. this._dispose();
  19079. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  19080. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  19081. if ( this._backgroundBox !== null ) {
  19082. this._backgroundBox.geometry.dispose();
  19083. this._backgroundBox.material.dispose();
  19084. }
  19085. }
  19086. // private interface
  19087. _setSizeFromTexture( texture ) {
  19088. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  19089. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  19090. } else { // Equirectangular
  19091. this._setSize( texture.image.width / 4 );
  19092. }
  19093. }
  19094. _setSize( cubeSize ) {
  19095. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  19096. this._cubeSize = Math.pow( 2, this._lodMax );
  19097. }
  19098. _dispose() {
  19099. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  19100. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  19101. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  19102. this._lodPlanes[ i ].dispose();
  19103. }
  19104. }
  19105. _cleanup( outputTarget ) {
  19106. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  19107. outputTarget.scissorTest = false;
  19108. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  19109. }
  19110. _fromTexture( texture, renderTarget ) {
  19111. this._setSizeFromTexture( texture );
  19112. _oldTarget = this._renderer.getRenderTarget();
  19113. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  19114. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  19115. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  19116. this._textureToCubeUV( texture, cubeUVRenderTarget );
  19117. this._applyPMREM( cubeUVRenderTarget );
  19118. this._cleanup( cubeUVRenderTarget );
  19119. return cubeUVRenderTarget;
  19120. }
  19121. _allocateTargets() {
  19122. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  19123. const height = 4 * this._cubeSize;
  19124. const params = {
  19125. magFilter: LinearFilter,
  19126. minFilter: LinearFilter,
  19127. generateMipmaps: false,
  19128. type: HalfFloatType,
  19129. format: RGBAFormat,
  19130. colorSpace: LinearSRGBColorSpace,
  19131. //depthBuffer: false
  19132. };
  19133. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  19134. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  19135. if ( this._pingPongRenderTarget !== null ) {
  19136. this._dispose();
  19137. }
  19138. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  19139. const { _lodMax } = this;
  19140. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  19141. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  19142. }
  19143. return cubeUVRenderTarget;
  19144. }
  19145. async _compileMaterial( material ) {
  19146. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  19147. await this._renderer.compile( tmpMesh, _flatCamera );
  19148. }
  19149. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  19150. const cubeCamera = _cubeCamera;
  19151. cubeCamera.near = near;
  19152. cubeCamera.far = far;
  19153. // px, py, pz, nx, ny, nz
  19154. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  19155. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  19156. const renderer = this._renderer;
  19157. const originalAutoClear = renderer.autoClear;
  19158. renderer.getClearColor( _clearColor );
  19159. renderer.autoClear = false;
  19160. let backgroundBox = this._backgroundBox;
  19161. if ( backgroundBox === null ) {
  19162. const backgroundMaterial = new MeshBasicMaterial( {
  19163. name: 'PMREM.Background',
  19164. side: BackSide,
  19165. depthWrite: false,
  19166. depthTest: false
  19167. } );
  19168. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  19169. }
  19170. let useSolidColor = false;
  19171. const background = scene.background;
  19172. if ( background ) {
  19173. if ( background.isColor ) {
  19174. backgroundBox.material.color.copy( background );
  19175. scene.background = null;
  19176. useSolidColor = true;
  19177. }
  19178. } else {
  19179. backgroundBox.material.color.copy( _clearColor );
  19180. useSolidColor = true;
  19181. }
  19182. renderer.setRenderTarget( cubeUVRenderTarget );
  19183. renderer.clear();
  19184. if ( useSolidColor ) {
  19185. renderer.render( backgroundBox, cubeCamera );
  19186. }
  19187. for ( let i = 0; i < 6; i ++ ) {
  19188. const col = i % 3;
  19189. if ( col === 0 ) {
  19190. cubeCamera.up.set( 0, upSign[ i ], 0 );
  19191. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  19192. } else if ( col === 1 ) {
  19193. cubeCamera.up.set( 0, 0, upSign[ i ] );
  19194. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  19195. } else {
  19196. cubeCamera.up.set( 0, upSign[ i ], 0 );
  19197. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  19198. }
  19199. const size = this._cubeSize;
  19200. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  19201. renderer.render( scene, cubeCamera );
  19202. }
  19203. renderer.autoClear = originalAutoClear;
  19204. scene.background = background;
  19205. }
  19206. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  19207. const renderer = this._renderer;
  19208. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  19209. if ( isCubeTexture ) {
  19210. if ( this._cubemapMaterial === null ) {
  19211. this._cubemapMaterial = _getCubemapMaterial( texture );
  19212. }
  19213. } else {
  19214. if ( this._equirectMaterial === null ) {
  19215. this._equirectMaterial = _getEquirectMaterial( texture );
  19216. }
  19217. }
  19218. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  19219. material.fragmentNode.value = texture;
  19220. const mesh = this._lodMeshes[ 0 ];
  19221. mesh.material = material;
  19222. const size = this._cubeSize;
  19223. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  19224. renderer.setRenderTarget( cubeUVRenderTarget );
  19225. renderer.render( mesh, _flatCamera );
  19226. }
  19227. _applyPMREM( cubeUVRenderTarget ) {
  19228. const renderer = this._renderer;
  19229. const autoClear = renderer.autoClear;
  19230. renderer.autoClear = false;
  19231. const n = this._lodPlanes.length;
  19232. for ( let i = 1; i < n; i ++ ) {
  19233. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  19234. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  19235. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  19236. }
  19237. renderer.autoClear = autoClear;
  19238. }
  19239. /**
  19240. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  19241. * vertically and horizontally, but this breaks down on a cube. Here we apply
  19242. * the blur latitudinally (around the poles), and then longitudinally (towards
  19243. * the poles) to approximate the orthogonally-separable blur. It is least
  19244. * accurate at the poles, but still does a decent job.
  19245. *
  19246. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  19247. * @param {Number} lodIn - The input level-of-detail.
  19248. * @param {Number} lodOut - The output level-of-detail.
  19249. * @param {Number} sigma - The blur radius in radians.
  19250. * @param {Vector3} [poleAxis] - The pole axis.
  19251. */
  19252. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  19253. const pingPongRenderTarget = this._pingPongRenderTarget;
  19254. this._halfBlur(
  19255. cubeUVRenderTarget,
  19256. pingPongRenderTarget,
  19257. lodIn,
  19258. lodOut,
  19259. sigma,
  19260. 'latitudinal',
  19261. poleAxis );
  19262. this._halfBlur(
  19263. pingPongRenderTarget,
  19264. cubeUVRenderTarget,
  19265. lodOut,
  19266. lodOut,
  19267. sigma,
  19268. 'longitudinal',
  19269. poleAxis );
  19270. }
  19271. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  19272. const renderer = this._renderer;
  19273. const blurMaterial = this._blurMaterial;
  19274. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  19275. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  19276. }
  19277. // Number of standard deviations at which to cut off the discrete approximation.
  19278. const STANDARD_DEVIATIONS = 3;
  19279. const blurMesh = this._lodMeshes[ lodOut ];
  19280. blurMesh.material = blurMaterial;
  19281. const blurUniforms = blurMaterial.uniforms;
  19282. const pixels = this._sizeLods[ lodIn ] - 1;
  19283. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  19284. const sigmaPixels = sigmaRadians / radiansPerPixel;
  19285. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  19286. if ( samples > MAX_SAMPLES ) {
  19287. console.warn( `sigmaRadians, ${
  19288. sigmaRadians}, is too large and will clip, as it requested ${
  19289. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  19290. }
  19291. const weights = [];
  19292. let sum = 0;
  19293. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  19294. const x = i / sigmaPixels;
  19295. const weight = Math.exp( - x * x / 2 );
  19296. weights.push( weight );
  19297. if ( i === 0 ) {
  19298. sum += weight;
  19299. } else if ( i < samples ) {
  19300. sum += 2 * weight;
  19301. }
  19302. }
  19303. for ( let i = 0; i < weights.length; i ++ ) {
  19304. weights[ i ] = weights[ i ] / sum;
  19305. }
  19306. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  19307. blurUniforms.envMap.value = targetIn.texture;
  19308. blurUniforms.samples.value = samples;
  19309. blurUniforms.weights.array = weights;
  19310. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  19311. if ( poleAxis ) {
  19312. blurUniforms.poleAxis.value = poleAxis;
  19313. }
  19314. const { _lodMax } = this;
  19315. blurUniforms.dTheta.value = radiansPerPixel;
  19316. blurUniforms.mipInt.value = _lodMax - lodIn;
  19317. const outputSize = this._sizeLods[ lodOut ];
  19318. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  19319. const y = 4 * ( this._cubeSize - outputSize );
  19320. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  19321. renderer.setRenderTarget( targetOut );
  19322. renderer.render( blurMesh, _flatCamera );
  19323. }
  19324. }
  19325. function _createPlanes( lodMax ) {
  19326. const lodPlanes = [];
  19327. const sizeLods = [];
  19328. const sigmas = [];
  19329. const lodMeshes = [];
  19330. let lod = lodMax;
  19331. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  19332. for ( let i = 0; i < totalLods; i ++ ) {
  19333. const sizeLod = Math.pow( 2, lod );
  19334. sizeLods.push( sizeLod );
  19335. let sigma = 1.0 / sizeLod;
  19336. if ( i > lodMax - LOD_MIN ) {
  19337. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  19338. } else if ( i === 0 ) {
  19339. sigma = 0;
  19340. }
  19341. sigmas.push( sigma );
  19342. const texelSize = 1.0 / ( sizeLod - 2 );
  19343. const min = - texelSize;
  19344. const max = 1 + texelSize;
  19345. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  19346. const cubeFaces = 6;
  19347. const vertices = 6;
  19348. const positionSize = 3;
  19349. const uvSize = 2;
  19350. const faceIndexSize = 1;
  19351. const position = new Float32Array( positionSize * vertices * cubeFaces );
  19352. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  19353. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  19354. for ( let face = 0; face < cubeFaces; face ++ ) {
  19355. const x = ( face % 3 ) * 2 / 3 - 1;
  19356. const y = face > 2 ? 0 : - 1;
  19357. const coordinates = [
  19358. x, y, 0,
  19359. x + 2 / 3, y, 0,
  19360. x + 2 / 3, y + 1, 0,
  19361. x, y, 0,
  19362. x + 2 / 3, y + 1, 0,
  19363. x, y + 1, 0
  19364. ];
  19365. const faceIdx = _faceLib[ face ];
  19366. position.set( coordinates, positionSize * vertices * faceIdx );
  19367. uv.set( uv1, uvSize * vertices * faceIdx );
  19368. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  19369. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  19370. }
  19371. const planes = new BufferGeometry();
  19372. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  19373. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  19374. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  19375. lodPlanes.push( planes );
  19376. lodMeshes.push( new Mesh( planes, null ) );
  19377. if ( lod > LOD_MIN ) {
  19378. lod --;
  19379. }
  19380. }
  19381. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  19382. }
  19383. function _createRenderTarget( width, height, params ) {
  19384. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  19385. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  19386. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  19387. cubeUVRenderTarget.texture.isPMREMTexture = true;
  19388. cubeUVRenderTarget.scissorTest = true;
  19389. return cubeUVRenderTarget;
  19390. }
  19391. function _setViewport( target, x, y, width, height ) {
  19392. target.viewport.set( x, y, width, height );
  19393. target.scissor.set( x, y, width, height );
  19394. }
  19395. function _getMaterial( type ) {
  19396. const material = new NodeMaterial();
  19397. material.depthTest = false;
  19398. material.depthWrite = false;
  19399. material.blending = NoBlending;
  19400. material.name = `PMREM_${ type }`;
  19401. return material;
  19402. }
  19403. function _getBlurShader( lodMax, width, height ) {
  19404. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  19405. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  19406. const dTheta = uniform( 0 );
  19407. const n = float( MAX_SAMPLES );
  19408. const latitudinal = uniform( 0 ); // false, bool
  19409. const samples = uniform( 1 ); // int
  19410. const envMap = texture( null );
  19411. const mipInt = uniform( 0 ); // int
  19412. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  19413. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  19414. const CUBEUV_MAX_MIP = float( lodMax );
  19415. const materialUniforms = {
  19416. n,
  19417. latitudinal,
  19418. weights,
  19419. poleAxis,
  19420. outputDirection,
  19421. dTheta,
  19422. samples,
  19423. envMap,
  19424. mipInt,
  19425. CUBEUV_TEXEL_WIDTH,
  19426. CUBEUV_TEXEL_HEIGHT,
  19427. CUBEUV_MAX_MIP
  19428. };
  19429. const material = _getMaterial( 'blur' );
  19430. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  19431. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  19432. return material;
  19433. }
  19434. function _getCubemapMaterial( envTexture ) {
  19435. const material = _getMaterial( 'cubemap' );
  19436. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  19437. return material;
  19438. }
  19439. function _getEquirectMaterial( envTexture ) {
  19440. const material = _getMaterial( 'equirect' );
  19441. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  19442. return material;
  19443. }
  19444. const rendererCache = new WeakMap();
  19445. const typeFromArray = new Map( [
  19446. [ Int8Array, 'int' ],
  19447. [ Int16Array, 'int' ],
  19448. [ Int32Array, 'int' ],
  19449. [ Uint8Array, 'uint' ],
  19450. [ Uint16Array, 'uint' ],
  19451. [ Uint32Array, 'uint' ],
  19452. [ Float32Array, 'float' ]
  19453. ] );
  19454. const toFloat = ( value ) => {
  19455. if ( /e/g.test( value ) ) {
  19456. return String( value ).replace( /\+/g, '' );
  19457. } else {
  19458. value = Number( value );
  19459. return value + ( value % 1 ? '' : '.0' );
  19460. }
  19461. };
  19462. /**
  19463. * Base class for builders which generate a shader program based
  19464. * on a 3D object and its node material definition.
  19465. */
  19466. class NodeBuilder {
  19467. /**
  19468. * Constructs a new node builder.
  19469. *
  19470. * @param {Object3D} object - The 3D object.
  19471. * @param {Renderer} renderer - The current renderer.
  19472. * @param {NodeParser} parser - A reference to a node parser.
  19473. */
  19474. constructor( object, renderer, parser ) {
  19475. /**
  19476. * The 3D object.
  19477. *
  19478. * @type {Object3D}
  19479. */
  19480. this.object = object;
  19481. /**
  19482. * The material of the 3D object.
  19483. *
  19484. * @type {Material?}
  19485. */
  19486. this.material = ( object && object.material ) || null;
  19487. /**
  19488. * The geometry of the 3D object.
  19489. *
  19490. * @type {BufferGeometry?}
  19491. */
  19492. this.geometry = ( object && object.geometry ) || null;
  19493. /**
  19494. * The current renderer.
  19495. *
  19496. * @type {Renderer}
  19497. */
  19498. this.renderer = renderer;
  19499. /**
  19500. * A reference to a node parser.
  19501. *
  19502. * @type {NodeParser}
  19503. */
  19504. this.parser = parser;
  19505. /**
  19506. * The scene the 3D object belongs to.
  19507. *
  19508. * @type {Scene?}
  19509. * @default null
  19510. */
  19511. this.scene = null;
  19512. /**
  19513. * The camera the 3D object is rendered with.
  19514. *
  19515. * @type {Camera?}
  19516. * @default null
  19517. */
  19518. this.camera = null;
  19519. /**
  19520. * A list of all nodes the builder is processing
  19521. * for this 3D object.
  19522. *
  19523. * @type {Array<Node>}
  19524. */
  19525. this.nodes = [];
  19526. /**
  19527. * A list of all sequential nodes.
  19528. *
  19529. * @type {Array<Node>}
  19530. */
  19531. this.sequentialNodes = [];
  19532. /**
  19533. * A list of all nodes which {@link Node#update} method should be executed.
  19534. *
  19535. * @type {Array<Node>}
  19536. */
  19537. this.updateNodes = [];
  19538. /**
  19539. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  19540. *
  19541. * @type {Array<Node>}
  19542. */
  19543. this.updateBeforeNodes = [];
  19544. /**
  19545. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  19546. *
  19547. * @type {Array<Node>}
  19548. */
  19549. this.updateAfterNodes = [];
  19550. /**
  19551. * A dictionary that assigns each node to a unique hash.
  19552. *
  19553. * @type {Object<Number,Node>}
  19554. */
  19555. this.hashNodes = {};
  19556. /**
  19557. * A reference to a node material observer.
  19558. *
  19559. * @type {NodeMaterialObserver?}
  19560. * @default null
  19561. */
  19562. this.monitor = null;
  19563. /**
  19564. * A reference to the current lights node.
  19565. *
  19566. * @type {LightsNode?}
  19567. * @default null
  19568. */
  19569. this.lightsNode = null;
  19570. /**
  19571. * A reference to the current environment node.
  19572. *
  19573. * @type {Node?}
  19574. * @default null
  19575. */
  19576. this.environmentNode = null;
  19577. /**
  19578. * A reference to the current fog node.
  19579. *
  19580. * @type {FogNode?}
  19581. * @default null
  19582. */
  19583. this.fogNode = null;
  19584. /**
  19585. * The current clipping context.
  19586. *
  19587. * @type {ClippingContext?}
  19588. */
  19589. this.clippingContext = null;
  19590. /**
  19591. * The generated vertex shader.
  19592. *
  19593. * @type {String?}
  19594. */
  19595. this.vertexShader = null;
  19596. /**
  19597. * The generated fragment shader.
  19598. *
  19599. * @type {String?}
  19600. */
  19601. this.fragmentShader = null;
  19602. /**
  19603. * The generated compute shader.
  19604. *
  19605. * @type {String?}
  19606. */
  19607. this.computeShader = null;
  19608. /**
  19609. * Nodes used in the primary flow of code generation.
  19610. *
  19611. * @type {Object<String,Array<Node>>}
  19612. */
  19613. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  19614. /**
  19615. * Nodes code from `.flowNodes`.
  19616. *
  19617. * @type {Object<String,String>}
  19618. */
  19619. this.flowCode = { vertex: '', fragment: '', compute: '' };
  19620. /**
  19621. * This dictionary holds the node uniforms of the builder.
  19622. * The uniforms are maintained in an array for each shader stage.
  19623. *
  19624. * @type {Object}
  19625. */
  19626. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  19627. /**
  19628. * This dictionary holds the output structs of the builder.
  19629. * The structs are maintained in an array for each shader stage.
  19630. *
  19631. * @type {Object}
  19632. */
  19633. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  19634. /**
  19635. * This dictionary holds the bindings for each shader stage.
  19636. *
  19637. * @type {Object}
  19638. */
  19639. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  19640. /**
  19641. * This dictionary maintains the binding indices per bind group.
  19642. *
  19643. * @type {Object}
  19644. */
  19645. this.bindingsIndexes = {};
  19646. /**
  19647. * Reference to the array of bind groups.
  19648. *
  19649. * @type {Array<BindGroup>?}
  19650. */
  19651. this.bindGroups = null;
  19652. /**
  19653. * This array holds the node attributes of this builder
  19654. * created via {@link AttributeNode}.
  19655. *
  19656. * @type {Array<NodeAttribute>}
  19657. */
  19658. this.attributes = [];
  19659. /**
  19660. * This array holds the node attributes of this builder
  19661. * created via {@link BufferAttributeNode}.
  19662. *
  19663. * @type {Array<NodeAttribute>}
  19664. */
  19665. this.bufferAttributes = [];
  19666. /**
  19667. * This array holds the node varyings of this builder.
  19668. *
  19669. * @type {Array<NodeVarying>}
  19670. */
  19671. this.varyings = [];
  19672. /**
  19673. * This dictionary holds the (native) node codes of this builder.
  19674. * The codes are maintained in an array for each shader stage.
  19675. *
  19676. * @type {Object<String,Array<NodeCode>>}
  19677. */
  19678. this.codes = {};
  19679. /**
  19680. * This dictionary holds the node variables of this builder.
  19681. * The variables are maintained in an array for each shader stage.
  19682. *
  19683. * @type {Object<String,Array<NodeVar>>}
  19684. */
  19685. this.vars = {};
  19686. /**
  19687. * Current code flow.
  19688. * All code generated in this stack will be stored in `.flow`.
  19689. *
  19690. * @type {{code: String}}
  19691. */
  19692. this.flow = { code: '' };
  19693. /**
  19694. * A chain of nodes.
  19695. * Used to check recursive calls in node-graph.
  19696. *
  19697. * @type {Array<Node>}
  19698. */
  19699. this.chaining = [];
  19700. /**
  19701. * The current stack.
  19702. * This reflects the current process in the code block hierarchy,
  19703. * it is useful to know if the current process is inside a conditional for example.
  19704. *
  19705. * @type {StackNode}
  19706. */
  19707. this.stack = stack();
  19708. /**
  19709. * List of stack nodes.
  19710. * The current stack hierarchy is stored in an array.
  19711. *
  19712. * @type {Array<StackNode>}
  19713. */
  19714. this.stacks = [];
  19715. /**
  19716. * A tab value. Used for shader string generation.
  19717. *
  19718. * @type {String}
  19719. * @default '\t'
  19720. */
  19721. this.tab = '\t';
  19722. /**
  19723. * Reference to the current function node.
  19724. *
  19725. * @type {FunctionNode?}
  19726. * @default null
  19727. */
  19728. this.currentFunctionNode = null;
  19729. /**
  19730. * The builder's context.
  19731. *
  19732. * @type {Object}
  19733. */
  19734. this.context = {
  19735. material: this.material
  19736. };
  19737. /**
  19738. * The builder's cache.
  19739. *
  19740. * @type {NodeCache}
  19741. */
  19742. this.cache = new NodeCache();
  19743. /**
  19744. * Since the {@link NodeBuilder#cache} might be temporarily
  19745. * overwritten by other caches, this member retains the reference
  19746. * to the builder's own cache.
  19747. *
  19748. * @type {NodeCache}
  19749. * @default this.cache
  19750. */
  19751. this.globalCache = this.cache;
  19752. this.flowsData = new WeakMap();
  19753. /**
  19754. * The current shader stage.
  19755. *
  19756. * @type {('vertex'|'fragment'|'compute'|'any')?}
  19757. */
  19758. this.shaderStage = null;
  19759. /**
  19760. * The current build stage.
  19761. *
  19762. * @type {('setup'|'analyze'|'generate')?}
  19763. */
  19764. this.buildStage = null;
  19765. /**
  19766. * Whether comparison in shader code are generated with methods or not.
  19767. *
  19768. * @type {Boolean}
  19769. * @default false
  19770. */
  19771. this.useComparisonMethod = false;
  19772. }
  19773. /**
  19774. * Returns the bind groups of the current renderer.
  19775. *
  19776. * @return {ChainMap} The cache.
  19777. */
  19778. getBindGroupsCache() {
  19779. let bindGroupsCache = rendererCache.get( this.renderer );
  19780. if ( bindGroupsCache === undefined ) {
  19781. bindGroupsCache = new ChainMap();
  19782. rendererCache.set( this.renderer, bindGroupsCache );
  19783. }
  19784. return bindGroupsCache;
  19785. }
  19786. /**
  19787. * Factory method for creating an instance of {@link RenderTarget} with the given
  19788. * dimensions and options.
  19789. *
  19790. * @param {Number} width - The width of the render target.
  19791. * @param {Number} height - The height of the render target.
  19792. * @param {Object} options - The options of the render target.
  19793. * @return {RenderTarget} The render target.
  19794. */
  19795. createRenderTarget( width, height, options ) {
  19796. return new RenderTarget( width, height, options );
  19797. }
  19798. /**
  19799. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  19800. * dimensions and options.
  19801. *
  19802. * @param {Number} size - The size of the cube render target.
  19803. * @param {Object} options - The options of the cube render target.
  19804. * @return {CubeRenderTarget} The cube render target.
  19805. */
  19806. createCubeRenderTarget( size, options ) {
  19807. return new CubeRenderTarget( size, options );
  19808. }
  19809. /**
  19810. * Factory method for creating an instance of {@link PMREMGenerator}.
  19811. *
  19812. * @return {PMREMGenerator} The PMREM generator.
  19813. */
  19814. createPMREMGenerator() {
  19815. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  19816. return new PMREMGenerator( this.renderer );
  19817. }
  19818. /**
  19819. * Whether the given node is included in the internal array of nodes or not.
  19820. *
  19821. * @param {Node} node - The node to test.
  19822. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  19823. */
  19824. includes( node ) {
  19825. return this.nodes.includes( node );
  19826. }
  19827. /**
  19828. * Returns a bind group for the given group name and binding.
  19829. *
  19830. * @private
  19831. * @param {String} groupName - The group name.
  19832. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  19833. * @return {BindGroup} The bind group
  19834. */
  19835. _getBindGroup( groupName, bindings ) {
  19836. const bindGroupsCache = this.getBindGroupsCache();
  19837. //
  19838. const bindingsArray = [];
  19839. let sharedGroup = true;
  19840. for ( const binding of bindings ) {
  19841. bindingsArray.push( binding );
  19842. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  19843. }
  19844. //
  19845. let bindGroup;
  19846. if ( sharedGroup ) {
  19847. bindGroup = bindGroupsCache.get( bindingsArray );
  19848. if ( bindGroup === undefined ) {
  19849. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19850. bindGroupsCache.set( bindingsArray, bindGroup );
  19851. }
  19852. } else {
  19853. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19854. }
  19855. return bindGroup;
  19856. }
  19857. /**
  19858. * Returns an array of node uniform groups for the given group name and shader stage.
  19859. *
  19860. * @param {String} groupName - The group name.
  19861. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  19862. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  19863. */
  19864. getBindGroupArray( groupName, shaderStage ) {
  19865. const bindings = this.bindings[ shaderStage ];
  19866. let bindGroup = bindings[ groupName ];
  19867. if ( bindGroup === undefined ) {
  19868. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  19869. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  19870. }
  19871. bindings[ groupName ] = bindGroup = [];
  19872. }
  19873. return bindGroup;
  19874. }
  19875. /**
  19876. * Returns a list bindings of all shader stages separated by groups.
  19877. *
  19878. * @return {Array<BindGroup>} The list of bindings.
  19879. */
  19880. getBindings() {
  19881. let bindingsGroups = this.bindGroups;
  19882. if ( bindingsGroups === null ) {
  19883. const groups = {};
  19884. const bindings = this.bindings;
  19885. for ( const shaderStage of shaderStages ) {
  19886. for ( const groupName in bindings[ shaderStage ] ) {
  19887. const uniforms = bindings[ shaderStage ][ groupName ];
  19888. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  19889. groupUniforms.push( ...uniforms );
  19890. }
  19891. }
  19892. bindingsGroups = [];
  19893. for ( const groupName in groups ) {
  19894. const group = groups[ groupName ];
  19895. const bindingsGroup = this._getBindGroup( groupName, group );
  19896. bindingsGroups.push( bindingsGroup );
  19897. }
  19898. this.bindGroups = bindingsGroups;
  19899. }
  19900. return bindingsGroups;
  19901. }
  19902. /**
  19903. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  19904. */
  19905. sortBindingGroups() {
  19906. const bindingsGroups = this.getBindings();
  19907. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  19908. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  19909. const bindingGroup = bindingsGroups[ i ];
  19910. this.bindingsIndexes[ bindingGroup.name ].group = i;
  19911. bindingGroup.index = i;
  19912. }
  19913. }
  19914. /**
  19915. * The builder maintains each node in a hash-based dictionary.
  19916. * This method sets the given node (value) with the given hash (key) into this dictionary.
  19917. *
  19918. * @param {Node} node - The node to add.
  19919. * @param {Number} hash - The hash of the node.
  19920. */
  19921. setHashNode( node, hash ) {
  19922. this.hashNodes[ hash ] = node;
  19923. }
  19924. /**
  19925. * Adds a node to this builder.
  19926. *
  19927. * @param {Node} node - The node to add.
  19928. */
  19929. addNode( node ) {
  19930. if ( this.nodes.includes( node ) === false ) {
  19931. this.nodes.push( node );
  19932. this.setHashNode( node, node.getHash( this ) );
  19933. }
  19934. }
  19935. /**
  19936. * It is used to add Nodes that will be used as FRAME and RENDER events,
  19937. * and need to follow a certain sequence in the calls to work correctly.
  19938. *
  19939. * @param {Node} node - The node to add.
  19940. */
  19941. addSequentialNode( node ) {
  19942. if ( this.sequentialNodes.includes( node ) === false ) {
  19943. this.sequentialNodes.push( node );
  19944. }
  19945. }
  19946. /**
  19947. * Checks the update types of nodes
  19948. */
  19949. buildUpdateNodes() {
  19950. for ( const node of this.nodes ) {
  19951. const updateType = node.getUpdateType();
  19952. if ( updateType !== NodeUpdateType.NONE ) {
  19953. this.updateNodes.push( node.getSelf() );
  19954. }
  19955. }
  19956. for ( const node of this.sequentialNodes ) {
  19957. const updateBeforeType = node.getUpdateBeforeType();
  19958. const updateAfterType = node.getUpdateAfterType();
  19959. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  19960. this.updateBeforeNodes.push( node.getSelf() );
  19961. }
  19962. if ( updateAfterType !== NodeUpdateType.NONE ) {
  19963. this.updateAfterNodes.push( node.getSelf() );
  19964. }
  19965. }
  19966. }
  19967. /**
  19968. * A reference the current node which is the
  19969. * last node in the chain of nodes.
  19970. *
  19971. * @type {Node}
  19972. */
  19973. get currentNode() {
  19974. return this.chaining[ this.chaining.length - 1 ];
  19975. }
  19976. /**
  19977. * Whether the given texture is filtered or not.
  19978. *
  19979. * @param {Texture} texture - The texture to check.
  19980. * @return {Boolean} Whether the given texture is filtered or not.
  19981. */
  19982. isFilteredTexture( texture ) {
  19983. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  19984. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  19985. }
  19986. /**
  19987. * Adds the given node to the internal node chain.
  19988. * This is used to check recursive calls in node-graph.
  19989. *
  19990. * @param {Node} node - The node to add.
  19991. */
  19992. addChain( node ) {
  19993. /*
  19994. if ( this.chaining.indexOf( node ) !== - 1 ) {
  19995. console.warn( 'Recursive node: ', node );
  19996. }
  19997. */
  19998. this.chaining.push( node );
  19999. }
  20000. /**
  20001. * Removes the given node from the internal node chain.
  20002. *
  20003. * @param {Node} node - The node to remove.
  20004. */
  20005. removeChain( node ) {
  20006. const lastChain = this.chaining.pop();
  20007. if ( lastChain !== node ) {
  20008. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  20009. }
  20010. }
  20011. /**
  20012. * Returns the native shader method name for a given generic name. E.g.
  20013. * the method name `textureDimensions` matches the WGSL name but must be
  20014. * resolved to `textureSize` in GLSL.
  20015. *
  20016. * @abstract
  20017. * @param {String} method - The method name to resolve.
  20018. * @return {String} The resolved method name.
  20019. */
  20020. getMethod( method ) {
  20021. return method;
  20022. }
  20023. /**
  20024. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  20025. *
  20026. * @param {Number} hash - The hash of the node.
  20027. * @return {Node} The found node.
  20028. */
  20029. getNodeFromHash( hash ) {
  20030. return this.hashNodes[ hash ];
  20031. }
  20032. /**
  20033. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  20034. *
  20035. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  20036. * @param {Node} node - The node to add.
  20037. * @return {Node} The node.
  20038. */
  20039. addFlow( shaderStage, node ) {
  20040. this.flowNodes[ shaderStage ].push( node );
  20041. return node;
  20042. }
  20043. /**
  20044. * Sets builder's context.
  20045. *
  20046. * @param {Object} context - The context to set.
  20047. */
  20048. setContext( context ) {
  20049. this.context = context;
  20050. }
  20051. /**
  20052. * Returns the builder's current context.
  20053. *
  20054. * @return {Object} The builder's current context.
  20055. */
  20056. getContext() {
  20057. return this.context;
  20058. }
  20059. /**
  20060. * Gets a context used in shader construction that can be shared across different materials.
  20061. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  20062. *
  20063. * @return {Object} The builder's current context without material.
  20064. */
  20065. getSharedContext() {
  20066. ({ ...this.context });
  20067. return this.context;
  20068. }
  20069. /**
  20070. * Sets builder's cache.
  20071. *
  20072. * @param {NodeCache} cache - The cache to set.
  20073. */
  20074. setCache( cache ) {
  20075. this.cache = cache;
  20076. }
  20077. /**
  20078. * Returns the builder's current cache.
  20079. *
  20080. * @return {NodeCache} The builder's current cache.
  20081. */
  20082. getCache() {
  20083. return this.cache;
  20084. }
  20085. /**
  20086. * Returns a cache for the given node.
  20087. *
  20088. * @param {Node} node - The node.
  20089. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  20090. * @return {NodeCache} The cache.
  20091. */
  20092. getCacheFromNode( node, parent = true ) {
  20093. const data = this.getDataFromNode( node );
  20094. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  20095. return data.cache;
  20096. }
  20097. /**
  20098. * Whether the requested feature is available or not.
  20099. *
  20100. * @abstract
  20101. * @param {String} name - The requested feature.
  20102. * @return {Boolean} Whether the requested feature is supported or not.
  20103. */
  20104. isAvailable( /*name*/ ) {
  20105. return false;
  20106. }
  20107. /**
  20108. * Returns the vertexIndex input variable as a native shader string.
  20109. *
  20110. * @abstract
  20111. * @return {String} The instanceIndex shader string.
  20112. */
  20113. getVertexIndex() {
  20114. console.warn( 'Abstract function.' );
  20115. }
  20116. /**
  20117. * Returns the instanceIndex input variable as a native shader string.
  20118. *
  20119. * @abstract
  20120. * @return {String} The instanceIndex shader string.
  20121. */
  20122. getInstanceIndex() {
  20123. console.warn( 'Abstract function.' );
  20124. }
  20125. /**
  20126. * Returns the drawIndex input variable as a native shader string.
  20127. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  20128. *
  20129. * @abstract
  20130. * @return {String} The drawIndex shader string.
  20131. */
  20132. getDrawIndex() {
  20133. console.warn( 'Abstract function.' );
  20134. }
  20135. /**
  20136. * Returns the frontFacing input variable as a native shader string.
  20137. *
  20138. * @abstract
  20139. * @return {String} The frontFacing shader string.
  20140. */
  20141. getFrontFacing() {
  20142. console.warn( 'Abstract function.' );
  20143. }
  20144. /**
  20145. * Returns the fragCoord input variable as a native shader string.
  20146. *
  20147. * @abstract
  20148. * @return {String} The fragCoord shader string.
  20149. */
  20150. getFragCoord() {
  20151. console.warn( 'Abstract function.' );
  20152. }
  20153. /**
  20154. * Whether to flip texture data along its vertical axis or not. WebGL needs
  20155. * this method evaluate to `true`, WebGPU to `false`.
  20156. *
  20157. * @abstract
  20158. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  20159. */
  20160. isFlipY() {
  20161. return false;
  20162. }
  20163. /**
  20164. * Calling this method increases the usage count for the given node by one.
  20165. *
  20166. * @param {Node} node - The node to increase the usage count for.
  20167. * @return {Number} The updated usage count.
  20168. */
  20169. increaseUsage( node ) {
  20170. const nodeData = this.getDataFromNode( node );
  20171. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  20172. return nodeData.usageCount;
  20173. }
  20174. /**
  20175. * Generates a texture sample shader string for the given texture data.
  20176. *
  20177. * @abstract
  20178. * @param {Texture} texture - The texture.
  20179. * @param {String} textureProperty - The texture property name.
  20180. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  20181. * @return {String} The generated shader string.
  20182. */
  20183. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  20184. console.warn( 'Abstract function.' );
  20185. }
  20186. /**
  20187. * Generates a texture LOD shader string for the given texture data.
  20188. *
  20189. * @abstract
  20190. * @param {Texture} texture - The texture.
  20191. * @param {String} textureProperty - The texture property name.
  20192. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  20193. * @param {String} levelSnippet - Snippet defining the mip level.
  20194. * @return {String} The generated shader string.
  20195. */
  20196. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  20197. console.warn( 'Abstract function.' );
  20198. }
  20199. /**
  20200. * Generates the shader string for the given type and value.
  20201. *
  20202. * @param {String} type - The type.
  20203. * @param {Any?} [value=null] - The value.
  20204. * @return {String} The generated value as a shader string.
  20205. */
  20206. generateConst( type, value = null ) {
  20207. if ( value === null ) {
  20208. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  20209. else if ( type === 'bool' ) value = false;
  20210. else if ( type === 'color' ) value = new Color();
  20211. else if ( type === 'vec2' ) value = new Vector2();
  20212. else if ( type === 'vec3' ) value = new Vector3();
  20213. else if ( type === 'vec4' ) value = new Vector4();
  20214. }
  20215. if ( type === 'float' ) return toFloat( value );
  20216. if ( type === 'int' ) return `${ Math.round( value ) }`;
  20217. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  20218. if ( type === 'bool' ) return value ? 'true' : 'false';
  20219. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  20220. const typeLength = this.getTypeLength( type );
  20221. const componentType = this.getComponentType( type );
  20222. const generateConst = value => this.generateConst( componentType, value );
  20223. if ( typeLength === 2 ) {
  20224. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  20225. } else if ( typeLength === 3 ) {
  20226. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  20227. } else if ( typeLength === 4 ) {
  20228. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  20229. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  20230. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  20231. } else if ( typeLength > 4 ) {
  20232. return `${ this.getType( type ) }()`;
  20233. }
  20234. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  20235. }
  20236. /**
  20237. * It might be necessary to convert certain data types to different ones
  20238. * so this method can be used to hide the conversion.
  20239. *
  20240. * @param {String} type - The type.
  20241. * @return {String} The updated type.
  20242. */
  20243. getType( type ) {
  20244. if ( type === 'color' ) return 'vec3';
  20245. return type;
  20246. }
  20247. /**
  20248. * Whether the given attribute name is defined in the geometry or not.
  20249. *
  20250. * @param {String} name - The attribute name.
  20251. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  20252. */
  20253. hasGeometryAttribute( name ) {
  20254. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  20255. }
  20256. /**
  20257. * Returns a node attribute for the given name and type.
  20258. *
  20259. * @param {String} name - The attribute's name.
  20260. * @param {String} type - The attribute's type.
  20261. * @return {NodeAttribute} The node attribute.
  20262. */
  20263. getAttribute( name, type ) {
  20264. const attributes = this.attributes;
  20265. // find attribute
  20266. for ( const attribute of attributes ) {
  20267. if ( attribute.name === name ) {
  20268. return attribute;
  20269. }
  20270. }
  20271. // create a new if no exist
  20272. const attribute = new NodeAttribute( name, type );
  20273. attributes.push( attribute );
  20274. return attribute;
  20275. }
  20276. /**
  20277. * Returns for the given node and shader stage the property name for the shader.
  20278. *
  20279. * @param {Node} node - The node.
  20280. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20281. * @return {String} The property name.
  20282. */
  20283. getPropertyName( node/*, shaderStage*/ ) {
  20284. return node.name;
  20285. }
  20286. /**
  20287. * Whether the given type is a vector type or not.
  20288. *
  20289. * @param {String} type - The type to check.
  20290. * @return {Boolean} Whether the given type is a vector type or not.
  20291. */
  20292. isVector( type ) {
  20293. return /vec\d/.test( type );
  20294. }
  20295. /**
  20296. * Whether the given type is a matrix type or not.
  20297. *
  20298. * @param {String} type - The type to check.
  20299. * @return {Boolean} Whether the given type is a matrix type or not.
  20300. */
  20301. isMatrix( type ) {
  20302. return /mat\d/.test( type );
  20303. }
  20304. /**
  20305. * Whether the given type is a reference type or not.
  20306. *
  20307. * @param {String} type - The type to check.
  20308. * @return {Boolean} Whether the given type is a reference type or not.
  20309. */
  20310. isReference( type ) {
  20311. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  20312. }
  20313. /**
  20314. * Whether the given texture needs a conversion to working color space.
  20315. *
  20316. * @abstract
  20317. * @param {Texture} texture - The texture to check.
  20318. * @return {Boolean} Whether a color space conversion is required or not.
  20319. */
  20320. needsToWorkingColorSpace( /*texture*/ ) {
  20321. return false;
  20322. }
  20323. /**
  20324. * Returns the component type of a given texture.
  20325. *
  20326. * @param {Texture} texture - The texture.
  20327. * @return {String} The component type.
  20328. */
  20329. getComponentTypeFromTexture( texture ) {
  20330. const type = texture.type;
  20331. if ( texture.isDataTexture ) {
  20332. if ( type === IntType ) return 'int';
  20333. if ( type === UnsignedIntType ) return 'uint';
  20334. }
  20335. return 'float';
  20336. }
  20337. /**
  20338. * Returns the element type for a given type.
  20339. *
  20340. * @param {String} type - The type.
  20341. * @return {String} The element type.
  20342. */
  20343. getElementType( type ) {
  20344. if ( type === 'mat2' ) return 'vec2';
  20345. if ( type === 'mat3' ) return 'vec3';
  20346. if ( type === 'mat4' ) return 'vec4';
  20347. return this.getComponentType( type );
  20348. }
  20349. /**
  20350. * Returns the component type for a given type.
  20351. *
  20352. * @param {String} type - The type.
  20353. * @return {String} The component type.
  20354. */
  20355. getComponentType( type ) {
  20356. type = this.getVectorType( type );
  20357. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  20358. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  20359. if ( componentType === null ) return null;
  20360. if ( componentType[ 1 ] === 'b' ) return 'bool';
  20361. if ( componentType[ 1 ] === 'i' ) return 'int';
  20362. if ( componentType[ 1 ] === 'u' ) return 'uint';
  20363. return 'float';
  20364. }
  20365. /**
  20366. * Returns the vector type for a given type.
  20367. *
  20368. * @param {String} type - The type.
  20369. * @return {String} The vector type.
  20370. */
  20371. getVectorType( type ) {
  20372. if ( type === 'color' ) return 'vec3';
  20373. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  20374. return type;
  20375. }
  20376. /**
  20377. * Returns the data type for the given the length and component type.
  20378. *
  20379. * @param {Number} length - The length.
  20380. * @param {String} [componentType='float'] - The component type.
  20381. * @return {String} The type.
  20382. */
  20383. getTypeFromLength( length, componentType = 'float' ) {
  20384. if ( length === 1 ) return componentType;
  20385. const baseType = getTypeFromLength( length );
  20386. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  20387. return prefix + baseType;
  20388. }
  20389. /**
  20390. * Returns the type for a given typed array.
  20391. *
  20392. * @param {TypedArray} array - The typed array.
  20393. * @return {String} The type.
  20394. */
  20395. getTypeFromArray( array ) {
  20396. return typeFromArray.get( array.constructor );
  20397. }
  20398. /**
  20399. * Returns the type for a given buffer attribute.
  20400. *
  20401. * @param {BufferAttribute} attribute - The buffer attribute.
  20402. * @return {String} The type.
  20403. */
  20404. getTypeFromAttribute( attribute ) {
  20405. let dataAttribute = attribute;
  20406. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  20407. const array = dataAttribute.array;
  20408. const itemSize = attribute.itemSize;
  20409. const normalized = attribute.normalized;
  20410. let arrayType;
  20411. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  20412. arrayType = this.getTypeFromArray( array );
  20413. }
  20414. return this.getTypeFromLength( itemSize, arrayType );
  20415. }
  20416. /**
  20417. * Returns the length for the given data type.
  20418. *
  20419. * @param {String} type - The data type.
  20420. * @return {Number} The length.
  20421. */
  20422. getTypeLength( type ) {
  20423. const vecType = this.getVectorType( type );
  20424. const vecNum = /vec([2-4])/.exec( vecType );
  20425. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  20426. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  20427. if ( /mat2/.test( type ) === true ) return 4;
  20428. if ( /mat3/.test( type ) === true ) return 9;
  20429. if ( /mat4/.test( type ) === true ) return 16;
  20430. return 0;
  20431. }
  20432. /**
  20433. * Returns the vector type for a given matrix type.
  20434. *
  20435. * @param {String} type - The matrix type.
  20436. * @return {String} The vector type.
  20437. */
  20438. getVectorFromMatrix( type ) {
  20439. return type.replace( 'mat', 'vec' );
  20440. }
  20441. /**
  20442. * For a given type this method changes the component type to the
  20443. * given value. E.g. `vec4` should be changed to the new component type
  20444. * `uint` which results in `uvec4`.
  20445. *
  20446. * @param {String} type - The type.
  20447. * @param {String} newComponentType - The new component type.
  20448. * @return {String} The new type.
  20449. */
  20450. changeComponentType( type, newComponentType ) {
  20451. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  20452. }
  20453. /**
  20454. * Returns the integer type pendant for the given type.
  20455. *
  20456. * @param {String} type - The type.
  20457. * @return {String} The integer type.
  20458. */
  20459. getIntegerType( type ) {
  20460. const componentType = this.getComponentType( type );
  20461. if ( componentType === 'int' || componentType === 'uint' ) return type;
  20462. return this.changeComponentType( type, 'int' );
  20463. }
  20464. /**
  20465. * Adds a stack node to the internal stack.
  20466. *
  20467. * @return {StackNode} The added stack node.
  20468. */
  20469. addStack() {
  20470. this.stack = stack( this.stack );
  20471. this.stacks.push( getCurrentStack() || this.stack );
  20472. setCurrentStack( this.stack );
  20473. return this.stack;
  20474. }
  20475. /**
  20476. * Removes the last stack node from the internal stack.
  20477. *
  20478. * @return {StackNode} The removed stack node.
  20479. */
  20480. removeStack() {
  20481. const lastStack = this.stack;
  20482. this.stack = lastStack.parent;
  20483. setCurrentStack( this.stacks.pop() );
  20484. return lastStack;
  20485. }
  20486. /**
  20487. * The builder maintains (cached) data for each node during the building process. This method
  20488. * can be used to get these data for a specific shader stage and cache.
  20489. *
  20490. * @param {Node} node - The node to get the data for.
  20491. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  20492. * @param {NodeCache?} cache - An optional cache.
  20493. * @return {Object} The node data.
  20494. */
  20495. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  20496. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  20497. let nodeData = cache.getData( node );
  20498. if ( nodeData === undefined ) {
  20499. nodeData = {};
  20500. cache.setData( node, nodeData );
  20501. }
  20502. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  20503. return nodeData[ shaderStage ];
  20504. }
  20505. /**
  20506. * Returns the properties for the given node and shader stage.
  20507. *
  20508. * @param {Node} node - The node to get the properties for.
  20509. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  20510. * @return {Object} The node properties.
  20511. */
  20512. getNodeProperties( node, shaderStage = 'any' ) {
  20513. const nodeData = this.getDataFromNode( node, shaderStage );
  20514. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  20515. }
  20516. /**
  20517. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  20518. *
  20519. * @param {BufferAttributeNode} node - The buffer attribute node.
  20520. * @param {String} type - The node type.
  20521. * @return {NodeAttribute} The node attribute.
  20522. */
  20523. getBufferAttributeFromNode( node, type ) {
  20524. const nodeData = this.getDataFromNode( node );
  20525. let bufferAttribute = nodeData.bufferAttribute;
  20526. if ( bufferAttribute === undefined ) {
  20527. const index = this.uniforms.index ++;
  20528. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  20529. this.bufferAttributes.push( bufferAttribute );
  20530. nodeData.bufferAttribute = bufferAttribute;
  20531. }
  20532. return bufferAttribute;
  20533. }
  20534. /**
  20535. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  20536. *
  20537. * @param {OutputStructNode} node - The output struct node.
  20538. * @param {Array<String>} types - The output struct types.
  20539. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  20540. * @return {StructTypeNode} The struct type attribute.
  20541. */
  20542. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  20543. const nodeData = this.getDataFromNode( node, shaderStage );
  20544. let structType = nodeData.structType;
  20545. if ( structType === undefined ) {
  20546. const index = this.structs.index ++;
  20547. structType = new StructTypeNode( 'StructType' + index, types );
  20548. this.structs[ shaderStage ].push( structType );
  20549. nodeData.structType = structType;
  20550. }
  20551. return structType;
  20552. }
  20553. /**
  20554. * Returns an instance of {@link NodeUniform} for the given uniform node.
  20555. *
  20556. * @param {UniformNode} node - The uniform node.
  20557. * @param {String} type - The uniform type.
  20558. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  20559. * @param {String?} name - The name of the uniform.
  20560. * @return {NodeUniform} The node uniform.
  20561. */
  20562. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  20563. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  20564. let nodeUniform = nodeData.uniform;
  20565. if ( nodeUniform === undefined ) {
  20566. const index = this.uniforms.index ++;
  20567. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  20568. this.uniforms[ shaderStage ].push( nodeUniform );
  20569. nodeData.uniform = nodeUniform;
  20570. }
  20571. return nodeUniform;
  20572. }
  20573. /**
  20574. * Returns an instance of {@link NodeVar} for the given variable node.
  20575. *
  20576. * @param {VarNode} node - The variable node.
  20577. * @param {String?} name - The variable's name.
  20578. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  20579. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  20580. * @return {NodeVar} The node variable.
  20581. */
  20582. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  20583. const nodeData = this.getDataFromNode( node, shaderStage );
  20584. let nodeVar = nodeData.variable;
  20585. if ( nodeVar === undefined ) {
  20586. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  20587. if ( name === null ) name = 'nodeVar' + vars.length;
  20588. nodeVar = new NodeVar( name, type );
  20589. vars.push( nodeVar );
  20590. nodeData.variable = nodeVar;
  20591. }
  20592. return nodeVar;
  20593. }
  20594. /**
  20595. * Returns an instance of {@link NodeVarying} for the given varying node.
  20596. *
  20597. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  20598. * @param {String?} name - The varying's name.
  20599. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  20600. * @return {NodeVar} The node varying.
  20601. */
  20602. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  20603. const nodeData = this.getDataFromNode( node, 'any' );
  20604. let nodeVarying = nodeData.varying;
  20605. if ( nodeVarying === undefined ) {
  20606. const varyings = this.varyings;
  20607. const index = varyings.length;
  20608. if ( name === null ) name = 'nodeVarying' + index;
  20609. nodeVarying = new NodeVarying( name, type );
  20610. varyings.push( nodeVarying );
  20611. nodeData.varying = nodeVarying;
  20612. }
  20613. return nodeVarying;
  20614. }
  20615. /**
  20616. * Returns an instance of {@link NodeCode} for the given code node.
  20617. *
  20618. * @param {CodeNode} node - The code node.
  20619. * @param {String} type - The node type.
  20620. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  20621. * @return {NodeCode} The node code.
  20622. */
  20623. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  20624. const nodeData = this.getDataFromNode( node );
  20625. let nodeCode = nodeData.code;
  20626. if ( nodeCode === undefined ) {
  20627. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  20628. const index = codes.length;
  20629. nodeCode = new NodeCode( 'nodeCode' + index, type );
  20630. codes.push( nodeCode );
  20631. nodeData.code = nodeCode;
  20632. }
  20633. return nodeCode;
  20634. }
  20635. /**
  20636. * Adds a code flow based on the code-block hierarchy.
  20637. * This is used so that code-blocks like If,Else create their variables locally if the Node
  20638. * is only used inside one of these conditionals in the current shader stage.
  20639. *
  20640. * @param {Node} node - The node to add.
  20641. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  20642. */
  20643. addFlowCodeHierarchy( node, nodeBlock ) {
  20644. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  20645. let needsFlowCode = true;
  20646. let nodeBlockHierarchy = nodeBlock;
  20647. while ( nodeBlockHierarchy ) {
  20648. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  20649. needsFlowCode = false;
  20650. break;
  20651. }
  20652. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  20653. }
  20654. if ( needsFlowCode ) {
  20655. for ( const flowCode of flowCodes ) {
  20656. this.addLineFlowCode( flowCode );
  20657. }
  20658. }
  20659. }
  20660. /**
  20661. * Add a inline-code to the current flow code-block.
  20662. *
  20663. * @param {Node} node - The node to add.
  20664. * @param {String} code - The code to add.
  20665. * @param {Node} nodeBlock - Current ConditionalNode
  20666. */
  20667. addLineFlowCodeBlock( node, code, nodeBlock ) {
  20668. const nodeData = this.getDataFromNode( node );
  20669. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  20670. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  20671. flowCodes.push( code );
  20672. codeBlock.set( nodeBlock, true );
  20673. }
  20674. /**
  20675. * Add a inline-code to the current flow.
  20676. *
  20677. * @param {String} code - The code to add.
  20678. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  20679. * @return {NodeBuilder} A reference to this node builder.
  20680. */
  20681. addLineFlowCode( code, node = null ) {
  20682. if ( code === '' ) return this;
  20683. if ( node !== null && this.context.nodeBlock ) {
  20684. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  20685. }
  20686. code = this.tab + code;
  20687. if ( ! /;\s*$/.test( code ) ) {
  20688. code = code + ';\n';
  20689. }
  20690. this.flow.code += code;
  20691. return this;
  20692. }
  20693. /**
  20694. * Adds a code to the current code flow.
  20695. *
  20696. * @param {String} code - Shader code.
  20697. * @return {NodeBuilder} A reference to this node builder.
  20698. */
  20699. addFlowCode( code ) {
  20700. this.flow.code += code;
  20701. return this;
  20702. }
  20703. /**
  20704. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  20705. * Typically used in codes with If,Else.
  20706. *
  20707. * @return {NodeBuilder} A reference to this node builder.
  20708. */
  20709. addFlowTab() {
  20710. this.tab += '\t';
  20711. return this;
  20712. }
  20713. /**
  20714. * Removes a tab.
  20715. *
  20716. * @return {NodeBuilder} A reference to this node builder.
  20717. */
  20718. removeFlowTab() {
  20719. this.tab = this.tab.slice( 0, - 1 );
  20720. return this;
  20721. }
  20722. /**
  20723. * Gets the current flow data based on a Node.
  20724. *
  20725. * @param {Node} node - Node that the flow was started.
  20726. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20727. * @return {Object} The flow data.
  20728. */
  20729. getFlowData( node/*, shaderStage*/ ) {
  20730. return this.flowsData.get( node );
  20731. }
  20732. /**
  20733. * Executes the node flow based on a root node to generate the final shader code.
  20734. *
  20735. * @param {Node} node - The node to execute.
  20736. * @return {Object} The code flow.
  20737. */
  20738. flowNode( node ) {
  20739. const output = node.getNodeType( this );
  20740. const flowData = this.flowChildNode( node, output );
  20741. this.flowsData.set( node, flowData );
  20742. return flowData;
  20743. }
  20744. /**
  20745. * Returns the native shader operator name for a given generic name.
  20746. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20747. *
  20748. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  20749. * @return {FunctionNode} The build function node.
  20750. */
  20751. buildFunctionNode( shaderNode ) {
  20752. const fn = new FunctionNode();
  20753. const previous = this.currentFunctionNode;
  20754. this.currentFunctionNode = fn;
  20755. fn.code = this.buildFunctionCode( shaderNode );
  20756. this.currentFunctionNode = previous;
  20757. return fn;
  20758. }
  20759. /**
  20760. * Generates a code flow based on a TSL function: Fn().
  20761. *
  20762. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  20763. * @return {Object}
  20764. */
  20765. flowShaderNode( shaderNode ) {
  20766. const layout = shaderNode.layout;
  20767. const inputs = {
  20768. [ Symbol.iterator ]() {
  20769. let index = 0;
  20770. const values = Object.values( this );
  20771. return {
  20772. next: () => ( {
  20773. value: values[ index ],
  20774. done: index ++ >= values.length
  20775. } )
  20776. };
  20777. }
  20778. };
  20779. for ( const input of layout.inputs ) {
  20780. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  20781. }
  20782. //
  20783. shaderNode.layout = null;
  20784. const callNode = shaderNode.call( inputs );
  20785. const flowData = this.flowStagesNode( callNode, layout.type );
  20786. shaderNode.layout = layout;
  20787. return flowData;
  20788. }
  20789. /**
  20790. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  20791. *
  20792. * @param {Node} node - The node to execute.
  20793. * @param {String?} output - Expected output type. For example 'vec3'.
  20794. * @return {Object}
  20795. */
  20796. flowStagesNode( node, output = null ) {
  20797. const previousFlow = this.flow;
  20798. const previousVars = this.vars;
  20799. const previousCache = this.cache;
  20800. const previousBuildStage = this.buildStage;
  20801. const previousStack = this.stack;
  20802. const flow = {
  20803. code: ''
  20804. };
  20805. this.flow = flow;
  20806. this.vars = {};
  20807. this.cache = new NodeCache();
  20808. this.stack = stack();
  20809. for ( const buildStage of defaultBuildStages ) {
  20810. this.setBuildStage( buildStage );
  20811. flow.result = node.build( this, output );
  20812. }
  20813. flow.vars = this.getVars( this.shaderStage );
  20814. this.flow = previousFlow;
  20815. this.vars = previousVars;
  20816. this.cache = previousCache;
  20817. this.stack = previousStack;
  20818. this.setBuildStage( previousBuildStage );
  20819. return flow;
  20820. }
  20821. /**
  20822. * Returns the native shader operator name for a given generic name.
  20823. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20824. *
  20825. * @abstract
  20826. * @param {String} op - The operator name to resolve.
  20827. * @return {String} The resolved operator name.
  20828. */
  20829. getFunctionOperator( /* op */ ) {
  20830. return null;
  20831. }
  20832. /**
  20833. * Generates a code flow based on a child Node.
  20834. *
  20835. * @param {Node} node - The node to execute.
  20836. * @param {String?} output - Expected output type. For example 'vec3'.
  20837. * @return {Object} The code flow.
  20838. */
  20839. flowChildNode( node, output = null ) {
  20840. const previousFlow = this.flow;
  20841. const flow = {
  20842. code: ''
  20843. };
  20844. this.flow = flow;
  20845. flow.result = node.build( this, output );
  20846. this.flow = previousFlow;
  20847. return flow;
  20848. }
  20849. /**
  20850. * Executes a flow of code in a different stage.
  20851. *
  20852. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  20853. * return the value in fragment-stage even if it is being executed in an input fragment.
  20854. *
  20855. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20856. * @param {Node} node - The node to execute.
  20857. * @param {String?} output - Expected output type. For example 'vec3'.
  20858. * @param {String?} propertyName - The property name to assign the result.
  20859. * @return {Object}
  20860. */
  20861. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  20862. const previousShaderStage = this.shaderStage;
  20863. this.setShaderStage( shaderStage );
  20864. const flowData = this.flowChildNode( node, output );
  20865. if ( propertyName !== null ) {
  20866. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  20867. }
  20868. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  20869. this.setShaderStage( previousShaderStage );
  20870. return flowData;
  20871. }
  20872. /**
  20873. * Returns an array holding all node attributes of this node builder.
  20874. *
  20875. * @return {Array<NodeAttribute>} The node attributes of this builder.
  20876. */
  20877. getAttributesArray() {
  20878. return this.attributes.concat( this.bufferAttributes );
  20879. }
  20880. /**
  20881. * Returns the attribute definitions as a shader string for the given shader stage.
  20882. *
  20883. * @abstract
  20884. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20885. * @return {String} The attribute code section.
  20886. */
  20887. getAttributes( /*shaderStage*/ ) {
  20888. console.warn( 'Abstract function.' );
  20889. }
  20890. /**
  20891. * Returns the varying definitions as a shader string for the given shader stage.
  20892. *
  20893. * @abstract
  20894. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20895. * @return {String} The varying code section.
  20896. */
  20897. getVaryings( /*shaderStage*/ ) {
  20898. console.warn( 'Abstract function.' );
  20899. }
  20900. /**
  20901. * Returns a single variable definition as a shader string for the given variable type and name.
  20902. *
  20903. * @param {String} type - The variable's type.
  20904. * @param {String} name - The variable's name.
  20905. * @return {String} The shader string.
  20906. */
  20907. getVar( type, name ) {
  20908. return `${ this.getType( type ) } ${ name }`;
  20909. }
  20910. /**
  20911. * Returns the variable definitions as a shader string for the given shader stage.
  20912. *
  20913. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20914. * @return {String} The variable code section.
  20915. */
  20916. getVars( shaderStage ) {
  20917. let snippet = '';
  20918. const vars = this.vars[ shaderStage ];
  20919. if ( vars !== undefined ) {
  20920. for ( const variable of vars ) {
  20921. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  20922. }
  20923. }
  20924. return snippet;
  20925. }
  20926. /**
  20927. * Returns the uniform definitions as a shader string for the given shader stage.
  20928. *
  20929. * @abstract
  20930. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20931. * @return {String} The uniform code section.
  20932. */
  20933. getUniforms( /*shaderStage*/ ) {
  20934. console.warn( 'Abstract function.' );
  20935. }
  20936. /**
  20937. * Returns the native code definitions as a shader string for the given shader stage.
  20938. *
  20939. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20940. * @return {String} The native code section.
  20941. */
  20942. getCodes( shaderStage ) {
  20943. const codes = this.codes[ shaderStage ];
  20944. let code = '';
  20945. if ( codes !== undefined ) {
  20946. for ( const nodeCode of codes ) {
  20947. code += nodeCode.code + '\n';
  20948. }
  20949. }
  20950. return code;
  20951. }
  20952. /**
  20953. * Returns the hash of this node builder.
  20954. *
  20955. * @return {String} The hash.
  20956. */
  20957. getHash() {
  20958. return this.vertexShader + this.fragmentShader + this.computeShader;
  20959. }
  20960. /**
  20961. * Sets the current shader stage.
  20962. *
  20963. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  20964. */
  20965. setShaderStage( shaderStage ) {
  20966. this.shaderStage = shaderStage;
  20967. }
  20968. /**
  20969. * Returns the current shader stage.
  20970. *
  20971. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  20972. */
  20973. getShaderStage() {
  20974. return this.shaderStage;
  20975. }
  20976. /**
  20977. * Sets the current build stage.
  20978. *
  20979. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  20980. */
  20981. setBuildStage( buildStage ) {
  20982. this.buildStage = buildStage;
  20983. }
  20984. /**
  20985. * Returns the current build stage.
  20986. *
  20987. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  20988. */
  20989. getBuildStage() {
  20990. return this.buildStage;
  20991. }
  20992. /**
  20993. * Controls the code build of the shader stages.
  20994. *
  20995. * @abstract
  20996. */
  20997. buildCode() {
  20998. console.warn( 'Abstract function.' );
  20999. }
  21000. /**
  21001. * Central build method which controls the build for the given object.
  21002. *
  21003. * @return {NodeBuilder} A reference to this node builder.
  21004. */
  21005. build() {
  21006. const { object, material, renderer } = this;
  21007. if ( material !== null ) {
  21008. let nodeMaterial = renderer.library.fromMaterial( material );
  21009. if ( nodeMaterial === null ) {
  21010. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  21011. nodeMaterial = new NodeMaterial();
  21012. }
  21013. nodeMaterial.build( this );
  21014. } else {
  21015. this.addFlow( 'compute', object );
  21016. }
  21017. // setup() -> stage 1: create possible new nodes and returns an output reference node
  21018. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  21019. // generate() -> stage 3: generate shader
  21020. for ( const buildStage of defaultBuildStages ) {
  21021. this.setBuildStage( buildStage );
  21022. if ( this.context.vertex && this.context.vertex.isNode ) {
  21023. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  21024. }
  21025. for ( const shaderStage of shaderStages ) {
  21026. this.setShaderStage( shaderStage );
  21027. const flowNodes = this.flowNodes[ shaderStage ];
  21028. for ( const node of flowNodes ) {
  21029. if ( buildStage === 'generate' ) {
  21030. this.flowNode( node );
  21031. } else {
  21032. node.build( this );
  21033. }
  21034. }
  21035. }
  21036. }
  21037. this.setBuildStage( null );
  21038. this.setShaderStage( null );
  21039. // stage 4: build code for a specific output
  21040. this.buildCode();
  21041. this.buildUpdateNodes();
  21042. return this;
  21043. }
  21044. /**
  21045. * Returns a uniform representation which is later used for UBO generation and rendering.
  21046. *
  21047. * @param {NodeUniform} uniformNode - The uniform node.
  21048. * @param {String} type - The requested type.
  21049. * @return {Uniform} The uniform.
  21050. */
  21051. getNodeUniform( uniformNode, type ) {
  21052. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  21053. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  21054. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  21055. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  21056. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  21057. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  21058. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  21059. throw new Error( `Uniform "${type}" not declared.` );
  21060. }
  21061. /**
  21062. * Formats the given shader snippet from a given type into another one. E.g.
  21063. * this method might be used to convert a simple float string `"1.0"` into a
  21064. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  21065. *
  21066. * @param {String} snippet - The shader snippet.
  21067. * @param {String} fromType - The source type.
  21068. * @param {String} toType - The target type.
  21069. * @return {String} The updated shader string.
  21070. */
  21071. format( snippet, fromType, toType ) {
  21072. fromType = this.getVectorType( fromType );
  21073. toType = this.getVectorType( toType );
  21074. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  21075. return snippet;
  21076. }
  21077. const fromTypeLength = this.getTypeLength( fromType );
  21078. const toTypeLength = this.getTypeLength( toType );
  21079. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  21080. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  21081. }
  21082. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  21083. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  21084. }
  21085. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  21086. // @TODO: ignore for now
  21087. return snippet;
  21088. }
  21089. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  21090. // @TODO: ignore for now
  21091. return snippet;
  21092. }
  21093. if ( fromTypeLength === toTypeLength ) {
  21094. return `${ this.getType( toType ) }( ${ snippet } )`;
  21095. }
  21096. if ( fromTypeLength > toTypeLength ) {
  21097. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  21098. }
  21099. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  21100. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  21101. }
  21102. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  21103. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  21104. }
  21105. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  21106. // convert a number value to vector type, e.g:
  21107. // vec3( 1u ) -> vec3( float( 1u ) )
  21108. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  21109. }
  21110. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  21111. }
  21112. /**
  21113. * Returns a signature with the engine's current revision.
  21114. *
  21115. * @return {String} The signature.
  21116. */
  21117. getSignature() {
  21118. return `// Three.js r${ REVISION } - Node System\n`;
  21119. }
  21120. // deprecated
  21121. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  21122. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  21123. }
  21124. }
  21125. /**
  21126. * Management class for updating nodes. The module tracks metrics like
  21127. * the elapsed time, delta time, the render and frame ID to correctly
  21128. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  21129. * and {@link Node#updateAfter} depending on the node's configuration.
  21130. */
  21131. class NodeFrame {
  21132. /**
  21133. * Constructs a new node fame.
  21134. */
  21135. constructor() {
  21136. /**
  21137. * The elapsed time in seconds.
  21138. *
  21139. * @type {Number}
  21140. * @default 0
  21141. */
  21142. this.time = 0;
  21143. /**
  21144. * The delta time in seconds.
  21145. *
  21146. * @type {Number}
  21147. * @default 0
  21148. */
  21149. this.deltaTime = 0;
  21150. /**
  21151. * The frame ID.
  21152. *
  21153. * @type {Number}
  21154. * @default 0
  21155. */
  21156. this.frameId = 0;
  21157. /**
  21158. * The render ID.
  21159. *
  21160. * @type {Number}
  21161. * @default 0
  21162. */
  21163. this.renderId = 0;
  21164. /**
  21165. * Used to control the {@link Node#update} call.
  21166. *
  21167. * @type {WeakMap<Node, Object>}
  21168. */
  21169. this.updateMap = new WeakMap();
  21170. /**
  21171. * Used to control the {@link Node#updateBefore} call.
  21172. *
  21173. * @type {WeakMap<Node, Object>}
  21174. */
  21175. this.updateBeforeMap = new WeakMap();
  21176. /**
  21177. * Used to control the {@link Node#updateAfter} call.
  21178. *
  21179. * @type {WeakMap<Node, Object>}
  21180. */
  21181. this.updateAfterMap = new WeakMap();
  21182. /**
  21183. * A reference to the current renderer.
  21184. *
  21185. * @type {Renderer?}
  21186. * @default null
  21187. */
  21188. this.renderer = null;
  21189. /**
  21190. * A reference to the current material.
  21191. *
  21192. * @type {Material?}
  21193. * @default null
  21194. */
  21195. this.material = null;
  21196. /**
  21197. * A reference to the current camera.
  21198. *
  21199. * @type {Camera?}
  21200. * @default null
  21201. */
  21202. this.camera = null;
  21203. /**
  21204. * A reference to the current 3D object.
  21205. *
  21206. * @type {Object3D?}
  21207. * @default null
  21208. */
  21209. this.object = null;
  21210. /**
  21211. * A reference to the current scene.
  21212. *
  21213. * @type {Scene?}
  21214. * @default null
  21215. */
  21216. this.scene = null;
  21217. }
  21218. /**
  21219. * Returns a dictionary for a given node and update map which
  21220. * is used to correctly call node update methods per frame or render.
  21221. *
  21222. * @private
  21223. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  21224. * @param {Node} nodeRef - The reference to the current node.
  21225. * @return {Object<String,WeakMap>} The dictionary.
  21226. */
  21227. _getMaps( referenceMap, nodeRef ) {
  21228. let maps = referenceMap.get( nodeRef );
  21229. if ( maps === undefined ) {
  21230. maps = {
  21231. renderMap: new WeakMap(),
  21232. frameMap: new WeakMap()
  21233. };
  21234. referenceMap.set( nodeRef, maps );
  21235. }
  21236. return maps;
  21237. }
  21238. /**
  21239. * This method executes the {@link Node#updateBefore} for the given node.
  21240. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  21241. * is only executed once per frame, render or object depending on the update
  21242. * type.
  21243. *
  21244. * @param {Node} node - The node that should be updated.
  21245. */
  21246. updateBeforeNode( node ) {
  21247. const updateType = node.getUpdateBeforeType();
  21248. const reference = node.updateReference( this );
  21249. if ( updateType === NodeUpdateType.FRAME ) {
  21250. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  21251. if ( frameMap.get( reference ) !== this.frameId ) {
  21252. if ( node.updateBefore( this ) !== false ) {
  21253. frameMap.set( reference, this.frameId );
  21254. }
  21255. }
  21256. } else if ( updateType === NodeUpdateType.RENDER ) {
  21257. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  21258. if ( renderMap.get( reference ) !== this.renderId ) {
  21259. if ( node.updateBefore( this ) !== false ) {
  21260. renderMap.set( reference, this.renderId );
  21261. }
  21262. }
  21263. } else if ( updateType === NodeUpdateType.OBJECT ) {
  21264. node.updateBefore( this );
  21265. }
  21266. }
  21267. /**
  21268. * This method executes the {@link Node#updateAfter} for the given node.
  21269. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  21270. * is only executed once per frame, render or object depending on the update
  21271. * type.
  21272. *
  21273. * @param {Node} node - The node that should be updated.
  21274. */
  21275. updateAfterNode( node ) {
  21276. const updateType = node.getUpdateAfterType();
  21277. const reference = node.updateReference( this );
  21278. if ( updateType === NodeUpdateType.FRAME ) {
  21279. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  21280. if ( frameMap.get( reference ) !== this.frameId ) {
  21281. if ( node.updateAfter( this ) !== false ) {
  21282. frameMap.set( reference, this.frameId );
  21283. }
  21284. }
  21285. } else if ( updateType === NodeUpdateType.RENDER ) {
  21286. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  21287. if ( renderMap.get( reference ) !== this.renderId ) {
  21288. if ( node.updateAfter( this ) !== false ) {
  21289. renderMap.set( reference, this.renderId );
  21290. }
  21291. }
  21292. } else if ( updateType === NodeUpdateType.OBJECT ) {
  21293. node.updateAfter( this );
  21294. }
  21295. }
  21296. /**
  21297. * This method executes the {@link Node#update} for the given node.
  21298. * It makes sure {@link Node#updateType} is honored meaning the update
  21299. * is only executed once per frame, render or object depending on the update
  21300. * type.
  21301. *
  21302. * @param {Node} node - The node that should be updated.
  21303. */
  21304. updateNode( node ) {
  21305. const updateType = node.getUpdateType();
  21306. const reference = node.updateReference( this );
  21307. if ( updateType === NodeUpdateType.FRAME ) {
  21308. const { frameMap } = this._getMaps( this.updateMap, reference );
  21309. if ( frameMap.get( reference ) !== this.frameId ) {
  21310. if ( node.update( this ) !== false ) {
  21311. frameMap.set( reference, this.frameId );
  21312. }
  21313. }
  21314. } else if ( updateType === NodeUpdateType.RENDER ) {
  21315. const { renderMap } = this._getMaps( this.updateMap, reference );
  21316. if ( renderMap.get( reference ) !== this.renderId ) {
  21317. if ( node.update( this ) !== false ) {
  21318. renderMap.set( reference, this.renderId );
  21319. }
  21320. }
  21321. } else if ( updateType === NodeUpdateType.OBJECT ) {
  21322. node.update( this );
  21323. }
  21324. }
  21325. /**
  21326. * Updates the internal state of the node frame. This method is
  21327. * called by the renderer in its internal animation loop.
  21328. */
  21329. update() {
  21330. this.frameId ++;
  21331. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  21332. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  21333. this.lastTime = performance.now();
  21334. this.time += this.deltaTime;
  21335. }
  21336. }
  21337. /**
  21338. * Describes the input of a {@link NodeFunction}.
  21339. */
  21340. class NodeFunctionInput {
  21341. /**
  21342. * Constructs a new node function input.
  21343. *
  21344. * @param {String} type - The input type.
  21345. * @param {String} name - The input name.
  21346. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  21347. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  21348. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  21349. */
  21350. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  21351. /**
  21352. * The input type.
  21353. *
  21354. * @type {String}
  21355. */
  21356. this.type = type;
  21357. /**
  21358. * The input name.
  21359. *
  21360. * @type {String}
  21361. */
  21362. this.name = name;
  21363. /**
  21364. * If the input is an Array, count will be the length.
  21365. *
  21366. * @type {Number?}
  21367. * @default null
  21368. */
  21369. this.count = count;
  21370. /**
  21371. *The parameter qualifier (only relevant for GLSL).
  21372. *
  21373. * @type {('in'|'out'|'inout')}
  21374. * @default ''
  21375. */
  21376. this.qualifier = qualifier;
  21377. /**
  21378. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  21379. *
  21380. * @type {Boolean}
  21381. * @default false
  21382. */
  21383. this.isConst = isConst;
  21384. }
  21385. }
  21386. NodeFunctionInput.isNodeFunctionInput = true;
  21387. /**
  21388. * Module for representing directional lights as nodes.
  21389. *
  21390. * @augments AnalyticLightNode
  21391. */
  21392. class DirectionalLightNode extends AnalyticLightNode {
  21393. static get type() {
  21394. return 'DirectionalLightNode';
  21395. }
  21396. /**
  21397. * Constructs a new directional light node.
  21398. *
  21399. * @param {DirectionalLight?} [light=null] - The directional light source.
  21400. */
  21401. constructor( light = null ) {
  21402. super( light );
  21403. }
  21404. setup( builder ) {
  21405. super.setup( builder );
  21406. const lightingModel = builder.context.lightingModel;
  21407. const lightColor = this.colorNode;
  21408. const lightDirection = lightTargetDirection( this.light );
  21409. const reflectedLight = builder.context.reflectedLight;
  21410. lightingModel.direct( {
  21411. lightDirection,
  21412. lightColor,
  21413. reflectedLight
  21414. }, builder.stack, builder );
  21415. }
  21416. }
  21417. const _matrix41 = /*@__PURE__*/ new Matrix4();
  21418. const _matrix42 = /*@__PURE__*/ new Matrix4();
  21419. let _ltcLib = null;
  21420. /**
  21421. * Module for representing rect area lights as nodes.
  21422. *
  21423. * @augments AnalyticLightNode
  21424. */
  21425. class RectAreaLightNode extends AnalyticLightNode {
  21426. static get type() {
  21427. return 'RectAreaLightNode';
  21428. }
  21429. /**
  21430. * Constructs a new rect area light node.
  21431. *
  21432. * @param {RectAreaLight?} [light=null] - The rect area light source.
  21433. */
  21434. constructor( light = null ) {
  21435. super( light );
  21436. /**
  21437. * Uniform node representing the half height of the are light.
  21438. *
  21439. * @type {UniformNode<vec3>}
  21440. */
  21441. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  21442. /**
  21443. * Uniform node representing the half width of the are light.
  21444. *
  21445. * @type {UniformNode<vec3>}
  21446. */
  21447. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  21448. /**
  21449. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  21450. * relies on `viewMatrix` which might vary per render call.
  21451. *
  21452. * @type {String}
  21453. * @default 'render'
  21454. */
  21455. this.updateType = NodeUpdateType.RENDER;
  21456. }
  21457. /**
  21458. * Overwritten to updated rect area light specific uniforms.
  21459. *
  21460. * @param {NodeFrame} frame - A reference to the current node frame.
  21461. */
  21462. update( frame ) {
  21463. super.update( frame );
  21464. const { light } = this;
  21465. const viewMatrix = frame.camera.matrixWorldInverse;
  21466. _matrix42.identity();
  21467. _matrix41.copy( light.matrixWorld );
  21468. _matrix41.premultiply( viewMatrix );
  21469. _matrix42.extractRotation( _matrix41 );
  21470. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  21471. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  21472. this.halfWidth.value.applyMatrix4( _matrix42 );
  21473. this.halfHeight.value.applyMatrix4( _matrix42 );
  21474. }
  21475. setup( builder ) {
  21476. super.setup( builder );
  21477. let ltc_1, ltc_2;
  21478. if ( builder.isAvailable( 'float32Filterable' ) ) {
  21479. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  21480. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  21481. } else {
  21482. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  21483. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  21484. }
  21485. const { colorNode, light } = this;
  21486. const lightingModel = builder.context.lightingModel;
  21487. const lightPosition = lightViewPosition( light );
  21488. const reflectedLight = builder.context.reflectedLight;
  21489. lightingModel.directRectArea( {
  21490. lightColor: colorNode,
  21491. lightPosition,
  21492. halfWidth: this.halfWidth,
  21493. halfHeight: this.halfHeight,
  21494. reflectedLight,
  21495. ltc_1,
  21496. ltc_2
  21497. }, builder.stack, builder );
  21498. }
  21499. /**
  21500. * Used to configure the internal BRDF approximation texture data.
  21501. *
  21502. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  21503. */
  21504. static setLTC( ltc ) {
  21505. _ltcLib = ltc;
  21506. }
  21507. }
  21508. /**
  21509. * Module for representing spot lights as nodes.
  21510. *
  21511. * @augments AnalyticLightNode
  21512. */
  21513. class SpotLightNode extends AnalyticLightNode {
  21514. static get type() {
  21515. return 'SpotLightNode';
  21516. }
  21517. /**
  21518. * Constructs a new spot light node.
  21519. *
  21520. * @param {SpotLight?} [light=null] - The spot light source.
  21521. */
  21522. constructor( light = null ) {
  21523. super( light );
  21524. /**
  21525. * Uniform node representing the cone cosinus.
  21526. *
  21527. * @type {UniformNode<float>}
  21528. */
  21529. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  21530. /**
  21531. * Uniform node representing the penumbra cosinus.
  21532. *
  21533. * @type {UniformNode<float>}
  21534. */
  21535. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  21536. /**
  21537. * Uniform node representing the cutoff distance.
  21538. *
  21539. * @type {UniformNode<float>}
  21540. */
  21541. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  21542. /**
  21543. * Uniform node representing the decay exponent.
  21544. *
  21545. * @type {UniformNode<float>}
  21546. */
  21547. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  21548. }
  21549. /**
  21550. * Overwritten to updated spot light specific uniforms.
  21551. *
  21552. * @param {NodeFrame} frame - A reference to the current node frame.
  21553. */
  21554. update( frame ) {
  21555. super.update( frame );
  21556. const { light } = this;
  21557. this.coneCosNode.value = Math.cos( light.angle );
  21558. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  21559. this.cutoffDistanceNode.value = light.distance;
  21560. this.decayExponentNode.value = light.decay;
  21561. }
  21562. /**
  21563. * Computes the spot attenuation for the given angle.
  21564. *
  21565. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  21566. * @return {Node<float>} The spot attenuation.
  21567. */
  21568. getSpotAttenuation( angleCosine ) {
  21569. const { coneCosNode, penumbraCosNode } = this;
  21570. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  21571. }
  21572. setup( builder ) {
  21573. super.setup( builder );
  21574. const lightingModel = builder.context.lightingModel;
  21575. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  21576. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  21577. const lightDirection = lVector.normalize();
  21578. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  21579. const spotAttenuation = this.getSpotAttenuation( angleCos );
  21580. const lightDistance = lVector.length();
  21581. const lightAttenuation = getDistanceAttenuation( {
  21582. lightDistance,
  21583. cutoffDistance: cutoffDistanceNode,
  21584. decayExponent: decayExponentNode
  21585. } );
  21586. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  21587. if ( light.map ) {
  21588. const spotLightCoord = lightProjectionUV( light );
  21589. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  21590. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  21591. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  21592. }
  21593. const reflectedLight = builder.context.reflectedLight;
  21594. lightingModel.direct( {
  21595. lightDirection,
  21596. lightColor,
  21597. reflectedLight
  21598. }, builder.stack, builder );
  21599. }
  21600. }
  21601. /**
  21602. * An IES version of the default spot light node.
  21603. *
  21604. * @augments SpotLightNode
  21605. */
  21606. class IESSpotLightNode extends SpotLightNode {
  21607. static get type() {
  21608. return 'IESSpotLightNode';
  21609. }
  21610. /**
  21611. * Overwrites the default implementation to compute an IES conform spot attenuation.
  21612. *
  21613. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  21614. * @return {Node<float>} The spot attenuation.
  21615. */
  21616. getSpotAttenuation( angleCosine ) {
  21617. const iesMap = this.light.iesMap;
  21618. let spotAttenuation = null;
  21619. if ( iesMap && iesMap.isTexture === true ) {
  21620. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  21621. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  21622. } else {
  21623. spotAttenuation = super.getSpotAttenuation( angleCosine );
  21624. }
  21625. return spotAttenuation;
  21626. }
  21627. }
  21628. /**
  21629. * Module for representing ambient lights as nodes.
  21630. *
  21631. * @augments AnalyticLightNode
  21632. */
  21633. class AmbientLightNode extends AnalyticLightNode {
  21634. static get type() {
  21635. return 'AmbientLightNode';
  21636. }
  21637. /**
  21638. * Constructs a new ambient light node.
  21639. *
  21640. * @param {AmbientLight?} [light=null] - The ambient light source.
  21641. */
  21642. constructor( light = null ) {
  21643. super( light );
  21644. }
  21645. setup( { context } ) {
  21646. context.irradiance.addAssign( this.colorNode );
  21647. }
  21648. }
  21649. /**
  21650. * Module for representing hemisphere lights as nodes.
  21651. *
  21652. * @augments AnalyticLightNode
  21653. */
  21654. class HemisphereLightNode extends AnalyticLightNode {
  21655. static get type() {
  21656. return 'HemisphereLightNode';
  21657. }
  21658. /**
  21659. * Constructs a new hemisphere light node.
  21660. *
  21661. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  21662. */
  21663. constructor( light = null ) {
  21664. super( light );
  21665. /**
  21666. * Uniform node representing the light's position.
  21667. *
  21668. * @type {UniformNode<vec3>}
  21669. */
  21670. this.lightPositionNode = lightPosition( light );
  21671. /**
  21672. * A node representing the light's direction.
  21673. *
  21674. * @type {Node<vec3>}
  21675. */
  21676. this.lightDirectionNode = this.lightPositionNode.normalize();
  21677. /**
  21678. * Uniform node representing the light's ground color.
  21679. *
  21680. * @type {UniformNode<vec3>}
  21681. */
  21682. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  21683. }
  21684. /**
  21685. * Overwritten to updated hemisphere light specific uniforms.
  21686. *
  21687. * @param {NodeFrame} frame - A reference to the current node frame.
  21688. */
  21689. update( frame ) {
  21690. const { light } = this;
  21691. super.update( frame );
  21692. this.lightPositionNode.object3d = light;
  21693. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  21694. }
  21695. setup( builder ) {
  21696. const { colorNode, groundColorNode, lightDirectionNode } = this;
  21697. const dotNL = normalView.dot( lightDirectionNode );
  21698. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  21699. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  21700. builder.context.irradiance.addAssign( irradiance );
  21701. }
  21702. }
  21703. /**
  21704. * Module for representing light probes as nodes.
  21705. *
  21706. * @augments AnalyticLightNode
  21707. */
  21708. class LightProbeNode extends AnalyticLightNode {
  21709. static get type() {
  21710. return 'LightProbeNode';
  21711. }
  21712. /**
  21713. * Constructs a new light probe node.
  21714. *
  21715. * @param {LightProbe?} [light=null] - The light probe.
  21716. */
  21717. constructor( light = null ) {
  21718. super( light );
  21719. const array = [];
  21720. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  21721. /**
  21722. * Light probe represented as a uniform of spherical harmonics.
  21723. *
  21724. * @type {UniformArrayNode}
  21725. */
  21726. this.lightProbe = uniformArray( array );
  21727. }
  21728. /**
  21729. * Overwritten to updated light probe specific uniforms.
  21730. *
  21731. * @param {NodeFrame} frame - A reference to the current node frame.
  21732. */
  21733. update( frame ) {
  21734. const { light } = this;
  21735. super.update( frame );
  21736. //
  21737. for ( let i = 0; i < 9; i ++ ) {
  21738. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  21739. }
  21740. }
  21741. setup( builder ) {
  21742. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  21743. builder.context.irradiance.addAssign( irradiance );
  21744. }
  21745. }
  21746. /**
  21747. * Base class for node parsers. A derived parser must be implemented
  21748. * for each supported native shader language.
  21749. */
  21750. class NodeParser {
  21751. /**
  21752. * The method parses the given native code an returns a node function.
  21753. *
  21754. * @abstract
  21755. * @param {String} source - The native shader code.
  21756. * @return {NodeFunction} A node function.
  21757. */
  21758. parseFunction( /*source*/ ) {
  21759. console.warn( 'Abstract function.' );
  21760. }
  21761. }
  21762. /**
  21763. * Base class for node functions. A derived module must be implemented
  21764. * for each supported native shader language. Similar to other `Node*` modules,
  21765. * this class is only relevant during the building process and not used
  21766. * in user-level code.
  21767. */
  21768. class NodeFunction {
  21769. /**
  21770. * Constructs a new node function.
  21771. *
  21772. * @param {String} type - The node type. This type is the return type of the node function.
  21773. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  21774. * @param {String} [name=''] - The function's name.
  21775. * @param {String} [precision=''] - The precision qualifier.
  21776. */
  21777. constructor( type, inputs, name = '', precision = '' ) {
  21778. /**
  21779. * The node type. This type is the return type of the node function.
  21780. *
  21781. * @type {String}
  21782. */
  21783. this.type = type;
  21784. /**
  21785. * The function's inputs.
  21786. *
  21787. * @type {Array<NodeFunctionInput>}
  21788. */
  21789. this.inputs = inputs;
  21790. /**
  21791. * The name of the uniform.
  21792. *
  21793. * @type {String}
  21794. * @default ''
  21795. */
  21796. this.name = name;
  21797. /**
  21798. * The precision qualifier.
  21799. *
  21800. * @type {String}
  21801. * @default ''
  21802. */
  21803. this.precision = precision;
  21804. }
  21805. /**
  21806. * This method returns the native code of the node function.
  21807. *
  21808. * @abstract
  21809. * @param {String} name - The function's name.
  21810. * @return {String} A shader code.
  21811. */
  21812. getCode( /*name = this.name*/ ) {
  21813. console.warn( 'Abstract function.' );
  21814. }
  21815. }
  21816. NodeFunction.isNodeFunction = true;
  21817. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  21818. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  21819. const pragmaMain = '#pragma main';
  21820. const parse$1 = ( source ) => {
  21821. source = source.trim();
  21822. const pragmaMainIndex = source.indexOf( pragmaMain );
  21823. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  21824. const declaration = mainCode.match( declarationRegexp$1 );
  21825. if ( declaration !== null && declaration.length === 5 ) {
  21826. // tokenizer
  21827. const inputsCode = declaration[ 4 ];
  21828. const propsMatches = [];
  21829. let nameMatch = null;
  21830. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  21831. propsMatches.push( nameMatch );
  21832. }
  21833. // parser
  21834. const inputs = [];
  21835. let i = 0;
  21836. while ( i < propsMatches.length ) {
  21837. const isConst = propsMatches[ i ][ 0 ] === 'const';
  21838. if ( isConst === true ) {
  21839. i ++;
  21840. }
  21841. let qualifier = propsMatches[ i ][ 0 ];
  21842. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  21843. i ++;
  21844. } else {
  21845. qualifier = '';
  21846. }
  21847. const type = propsMatches[ i ++ ][ 0 ];
  21848. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  21849. if ( Number.isNaN( count ) === false ) i ++;
  21850. else count = null;
  21851. const name = propsMatches[ i ++ ][ 0 ];
  21852. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  21853. }
  21854. //
  21855. const blockCode = mainCode.substring( declaration[ 0 ].length );
  21856. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  21857. const type = declaration[ 2 ];
  21858. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21859. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  21860. return {
  21861. type,
  21862. inputs,
  21863. name,
  21864. precision,
  21865. inputsCode,
  21866. blockCode,
  21867. headerCode
  21868. };
  21869. } else {
  21870. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  21871. }
  21872. };
  21873. /**
  21874. * This class represents a GLSL node function.
  21875. *
  21876. * @augments NodeFunction
  21877. */
  21878. class GLSLNodeFunction extends NodeFunction {
  21879. /**
  21880. * Constructs a new GLSL node function.
  21881. *
  21882. * @param {String} source - The GLSL source.
  21883. */
  21884. constructor( source ) {
  21885. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  21886. super( type, inputs, name, precision );
  21887. this.inputsCode = inputsCode;
  21888. this.blockCode = blockCode;
  21889. this.headerCode = headerCode;
  21890. }
  21891. /**
  21892. * This method returns the GLSL code of the node function.
  21893. *
  21894. * @param {String} [name=this.name] - The function's name.
  21895. * @return {String} The shader code.
  21896. */
  21897. getCode( name = this.name ) {
  21898. let code;
  21899. const blockCode = this.blockCode;
  21900. if ( blockCode !== '' ) {
  21901. const { type, inputsCode, headerCode, precision } = this;
  21902. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  21903. if ( precision !== '' ) {
  21904. declarationCode = `${ precision } ${ declarationCode }`;
  21905. }
  21906. code = headerCode + declarationCode + blockCode;
  21907. } else {
  21908. // interface function
  21909. code = '';
  21910. }
  21911. return code;
  21912. }
  21913. }
  21914. /**
  21915. * A GLSL node parser.
  21916. *
  21917. * @augments NodeParser
  21918. */
  21919. class GLSLNodeParser extends NodeParser {
  21920. /**
  21921. * The method parses the given GLSL code an returns a node function.
  21922. *
  21923. * @param {String} source - The GLSL code.
  21924. * @return {GLSLNodeFunction} A node function.
  21925. */
  21926. parseFunction( source ) {
  21927. return new GLSLNodeFunction( source );
  21928. }
  21929. }
  21930. const outputNodeMap = new WeakMap();
  21931. class Nodes extends DataMap {
  21932. constructor( renderer, backend ) {
  21933. super();
  21934. this.renderer = renderer;
  21935. this.backend = backend;
  21936. this.nodeFrame = new NodeFrame();
  21937. this.nodeBuilderCache = new Map();
  21938. this.callHashCache = new ChainMap();
  21939. this.groupsData = new ChainMap();
  21940. }
  21941. updateGroup( nodeUniformsGroup ) {
  21942. const groupNode = nodeUniformsGroup.groupNode;
  21943. const name = groupNode.name;
  21944. // objectGroup is every updated
  21945. if ( name === objectGroup.name ) return true;
  21946. // renderGroup is updated once per render/compute call
  21947. if ( name === renderGroup.name ) {
  21948. const uniformsGroupData = this.get( nodeUniformsGroup );
  21949. const renderId = this.nodeFrame.renderId;
  21950. if ( uniformsGroupData.renderId !== renderId ) {
  21951. uniformsGroupData.renderId = renderId;
  21952. return true;
  21953. }
  21954. return false;
  21955. }
  21956. // frameGroup is updated once per frame
  21957. if ( name === frameGroup.name ) {
  21958. const uniformsGroupData = this.get( nodeUniformsGroup );
  21959. const frameId = this.nodeFrame.frameId;
  21960. if ( uniformsGroupData.frameId !== frameId ) {
  21961. uniformsGroupData.frameId = frameId;
  21962. return true;
  21963. }
  21964. return false;
  21965. }
  21966. // other groups are updated just when groupNode.needsUpdate is true
  21967. const groupChain = [ groupNode, nodeUniformsGroup ];
  21968. let groupData = this.groupsData.get( groupChain );
  21969. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  21970. if ( groupData.version !== groupNode.version ) {
  21971. groupData.version = groupNode.version;
  21972. return true;
  21973. }
  21974. return false;
  21975. }
  21976. getForRenderCacheKey( renderObject ) {
  21977. return renderObject.initialCacheKey;
  21978. }
  21979. getForRender( renderObject ) {
  21980. const renderObjectData = this.get( renderObject );
  21981. let nodeBuilderState = renderObjectData.nodeBuilderState;
  21982. if ( nodeBuilderState === undefined ) {
  21983. const { nodeBuilderCache } = this;
  21984. const cacheKey = this.getForRenderCacheKey( renderObject );
  21985. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  21986. if ( nodeBuilderState === undefined ) {
  21987. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  21988. nodeBuilder.scene = renderObject.scene;
  21989. nodeBuilder.material = renderObject.material;
  21990. nodeBuilder.camera = renderObject.camera;
  21991. nodeBuilder.context.material = renderObject.material;
  21992. nodeBuilder.lightsNode = renderObject.lightsNode;
  21993. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  21994. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  21995. nodeBuilder.clippingContext = renderObject.clippingContext;
  21996. nodeBuilder.build();
  21997. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  21998. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  21999. }
  22000. nodeBuilderState.usedTimes ++;
  22001. renderObjectData.nodeBuilderState = nodeBuilderState;
  22002. }
  22003. return nodeBuilderState;
  22004. }
  22005. delete( object ) {
  22006. if ( object.isRenderObject ) {
  22007. const nodeBuilderState = this.get( object ).nodeBuilderState;
  22008. nodeBuilderState.usedTimes --;
  22009. if ( nodeBuilderState.usedTimes === 0 ) {
  22010. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  22011. }
  22012. }
  22013. return super.delete( object );
  22014. }
  22015. getForCompute( computeNode ) {
  22016. const computeData = this.get( computeNode );
  22017. let nodeBuilderState = computeData.nodeBuilderState;
  22018. if ( nodeBuilderState === undefined ) {
  22019. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  22020. nodeBuilder.build();
  22021. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  22022. computeData.nodeBuilderState = nodeBuilderState;
  22023. }
  22024. return nodeBuilderState;
  22025. }
  22026. _createNodeBuilderState( nodeBuilder ) {
  22027. return new NodeBuilderState(
  22028. nodeBuilder.vertexShader,
  22029. nodeBuilder.fragmentShader,
  22030. nodeBuilder.computeShader,
  22031. nodeBuilder.getAttributesArray(),
  22032. nodeBuilder.getBindings(),
  22033. nodeBuilder.updateNodes,
  22034. nodeBuilder.updateBeforeNodes,
  22035. nodeBuilder.updateAfterNodes,
  22036. nodeBuilder.monitor,
  22037. nodeBuilder.transforms
  22038. );
  22039. }
  22040. getEnvironmentNode( scene ) {
  22041. return scene.environmentNode || this.get( scene ).environmentNode || null;
  22042. }
  22043. getBackgroundNode( scene ) {
  22044. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  22045. }
  22046. getFogNode( scene ) {
  22047. return scene.fogNode || this.get( scene ).fogNode || null;
  22048. }
  22049. getCacheKey( scene, lightsNode ) {
  22050. const chain = [ scene, lightsNode ];
  22051. const callId = this.renderer.info.calls;
  22052. let cacheKeyData = this.callHashCache.get( chain );
  22053. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  22054. const environmentNode = this.getEnvironmentNode( scene );
  22055. const fogNode = this.getFogNode( scene );
  22056. const values = [];
  22057. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  22058. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  22059. if ( fogNode ) values.push( fogNode.getCacheKey() );
  22060. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  22061. cacheKeyData = {
  22062. callId,
  22063. cacheKey: hashArray( values )
  22064. };
  22065. this.callHashCache.set( chain, cacheKeyData );
  22066. }
  22067. return cacheKeyData.cacheKey;
  22068. }
  22069. updateScene( scene ) {
  22070. this.updateEnvironment( scene );
  22071. this.updateFog( scene );
  22072. this.updateBackground( scene );
  22073. }
  22074. get isToneMappingState() {
  22075. return this.renderer.getRenderTarget() ? false : true;
  22076. }
  22077. updateBackground( scene ) {
  22078. const sceneData = this.get( scene );
  22079. const background = scene.background;
  22080. if ( background ) {
  22081. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  22082. if ( sceneData.background !== background || forceUpdate ) {
  22083. let backgroundNode = null;
  22084. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  22085. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  22086. backgroundNode = pmremTexture( background );
  22087. } else {
  22088. let envMap;
  22089. if ( background.isCubeTexture === true ) {
  22090. envMap = cubeTexture( background );
  22091. } else {
  22092. envMap = texture( background );
  22093. }
  22094. backgroundNode = cubeMapNode( envMap );
  22095. }
  22096. } else if ( background.isTexture === true ) {
  22097. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  22098. } else if ( background.isColor !== true ) {
  22099. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  22100. }
  22101. sceneData.backgroundNode = backgroundNode;
  22102. sceneData.background = background;
  22103. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  22104. }
  22105. } else if ( sceneData.backgroundNode ) {
  22106. delete sceneData.backgroundNode;
  22107. delete sceneData.background;
  22108. }
  22109. }
  22110. updateFog( scene ) {
  22111. const sceneData = this.get( scene );
  22112. const fog = scene.fog;
  22113. if ( fog ) {
  22114. if ( sceneData.fog !== fog ) {
  22115. let fogNode = null;
  22116. if ( fog.isFogExp2 ) {
  22117. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  22118. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  22119. fogNode = densityFog( color, density );
  22120. } else if ( fog.isFog ) {
  22121. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  22122. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  22123. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  22124. fogNode = rangeFog( color, near, far );
  22125. } else {
  22126. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  22127. }
  22128. sceneData.fogNode = fogNode;
  22129. sceneData.fog = fog;
  22130. }
  22131. } else {
  22132. delete sceneData.fogNode;
  22133. delete sceneData.fog;
  22134. }
  22135. }
  22136. updateEnvironment( scene ) {
  22137. const sceneData = this.get( scene );
  22138. const environment = scene.environment;
  22139. if ( environment ) {
  22140. if ( sceneData.environment !== environment ) {
  22141. let environmentNode = null;
  22142. if ( environment.isCubeTexture === true ) {
  22143. environmentNode = cubeTexture( environment );
  22144. } else if ( environment.isTexture === true ) {
  22145. environmentNode = texture( environment );
  22146. } else {
  22147. console.error( 'Nodes: Unsupported environment configuration.', environment );
  22148. }
  22149. sceneData.environmentNode = environmentNode;
  22150. sceneData.environment = environment;
  22151. }
  22152. } else if ( sceneData.environmentNode ) {
  22153. delete sceneData.environmentNode;
  22154. delete sceneData.environment;
  22155. }
  22156. }
  22157. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  22158. const nodeFrame = this.nodeFrame;
  22159. nodeFrame.renderer = renderer;
  22160. nodeFrame.scene = scene;
  22161. nodeFrame.object = object;
  22162. nodeFrame.camera = camera;
  22163. nodeFrame.material = material;
  22164. return nodeFrame;
  22165. }
  22166. getNodeFrameForRender( renderObject ) {
  22167. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  22168. }
  22169. getOutputCacheKey() {
  22170. const renderer = this.renderer;
  22171. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  22172. }
  22173. hasOutputChange( outputTarget ) {
  22174. const cacheKey = outputNodeMap.get( outputTarget );
  22175. return cacheKey !== this.getOutputCacheKey();
  22176. }
  22177. getOutputNode( outputTexture ) {
  22178. const renderer = this.renderer;
  22179. const cacheKey = this.getOutputCacheKey();
  22180. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  22181. outputNodeMap.set( outputTexture, cacheKey );
  22182. return output;
  22183. }
  22184. updateBefore( renderObject ) {
  22185. const nodeBuilder = renderObject.getNodeBuilderState();
  22186. for ( const node of nodeBuilder.updateBeforeNodes ) {
  22187. // update frame state for each node
  22188. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  22189. }
  22190. }
  22191. updateAfter( renderObject ) {
  22192. const nodeBuilder = renderObject.getNodeBuilderState();
  22193. for ( const node of nodeBuilder.updateAfterNodes ) {
  22194. // update frame state for each node
  22195. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  22196. }
  22197. }
  22198. updateForCompute( computeNode ) {
  22199. const nodeFrame = this.getNodeFrame();
  22200. const nodeBuilder = this.getForCompute( computeNode );
  22201. for ( const node of nodeBuilder.updateNodes ) {
  22202. nodeFrame.updateNode( node );
  22203. }
  22204. }
  22205. updateForRender( renderObject ) {
  22206. const nodeFrame = this.getNodeFrameForRender( renderObject );
  22207. const nodeBuilder = renderObject.getNodeBuilderState();
  22208. for ( const node of nodeBuilder.updateNodes ) {
  22209. nodeFrame.updateNode( node );
  22210. }
  22211. }
  22212. needsRefresh( renderObject ) {
  22213. const nodeFrame = this.getNodeFrameForRender( renderObject );
  22214. const monitor = renderObject.getMonitor();
  22215. return monitor.needsRefresh( renderObject, nodeFrame );
  22216. }
  22217. dispose() {
  22218. super.dispose();
  22219. this.nodeFrame = new NodeFrame();
  22220. this.nodeBuilderCache = new Map();
  22221. }
  22222. }
  22223. const _plane = /*@__PURE__*/ new Plane();
  22224. class ClippingContext {
  22225. constructor( parentContext = null ) {
  22226. this.version = 0;
  22227. this.clipIntersection = null;
  22228. this.cacheKey = '';
  22229. if ( parentContext === null ) {
  22230. this.intersectionPlanes = [];
  22231. this.unionPlanes = [];
  22232. this.viewNormalMatrix = new Matrix3();
  22233. this.clippingGroupContexts = new WeakMap();
  22234. this.shadowPass = false;
  22235. } else {
  22236. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  22237. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  22238. this.shadowPass = parentContext.shadowPass;
  22239. this.viewMatrix = parentContext.viewMatrix;
  22240. }
  22241. this.parentVersion = null;
  22242. }
  22243. projectPlanes( source, destination, offset ) {
  22244. const l = source.length;
  22245. for ( let i = 0; i < l; i ++ ) {
  22246. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  22247. const v = destination[ offset + i ];
  22248. const normal = _plane.normal;
  22249. v.x = - normal.x;
  22250. v.y = - normal.y;
  22251. v.z = - normal.z;
  22252. v.w = _plane.constant;
  22253. }
  22254. }
  22255. updateGlobal( scene, camera ) {
  22256. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  22257. this.viewMatrix = camera.matrixWorldInverse;
  22258. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  22259. }
  22260. update( parentContext, clippingGroup ) {
  22261. let update = false;
  22262. if ( parentContext.version !== this.parentVersion ) {
  22263. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  22264. this.unionPlanes = Array.from( parentContext.unionPlanes );
  22265. this.parentVersion = parentContext.version;
  22266. }
  22267. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  22268. this.clipIntersection = clippingGroup.clipIntersection;
  22269. if ( this.clipIntersection ) {
  22270. this.unionPlanes.length = parentContext.unionPlanes.length;
  22271. } else {
  22272. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  22273. }
  22274. }
  22275. const srcClippingPlanes = clippingGroup.clippingPlanes;
  22276. const l = srcClippingPlanes.length;
  22277. let dstClippingPlanes;
  22278. let offset;
  22279. if ( this.clipIntersection ) {
  22280. dstClippingPlanes = this.intersectionPlanes;
  22281. offset = parentContext.intersectionPlanes.length;
  22282. } else {
  22283. dstClippingPlanes = this.unionPlanes;
  22284. offset = parentContext.unionPlanes.length;
  22285. }
  22286. if ( dstClippingPlanes.length !== offset + l ) {
  22287. dstClippingPlanes.length = offset + l;
  22288. for ( let i = 0; i < l; i ++ ) {
  22289. dstClippingPlanes[ offset + i ] = new Vector4();
  22290. }
  22291. update = true;
  22292. }
  22293. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  22294. if ( update ) {
  22295. this.version ++;
  22296. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  22297. }
  22298. }
  22299. getGroupContext( clippingGroup ) {
  22300. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  22301. let context = this.clippingGroupContexts.get( clippingGroup );
  22302. if ( context === undefined ) {
  22303. context = new ClippingContext( this );
  22304. this.clippingGroupContexts.set( clippingGroup, context );
  22305. }
  22306. context.update( this, clippingGroup );
  22307. return context;
  22308. }
  22309. get unionClippingCount() {
  22310. return this.unionPlanes.length;
  22311. }
  22312. }
  22313. class RenderBundle {
  22314. constructor( scene, camera ) {
  22315. this.scene = scene;
  22316. this.camera = camera;
  22317. }
  22318. clone() {
  22319. return Object.assign( new this.constructor(), this );
  22320. }
  22321. }
  22322. class RenderBundles {
  22323. constructor() {
  22324. this.lists = new ChainMap();
  22325. }
  22326. get( scene, camera ) {
  22327. const lists = this.lists;
  22328. const keys = [ scene, camera ];
  22329. let list = lists.get( keys );
  22330. if ( list === undefined ) {
  22331. list = new RenderBundle( scene, camera );
  22332. lists.set( keys, list );
  22333. }
  22334. return list;
  22335. }
  22336. dispose() {
  22337. this.lists = new ChainMap();
  22338. }
  22339. }
  22340. class NodeLibrary {
  22341. constructor() {
  22342. this.lightNodes = new WeakMap();
  22343. this.materialNodes = new Map();
  22344. this.toneMappingNodes = new Map();
  22345. }
  22346. fromMaterial( material ) {
  22347. if ( material.isNodeMaterial ) return material;
  22348. let nodeMaterial = null;
  22349. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  22350. if ( nodeMaterialClass !== null ) {
  22351. nodeMaterial = new nodeMaterialClass();
  22352. for ( const key in material ) {
  22353. nodeMaterial[ key ] = material[ key ];
  22354. }
  22355. }
  22356. return nodeMaterial;
  22357. }
  22358. addToneMapping( toneMappingNode, toneMapping ) {
  22359. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  22360. }
  22361. getToneMappingFunction( toneMapping ) {
  22362. return this.toneMappingNodes.get( toneMapping ) || null;
  22363. }
  22364. getMaterialNodeClass( materialType ) {
  22365. return this.materialNodes.get( materialType ) || null;
  22366. }
  22367. addMaterial( materialNodeClass, materialClassType ) {
  22368. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  22369. }
  22370. getLightNodeClass( light ) {
  22371. return this.lightNodes.get( light ) || null;
  22372. }
  22373. addLight( lightNodeClass, lightClass ) {
  22374. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  22375. }
  22376. addType( nodeClass, type, library ) {
  22377. if ( library.has( type ) ) {
  22378. console.warn( `Redefinition of node ${ type }` );
  22379. return;
  22380. }
  22381. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  22382. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  22383. library.set( type, nodeClass );
  22384. }
  22385. addClass( nodeClass, baseClass, library ) {
  22386. if ( library.has( baseClass ) ) {
  22387. console.warn( `Redefinition of node ${ baseClass.name }` );
  22388. return;
  22389. }
  22390. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  22391. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  22392. library.set( baseClass, nodeClass );
  22393. }
  22394. }
  22395. const _defaultLights = /*@__PURE__*/ new LightsNode();
  22396. class Lighting extends ChainMap {
  22397. constructor() {
  22398. super();
  22399. }
  22400. createNode( lights = [] ) {
  22401. return new LightsNode().setLights( lights );
  22402. }
  22403. getNode( scene, camera ) {
  22404. // ignore post-processing
  22405. if ( scene.isQuadMesh ) return _defaultLights;
  22406. // tiled lighting
  22407. const keys = [ scene, camera ];
  22408. let node = this.get( keys );
  22409. if ( node === undefined ) {
  22410. node = this.createNode();
  22411. this.set( keys, node );
  22412. }
  22413. return node;
  22414. }
  22415. }
  22416. const _scene = /*@__PURE__*/ new Scene();
  22417. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  22418. const _screen = /*@__PURE__*/ new Vector4();
  22419. const _frustum = /*@__PURE__*/ new Frustum();
  22420. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  22421. const _vector4 = /*@__PURE__*/ new Vector4();
  22422. class Renderer {
  22423. constructor( backend, parameters = {} ) {
  22424. this.isRenderer = true;
  22425. //
  22426. const {
  22427. logarithmicDepthBuffer = false,
  22428. alpha = true,
  22429. depth = true,
  22430. stencil = false,
  22431. antialias = false,
  22432. samples = 0,
  22433. getFallback = null
  22434. } = parameters;
  22435. // public
  22436. this.domElement = backend.getDomElement();
  22437. this.backend = backend;
  22438. this.samples = samples || ( antialias === true ) ? 4 : 0;
  22439. this.autoClear = true;
  22440. this.autoClearColor = true;
  22441. this.autoClearDepth = true;
  22442. this.autoClearStencil = true;
  22443. this.alpha = alpha;
  22444. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  22445. this.outputColorSpace = SRGBColorSpace;
  22446. this.toneMapping = NoToneMapping;
  22447. this.toneMappingExposure = 1.0;
  22448. this.sortObjects = true;
  22449. this.depth = depth;
  22450. this.stencil = stencil;
  22451. this.info = new Info();
  22452. this.nodes = {
  22453. modelViewMatrix: null,
  22454. modelNormalViewMatrix: null
  22455. };
  22456. this.library = new NodeLibrary();
  22457. this.lighting = new Lighting();
  22458. // internals
  22459. this._getFallback = getFallback;
  22460. this._pixelRatio = 1;
  22461. this._width = this.domElement.width;
  22462. this._height = this.domElement.height;
  22463. this._viewport = new Vector4( 0, 0, this._width, this._height );
  22464. this._scissor = new Vector4( 0, 0, this._width, this._height );
  22465. this._scissorTest = false;
  22466. this._attributes = null;
  22467. this._geometries = null;
  22468. this._nodes = null;
  22469. this._animation = null;
  22470. this._bindings = null;
  22471. this._objects = null;
  22472. this._pipelines = null;
  22473. this._bundles = null;
  22474. this._renderLists = null;
  22475. this._renderContexts = null;
  22476. this._textures = null;
  22477. this._background = null;
  22478. this._quad = new QuadMesh( new NodeMaterial() );
  22479. this._quad.material.type = 'Renderer_output';
  22480. this._currentRenderContext = null;
  22481. this._opaqueSort = null;
  22482. this._transparentSort = null;
  22483. this._frameBufferTarget = null;
  22484. const alphaClear = this.alpha === true ? 0 : 1;
  22485. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  22486. this._clearDepth = 1;
  22487. this._clearStencil = 0;
  22488. this._renderTarget = null;
  22489. this._activeCubeFace = 0;
  22490. this._activeMipmapLevel = 0;
  22491. this._mrt = null;
  22492. this._renderObjectFunction = null;
  22493. this._currentRenderObjectFunction = null;
  22494. this._currentRenderBundle = null;
  22495. this._handleObjectFunction = this._renderObjectDirect;
  22496. this._isDeviceLost = false;
  22497. this.onDeviceLost = this._onDeviceLost;
  22498. this._initialized = false;
  22499. this._initPromise = null;
  22500. this._compilationPromises = null;
  22501. this.transparent = true;
  22502. this.opaque = true;
  22503. this.shadowMap = {
  22504. enabled: false,
  22505. type: PCFShadowMap
  22506. };
  22507. this.xr = {
  22508. enabled: false
  22509. };
  22510. this.debug = {
  22511. checkShaderErrors: true,
  22512. onShaderError: null,
  22513. getShaderAsync: async ( scene, camera, object ) => {
  22514. await this.compileAsync( scene, camera );
  22515. const renderList = this._renderLists.get( scene, camera );
  22516. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  22517. const material = scene.overrideMaterial || object.material;
  22518. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  22519. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  22520. return { fragmentShader, vertexShader };
  22521. }
  22522. };
  22523. }
  22524. async init() {
  22525. if ( this._initialized ) {
  22526. throw new Error( 'Renderer: Backend has already been initialized.' );
  22527. }
  22528. if ( this._initPromise !== null ) {
  22529. return this._initPromise;
  22530. }
  22531. this._initPromise = new Promise( async ( resolve, reject ) => {
  22532. let backend = this.backend;
  22533. try {
  22534. await backend.init( this );
  22535. } catch ( error ) {
  22536. if ( this._getFallback !== null ) {
  22537. // try the fallback
  22538. try {
  22539. this.backend = backend = this._getFallback( error );
  22540. await backend.init( this );
  22541. } catch ( error ) {
  22542. reject( error );
  22543. return;
  22544. }
  22545. } else {
  22546. reject( error );
  22547. return;
  22548. }
  22549. }
  22550. this._nodes = new Nodes( this, backend );
  22551. this._animation = new Animation( this._nodes, this.info );
  22552. this._attributes = new Attributes( backend );
  22553. this._background = new Background( this, this._nodes );
  22554. this._geometries = new Geometries( this._attributes, this.info );
  22555. this._textures = new Textures( this, backend, this.info );
  22556. this._pipelines = new Pipelines( backend, this._nodes );
  22557. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  22558. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  22559. this._renderLists = new RenderLists( this.lighting );
  22560. this._bundles = new RenderBundles();
  22561. this._renderContexts = new RenderContexts();
  22562. //
  22563. this._animation.start();
  22564. this._initialized = true;
  22565. resolve();
  22566. } );
  22567. return this._initPromise;
  22568. }
  22569. get coordinateSystem() {
  22570. return this.backend.coordinateSystem;
  22571. }
  22572. async compileAsync( scene, camera, targetScene = null ) {
  22573. if ( this._isDeviceLost === true ) return;
  22574. if ( this._initialized === false ) await this.init();
  22575. // preserve render tree
  22576. const nodeFrame = this._nodes.nodeFrame;
  22577. const previousRenderId = nodeFrame.renderId;
  22578. const previousRenderContext = this._currentRenderContext;
  22579. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  22580. const previousCompilationPromises = this._compilationPromises;
  22581. //
  22582. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  22583. if ( targetScene === null ) targetScene = scene;
  22584. const renderTarget = this._renderTarget;
  22585. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  22586. const activeMipmapLevel = this._activeMipmapLevel;
  22587. const compilationPromises = [];
  22588. this._currentRenderContext = renderContext;
  22589. this._currentRenderObjectFunction = this.renderObject;
  22590. this._handleObjectFunction = this._createObjectPipeline;
  22591. this._compilationPromises = compilationPromises;
  22592. nodeFrame.renderId ++;
  22593. //
  22594. nodeFrame.update();
  22595. //
  22596. renderContext.depth = this.depth;
  22597. renderContext.stencil = this.stencil;
  22598. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  22599. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  22600. //
  22601. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  22602. //
  22603. const renderList = this._renderLists.get( scene, camera );
  22604. renderList.begin();
  22605. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  22606. // include lights from target scene
  22607. if ( targetScene !== scene ) {
  22608. targetScene.traverseVisible( function ( object ) {
  22609. if ( object.isLight && object.layers.test( camera.layers ) ) {
  22610. renderList.pushLight( object );
  22611. }
  22612. } );
  22613. }
  22614. renderList.finish();
  22615. //
  22616. if ( renderTarget !== null ) {
  22617. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  22618. const renderTargetData = this._textures.get( renderTarget );
  22619. renderContext.textures = renderTargetData.textures;
  22620. renderContext.depthTexture = renderTargetData.depthTexture;
  22621. } else {
  22622. renderContext.textures = null;
  22623. renderContext.depthTexture = null;
  22624. }
  22625. //
  22626. this._nodes.updateScene( sceneRef );
  22627. //
  22628. this._background.update( sceneRef, renderList, renderContext );
  22629. // process render lists
  22630. const opaqueObjects = renderList.opaque;
  22631. const transparentObjects = renderList.transparent;
  22632. const transparentDoublePassObjects = renderList.transparentDoublePass;
  22633. const lightsNode = renderList.lightsNode;
  22634. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  22635. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  22636. // restore render tree
  22637. nodeFrame.renderId = previousRenderId;
  22638. this._currentRenderContext = previousRenderContext;
  22639. this._currentRenderObjectFunction = previousRenderObjectFunction;
  22640. this._compilationPromises = previousCompilationPromises;
  22641. this._handleObjectFunction = this._renderObjectDirect;
  22642. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  22643. await Promise.all( compilationPromises );
  22644. }
  22645. async renderAsync( scene, camera ) {
  22646. if ( this._initialized === false ) await this.init();
  22647. const renderContext = this._renderScene( scene, camera );
  22648. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  22649. }
  22650. async waitForGPU() {
  22651. await this.backend.waitForGPU();
  22652. }
  22653. setMRT( mrt ) {
  22654. this._mrt = mrt;
  22655. return this;
  22656. }
  22657. getMRT() {
  22658. return this._mrt;
  22659. }
  22660. _onDeviceLost( info ) {
  22661. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  22662. if ( info.reason ) {
  22663. errorMessage += `\nReason: ${info.reason}`;
  22664. }
  22665. console.error( errorMessage );
  22666. this._isDeviceLost = true;
  22667. }
  22668. _renderBundle( bundle, sceneRef, lightsNode ) {
  22669. const { bundleGroup, camera, renderList } = bundle;
  22670. const renderContext = this._currentRenderContext;
  22671. //
  22672. const renderBundle = this._bundles.get( bundleGroup, camera );
  22673. const renderBundleData = this.backend.get( renderBundle );
  22674. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  22675. //
  22676. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  22677. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  22678. renderBundleData.renderContexts.add( renderContext );
  22679. if ( renderBundleNeedsUpdate ) {
  22680. this.backend.beginBundle( renderContext );
  22681. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  22682. renderBundleData.renderObjects = [];
  22683. }
  22684. this._currentRenderBundle = renderBundle;
  22685. const opaqueObjects = renderList.opaque;
  22686. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  22687. this._currentRenderBundle = null;
  22688. //
  22689. this.backend.finishBundle( renderContext, renderBundle );
  22690. renderBundleData.version = bundleGroup.version;
  22691. } else {
  22692. const { renderObjects } = renderBundleData;
  22693. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  22694. const renderObject = renderObjects[ i ];
  22695. if ( this._nodes.needsRefresh( renderObject ) ) {
  22696. this._nodes.updateBefore( renderObject );
  22697. this._nodes.updateForRender( renderObject );
  22698. this._bindings.updateForRender( renderObject );
  22699. this._nodes.updateAfter( renderObject );
  22700. }
  22701. }
  22702. }
  22703. this.backend.addBundle( renderContext, renderBundle );
  22704. }
  22705. render( scene, camera ) {
  22706. if ( this._initialized === false ) {
  22707. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  22708. return this.renderAsync( scene, camera );
  22709. }
  22710. this._renderScene( scene, camera );
  22711. }
  22712. _getFrameBufferTarget() {
  22713. const { currentToneMapping, currentColorSpace } = this;
  22714. const useToneMapping = currentToneMapping !== NoToneMapping;
  22715. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  22716. if ( useToneMapping === false && useColorSpace === false ) return null;
  22717. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  22718. const { depth, stencil } = this;
  22719. let frameBufferTarget = this._frameBufferTarget;
  22720. if ( frameBufferTarget === null ) {
  22721. frameBufferTarget = new RenderTarget( width, height, {
  22722. depthBuffer: depth,
  22723. stencilBuffer: stencil,
  22724. type: HalfFloatType, // FloatType
  22725. format: RGBAFormat,
  22726. colorSpace: LinearSRGBColorSpace,
  22727. generateMipmaps: false,
  22728. minFilter: LinearFilter,
  22729. magFilter: LinearFilter,
  22730. samples: this.samples
  22731. } );
  22732. frameBufferTarget.isPostProcessingRenderTarget = true;
  22733. this._frameBufferTarget = frameBufferTarget;
  22734. }
  22735. frameBufferTarget.depthBuffer = depth;
  22736. frameBufferTarget.stencilBuffer = stencil;
  22737. frameBufferTarget.setSize( width, height );
  22738. frameBufferTarget.viewport.copy( this._viewport );
  22739. frameBufferTarget.scissor.copy( this._scissor );
  22740. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  22741. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  22742. frameBufferTarget.scissorTest = this._scissorTest;
  22743. return frameBufferTarget;
  22744. }
  22745. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  22746. if ( this._isDeviceLost === true ) return;
  22747. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  22748. // preserve render tree
  22749. const nodeFrame = this._nodes.nodeFrame;
  22750. const previousRenderId = nodeFrame.renderId;
  22751. const previousRenderContext = this._currentRenderContext;
  22752. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  22753. //
  22754. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  22755. const outputRenderTarget = this._renderTarget;
  22756. const activeCubeFace = this._activeCubeFace;
  22757. const activeMipmapLevel = this._activeMipmapLevel;
  22758. //
  22759. let renderTarget;
  22760. if ( frameBufferTarget !== null ) {
  22761. renderTarget = frameBufferTarget;
  22762. this.setRenderTarget( renderTarget );
  22763. } else {
  22764. renderTarget = outputRenderTarget;
  22765. }
  22766. //
  22767. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  22768. this._currentRenderContext = renderContext;
  22769. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  22770. //
  22771. this.info.calls ++;
  22772. this.info.render.calls ++;
  22773. this.info.render.frameCalls ++;
  22774. nodeFrame.renderId = this.info.calls;
  22775. //
  22776. const coordinateSystem = this.coordinateSystem;
  22777. if ( camera.coordinateSystem !== coordinateSystem ) {
  22778. camera.coordinateSystem = coordinateSystem;
  22779. camera.updateProjectionMatrix();
  22780. }
  22781. //
  22782. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  22783. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  22784. //
  22785. let viewport = this._viewport;
  22786. let scissor = this._scissor;
  22787. let pixelRatio = this._pixelRatio;
  22788. if ( renderTarget !== null ) {
  22789. viewport = renderTarget.viewport;
  22790. scissor = renderTarget.scissor;
  22791. pixelRatio = 1;
  22792. }
  22793. this.getDrawingBufferSize( _drawingBufferSize );
  22794. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  22795. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  22796. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  22797. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  22798. renderContext.viewportValue.width >>= activeMipmapLevel;
  22799. renderContext.viewportValue.height >>= activeMipmapLevel;
  22800. renderContext.viewportValue.minDepth = minDepth;
  22801. renderContext.viewportValue.maxDepth = maxDepth;
  22802. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  22803. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  22804. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  22805. renderContext.scissorValue.width >>= activeMipmapLevel;
  22806. renderContext.scissorValue.height >>= activeMipmapLevel;
  22807. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  22808. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  22809. //
  22810. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  22811. //
  22812. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22813. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  22814. const renderList = this._renderLists.get( scene, camera );
  22815. renderList.begin();
  22816. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  22817. renderList.finish();
  22818. if ( this.sortObjects === true ) {
  22819. renderList.sort( this._opaqueSort, this._transparentSort );
  22820. }
  22821. //
  22822. if ( renderTarget !== null ) {
  22823. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  22824. const renderTargetData = this._textures.get( renderTarget );
  22825. renderContext.textures = renderTargetData.textures;
  22826. renderContext.depthTexture = renderTargetData.depthTexture;
  22827. renderContext.width = renderTargetData.width;
  22828. renderContext.height = renderTargetData.height;
  22829. renderContext.renderTarget = renderTarget;
  22830. renderContext.depth = renderTarget.depthBuffer;
  22831. renderContext.stencil = renderTarget.stencilBuffer;
  22832. } else {
  22833. renderContext.textures = null;
  22834. renderContext.depthTexture = null;
  22835. renderContext.width = this.domElement.width;
  22836. renderContext.height = this.domElement.height;
  22837. renderContext.depth = this.depth;
  22838. renderContext.stencil = this.stencil;
  22839. }
  22840. renderContext.width >>= activeMipmapLevel;
  22841. renderContext.height >>= activeMipmapLevel;
  22842. renderContext.activeCubeFace = activeCubeFace;
  22843. renderContext.activeMipmapLevel = activeMipmapLevel;
  22844. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  22845. //
  22846. this._nodes.updateScene( sceneRef );
  22847. //
  22848. this._background.update( sceneRef, renderList, renderContext );
  22849. //
  22850. this.backend.beginRender( renderContext );
  22851. // process render lists
  22852. const {
  22853. bundles,
  22854. lightsNode,
  22855. transparentDoublePass: transparentDoublePassObjects,
  22856. transparent: transparentObjects,
  22857. opaque: opaqueObjects
  22858. } = renderList;
  22859. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  22860. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  22861. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  22862. // finish render pass
  22863. this.backend.finishRender( renderContext );
  22864. // restore render tree
  22865. nodeFrame.renderId = previousRenderId;
  22866. this._currentRenderContext = previousRenderContext;
  22867. this._currentRenderObjectFunction = previousRenderObjectFunction;
  22868. //
  22869. if ( frameBufferTarget !== null ) {
  22870. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  22871. const quad = this._quad;
  22872. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  22873. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  22874. quad.material.needsUpdate = true;
  22875. }
  22876. this._renderScene( quad, quad.camera, false );
  22877. }
  22878. //
  22879. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  22880. //
  22881. return renderContext;
  22882. }
  22883. getMaxAnisotropy() {
  22884. return this.backend.getMaxAnisotropy();
  22885. }
  22886. getActiveCubeFace() {
  22887. return this._activeCubeFace;
  22888. }
  22889. getActiveMipmapLevel() {
  22890. return this._activeMipmapLevel;
  22891. }
  22892. async setAnimationLoop( callback ) {
  22893. if ( this._initialized === false ) await this.init();
  22894. this._animation.setAnimationLoop( callback );
  22895. }
  22896. async getArrayBufferAsync( attribute ) {
  22897. return await this.backend.getArrayBufferAsync( attribute );
  22898. }
  22899. getContext() {
  22900. return this.backend.getContext();
  22901. }
  22902. getPixelRatio() {
  22903. return this._pixelRatio;
  22904. }
  22905. getDrawingBufferSize( target ) {
  22906. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  22907. }
  22908. getSize( target ) {
  22909. return target.set( this._width, this._height );
  22910. }
  22911. setPixelRatio( value = 1 ) {
  22912. if ( this._pixelRatio === value ) return;
  22913. this._pixelRatio = value;
  22914. this.setSize( this._width, this._height, false );
  22915. }
  22916. setDrawingBufferSize( width, height, pixelRatio ) {
  22917. this._width = width;
  22918. this._height = height;
  22919. this._pixelRatio = pixelRatio;
  22920. this.domElement.width = Math.floor( width * pixelRatio );
  22921. this.domElement.height = Math.floor( height * pixelRatio );
  22922. this.setViewport( 0, 0, width, height );
  22923. if ( this._initialized ) this.backend.updateSize();
  22924. }
  22925. setSize( width, height, updateStyle = true ) {
  22926. this._width = width;
  22927. this._height = height;
  22928. this.domElement.width = Math.floor( width * this._pixelRatio );
  22929. this.domElement.height = Math.floor( height * this._pixelRatio );
  22930. if ( updateStyle === true ) {
  22931. this.domElement.style.width = width + 'px';
  22932. this.domElement.style.height = height + 'px';
  22933. }
  22934. this.setViewport( 0, 0, width, height );
  22935. if ( this._initialized ) this.backend.updateSize();
  22936. }
  22937. setOpaqueSort( method ) {
  22938. this._opaqueSort = method;
  22939. }
  22940. setTransparentSort( method ) {
  22941. this._transparentSort = method;
  22942. }
  22943. getScissor( target ) {
  22944. const scissor = this._scissor;
  22945. target.x = scissor.x;
  22946. target.y = scissor.y;
  22947. target.width = scissor.width;
  22948. target.height = scissor.height;
  22949. return target;
  22950. }
  22951. setScissor( x, y, width, height ) {
  22952. const scissor = this._scissor;
  22953. if ( x.isVector4 ) {
  22954. scissor.copy( x );
  22955. } else {
  22956. scissor.set( x, y, width, height );
  22957. }
  22958. }
  22959. getScissorTest() {
  22960. return this._scissorTest;
  22961. }
  22962. setScissorTest( boolean ) {
  22963. this._scissorTest = boolean;
  22964. this.backend.setScissorTest( boolean );
  22965. }
  22966. getViewport( target ) {
  22967. return target.copy( this._viewport );
  22968. }
  22969. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  22970. const viewport = this._viewport;
  22971. if ( x.isVector4 ) {
  22972. viewport.copy( x );
  22973. } else {
  22974. viewport.set( x, y, width, height );
  22975. }
  22976. viewport.minDepth = minDepth;
  22977. viewport.maxDepth = maxDepth;
  22978. }
  22979. getClearColor( target ) {
  22980. return target.copy( this._clearColor );
  22981. }
  22982. setClearColor( color, alpha = 1 ) {
  22983. this._clearColor.set( color );
  22984. this._clearColor.a = alpha;
  22985. }
  22986. getClearAlpha() {
  22987. return this._clearColor.a;
  22988. }
  22989. setClearAlpha( alpha ) {
  22990. this._clearColor.a = alpha;
  22991. }
  22992. getClearDepth() {
  22993. return this._clearDepth;
  22994. }
  22995. setClearDepth( depth ) {
  22996. this._clearDepth = depth;
  22997. }
  22998. getClearStencil() {
  22999. return this._clearStencil;
  23000. }
  23001. setClearStencil( stencil ) {
  23002. this._clearStencil = stencil;
  23003. }
  23004. isOccluded( object ) {
  23005. const renderContext = this._currentRenderContext;
  23006. return renderContext && this.backend.isOccluded( renderContext, object );
  23007. }
  23008. clear( color = true, depth = true, stencil = true ) {
  23009. if ( this._initialized === false ) {
  23010. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  23011. return this.clearAsync( color, depth, stencil );
  23012. }
  23013. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  23014. let renderTargetData = null;
  23015. if ( renderTarget !== null ) {
  23016. this._textures.updateRenderTarget( renderTarget );
  23017. renderTargetData = this._textures.get( renderTarget );
  23018. }
  23019. this.backend.clear( color, depth, stencil, renderTargetData );
  23020. if ( renderTarget !== null && this._renderTarget === null ) {
  23021. // If a color space transform or tone mapping is required,
  23022. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  23023. const quad = this._quad;
  23024. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  23025. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  23026. quad.material.needsUpdate = true;
  23027. }
  23028. this._renderScene( quad, quad.camera, false );
  23029. }
  23030. }
  23031. clearColor() {
  23032. return this.clear( true, false, false );
  23033. }
  23034. clearDepth() {
  23035. return this.clear( false, true, false );
  23036. }
  23037. clearStencil() {
  23038. return this.clear( false, false, true );
  23039. }
  23040. async clearAsync( color = true, depth = true, stencil = true ) {
  23041. if ( this._initialized === false ) await this.init();
  23042. this.clear( color, depth, stencil );
  23043. }
  23044. clearColorAsync() {
  23045. return this.clearAsync( true, false, false );
  23046. }
  23047. clearDepthAsync() {
  23048. return this.clearAsync( false, true, false );
  23049. }
  23050. clearStencilAsync() {
  23051. return this.clearAsync( false, false, true );
  23052. }
  23053. get currentToneMapping() {
  23054. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  23055. }
  23056. get currentColorSpace() {
  23057. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  23058. }
  23059. dispose() {
  23060. this.info.dispose();
  23061. this.backend.dispose();
  23062. this._animation.dispose();
  23063. this._objects.dispose();
  23064. this._pipelines.dispose();
  23065. this._nodes.dispose();
  23066. this._bindings.dispose();
  23067. this._renderLists.dispose();
  23068. this._renderContexts.dispose();
  23069. this._textures.dispose();
  23070. this.setRenderTarget( null );
  23071. this.setAnimationLoop( null );
  23072. }
  23073. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  23074. this._renderTarget = renderTarget;
  23075. this._activeCubeFace = activeCubeFace;
  23076. this._activeMipmapLevel = activeMipmapLevel;
  23077. }
  23078. getRenderTarget() {
  23079. return this._renderTarget;
  23080. }
  23081. setRenderObjectFunction( renderObjectFunction ) {
  23082. this._renderObjectFunction = renderObjectFunction;
  23083. }
  23084. getRenderObjectFunction() {
  23085. return this._renderObjectFunction;
  23086. }
  23087. compute( computeNodes ) {
  23088. if ( this.isDeviceLost === true ) return;
  23089. if ( this._initialized === false ) {
  23090. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  23091. return this.computeAsync( computeNodes );
  23092. }
  23093. //
  23094. const nodeFrame = this._nodes.nodeFrame;
  23095. const previousRenderId = nodeFrame.renderId;
  23096. //
  23097. this.info.calls ++;
  23098. this.info.compute.calls ++;
  23099. this.info.compute.frameCalls ++;
  23100. nodeFrame.renderId = this.info.calls;
  23101. //
  23102. const backend = this.backend;
  23103. const pipelines = this._pipelines;
  23104. const bindings = this._bindings;
  23105. const nodes = this._nodes;
  23106. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  23107. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  23108. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  23109. }
  23110. backend.beginCompute( computeNodes );
  23111. for ( const computeNode of computeList ) {
  23112. // onInit
  23113. if ( pipelines.has( computeNode ) === false ) {
  23114. const dispose = () => {
  23115. computeNode.removeEventListener( 'dispose', dispose );
  23116. pipelines.delete( computeNode );
  23117. bindings.delete( computeNode );
  23118. nodes.delete( computeNode );
  23119. };
  23120. computeNode.addEventListener( 'dispose', dispose );
  23121. //
  23122. const onInitFn = computeNode.onInitFunction;
  23123. if ( onInitFn !== null ) {
  23124. onInitFn.call( computeNode, { renderer: this } );
  23125. }
  23126. }
  23127. nodes.updateForCompute( computeNode );
  23128. bindings.updateForCompute( computeNode );
  23129. const computeBindings = bindings.getForCompute( computeNode );
  23130. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  23131. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  23132. }
  23133. backend.finishCompute( computeNodes );
  23134. //
  23135. nodeFrame.renderId = previousRenderId;
  23136. }
  23137. async computeAsync( computeNodes ) {
  23138. if ( this._initialized === false ) await this.init();
  23139. this.compute( computeNodes );
  23140. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  23141. }
  23142. async hasFeatureAsync( name ) {
  23143. if ( this._initialized === false ) await this.init();
  23144. return this.backend.hasFeature( name );
  23145. }
  23146. hasFeature( name ) {
  23147. if ( this._initialized === false ) {
  23148. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  23149. return false;
  23150. }
  23151. return this.backend.hasFeature( name );
  23152. }
  23153. hasInitialized() {
  23154. return this._initialized;
  23155. }
  23156. async initTextureAsync( texture ) {
  23157. if ( this._initialized === false ) await this.init();
  23158. this._textures.updateTexture( texture );
  23159. }
  23160. initTexture( texture ) {
  23161. if ( this._initialized === false ) {
  23162. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  23163. return false;
  23164. }
  23165. this._textures.updateTexture( texture );
  23166. }
  23167. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  23168. if ( rectangle !== null ) {
  23169. if ( rectangle.isVector2 ) {
  23170. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  23171. } else if ( rectangle.isVector4 ) {
  23172. rectangle = _vector4.copy( rectangle ).floor();
  23173. } else {
  23174. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  23175. return;
  23176. }
  23177. } else {
  23178. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  23179. }
  23180. //
  23181. let renderContext = this._currentRenderContext;
  23182. let renderTarget;
  23183. if ( renderContext !== null ) {
  23184. renderTarget = renderContext.renderTarget;
  23185. } else {
  23186. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  23187. if ( renderTarget !== null ) {
  23188. this._textures.updateRenderTarget( renderTarget );
  23189. renderContext = this._textures.get( renderTarget );
  23190. }
  23191. }
  23192. //
  23193. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  23194. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  23195. }
  23196. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  23197. this._textures.updateTexture( srcTexture );
  23198. this._textures.updateTexture( dstTexture );
  23199. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  23200. }
  23201. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  23202. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  23203. }
  23204. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  23205. if ( object.visible === false ) return;
  23206. const visible = object.layers.test( camera.layers );
  23207. if ( visible ) {
  23208. if ( object.isGroup ) {
  23209. groupOrder = object.renderOrder;
  23210. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  23211. } else if ( object.isLOD ) {
  23212. if ( object.autoUpdate === true ) object.update( camera );
  23213. } else if ( object.isLight ) {
  23214. renderList.pushLight( object );
  23215. } else if ( object.isSprite ) {
  23216. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  23217. if ( this.sortObjects === true ) {
  23218. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  23219. }
  23220. const { geometry, material } = object;
  23221. if ( material.visible ) {
  23222. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  23223. }
  23224. }
  23225. } else if ( object.isLineLoop ) {
  23226. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  23227. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  23228. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  23229. const { geometry, material } = object;
  23230. if ( this.sortObjects === true ) {
  23231. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  23232. _vector4
  23233. .copy( geometry.boundingSphere.center )
  23234. .applyMatrix4( object.matrixWorld )
  23235. .applyMatrix4( _projScreenMatrix );
  23236. }
  23237. if ( Array.isArray( material ) ) {
  23238. const groups = geometry.groups;
  23239. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  23240. const group = groups[ i ];
  23241. const groupMaterial = material[ group.materialIndex ];
  23242. if ( groupMaterial && groupMaterial.visible ) {
  23243. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  23244. }
  23245. }
  23246. } else if ( material.visible ) {
  23247. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  23248. }
  23249. }
  23250. }
  23251. }
  23252. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  23253. const baseRenderList = renderList;
  23254. // replace render list
  23255. renderList = this._renderLists.get( object, camera );
  23256. renderList.begin();
  23257. baseRenderList.pushBundle( {
  23258. bundleGroup: object,
  23259. camera,
  23260. renderList,
  23261. } );
  23262. renderList.finish();
  23263. }
  23264. const children = object.children;
  23265. for ( let i = 0, l = children.length; i < l; i ++ ) {
  23266. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  23267. }
  23268. }
  23269. _renderBundles( bundles, sceneRef, lightsNode ) {
  23270. for ( const bundle of bundles ) {
  23271. this._renderBundle( bundle, sceneRef, lightsNode );
  23272. }
  23273. }
  23274. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  23275. if ( doublePassList.length > 0 ) {
  23276. // render back side
  23277. for ( const { material } of doublePassList ) {
  23278. material.side = BackSide;
  23279. }
  23280. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  23281. // render front side
  23282. for ( const { material } of doublePassList ) {
  23283. material.side = FrontSide;
  23284. }
  23285. this._renderObjects( renderList, camera, scene, lightsNode );
  23286. // restore
  23287. for ( const { material } of doublePassList ) {
  23288. material.side = DoubleSide;
  23289. }
  23290. } else {
  23291. this._renderObjects( renderList, camera, scene, lightsNode );
  23292. }
  23293. }
  23294. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  23295. // process renderable objects
  23296. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  23297. const renderItem = renderList[ i ];
  23298. // @TODO: Add support for multiple materials per object. This will require to extract
  23299. // the material from the renderItem object and pass it with its group data to renderObject().
  23300. const { object, geometry, material, group, clippingContext } = renderItem;
  23301. if ( camera.isArrayCamera ) {
  23302. const cameras = camera.cameras;
  23303. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  23304. const camera2 = cameras[ j ];
  23305. if ( object.layers.test( camera2.layers ) ) {
  23306. const vp = camera2.viewport;
  23307. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  23308. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  23309. const viewportValue = this._currentRenderContext.viewportValue;
  23310. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  23311. viewportValue.minDepth = minDepth;
  23312. viewportValue.maxDepth = maxDepth;
  23313. this.backend.updateViewport( this._currentRenderContext );
  23314. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  23315. }
  23316. }
  23317. } else {
  23318. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  23319. }
  23320. }
  23321. }
  23322. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  23323. let overridePositionNode;
  23324. let overrideColorNode;
  23325. let overrideDepthNode;
  23326. //
  23327. object.onBeforeRender( this, scene, camera, geometry, material, group );
  23328. //
  23329. if ( scene.overrideMaterial !== null ) {
  23330. const overrideMaterial = scene.overrideMaterial;
  23331. if ( material.positionNode && material.positionNode.isNode ) {
  23332. overridePositionNode = overrideMaterial.positionNode;
  23333. overrideMaterial.positionNode = material.positionNode;
  23334. }
  23335. overrideMaterial.alphaTest = material.alphaTest;
  23336. overrideMaterial.alphaMap = material.alphaMap;
  23337. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  23338. if ( overrideMaterial.isShadowNodeMaterial ) {
  23339. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  23340. if ( material.depthNode && material.depthNode.isNode ) {
  23341. overrideDepthNode = overrideMaterial.depthNode;
  23342. overrideMaterial.depthNode = material.depthNode;
  23343. }
  23344. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  23345. overrideColorNode = overrideMaterial.colorNode;
  23346. overrideMaterial.colorNode = material.castShadowNode;
  23347. }
  23348. }
  23349. material = overrideMaterial;
  23350. }
  23351. //
  23352. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  23353. material.side = BackSide;
  23354. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  23355. material.side = FrontSide;
  23356. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  23357. material.side = DoubleSide;
  23358. } else {
  23359. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  23360. }
  23361. //
  23362. if ( overridePositionNode !== undefined ) {
  23363. scene.overrideMaterial.positionNode = overridePositionNode;
  23364. }
  23365. if ( overrideDepthNode !== undefined ) {
  23366. scene.overrideMaterial.depthNode = overrideDepthNode;
  23367. }
  23368. if ( overrideColorNode !== undefined ) {
  23369. scene.overrideMaterial.colorNode = overrideColorNode;
  23370. }
  23371. //
  23372. object.onAfterRender( this, scene, camera, geometry, material, group );
  23373. }
  23374. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  23375. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  23376. renderObject.drawRange = object.geometry.drawRange;
  23377. renderObject.group = group;
  23378. //
  23379. const needsRefresh = this._nodes.needsRefresh( renderObject );
  23380. if ( needsRefresh ) {
  23381. this._nodes.updateBefore( renderObject );
  23382. this._geometries.updateForRender( renderObject );
  23383. this._nodes.updateForRender( renderObject );
  23384. this._bindings.updateForRender( renderObject );
  23385. }
  23386. this._pipelines.updateForRender( renderObject );
  23387. //
  23388. if ( this._currentRenderBundle !== null ) {
  23389. const renderBundleData = this.backend.get( this._currentRenderBundle );
  23390. renderBundleData.renderObjects.push( renderObject );
  23391. renderObject.bundle = this._currentRenderBundle.scene;
  23392. }
  23393. this.backend.draw( renderObject, this.info );
  23394. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  23395. }
  23396. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  23397. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  23398. //
  23399. this._nodes.updateBefore( renderObject );
  23400. this._geometries.updateForRender( renderObject );
  23401. this._nodes.updateForRender( renderObject );
  23402. this._bindings.updateForRender( renderObject );
  23403. this._pipelines.getForRender( renderObject, this._compilationPromises );
  23404. this._nodes.updateAfter( renderObject );
  23405. }
  23406. get compile() {
  23407. return this.compileAsync;
  23408. }
  23409. }
  23410. class Binding {
  23411. constructor( name = '' ) {
  23412. this.name = name;
  23413. this.visibility = 0;
  23414. }
  23415. setVisibility( visibility ) {
  23416. this.visibility |= visibility;
  23417. }
  23418. clone() {
  23419. return Object.assign( new this.constructor(), this );
  23420. }
  23421. }
  23422. function getFloatLength( floatLength ) {
  23423. // ensure chunk size alignment (STD140 layout)
  23424. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  23425. }
  23426. class Buffer extends Binding {
  23427. constructor( name, buffer = null ) {
  23428. super( name );
  23429. this.isBuffer = true;
  23430. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  23431. this._buffer = buffer;
  23432. }
  23433. get byteLength() {
  23434. return getFloatLength( this._buffer.byteLength );
  23435. }
  23436. get buffer() {
  23437. return this._buffer;
  23438. }
  23439. update() {
  23440. return true;
  23441. }
  23442. }
  23443. class UniformBuffer extends Buffer {
  23444. constructor( name, buffer = null ) {
  23445. super( name, buffer );
  23446. this.isUniformBuffer = true;
  23447. }
  23448. }
  23449. let _id$4 = 0;
  23450. class NodeUniformBuffer extends UniformBuffer {
  23451. constructor( nodeUniform, groupNode ) {
  23452. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  23453. this.nodeUniform = nodeUniform;
  23454. this.groupNode = groupNode;
  23455. }
  23456. get buffer() {
  23457. return this.nodeUniform.value;
  23458. }
  23459. }
  23460. class UniformsGroup extends UniformBuffer {
  23461. constructor( name ) {
  23462. super( name );
  23463. this.isUniformsGroup = true;
  23464. this._values = null;
  23465. // the order of uniforms in this array must match the order of uniforms in the shader
  23466. this.uniforms = [];
  23467. }
  23468. addUniform( uniform ) {
  23469. this.uniforms.push( uniform );
  23470. return this;
  23471. }
  23472. removeUniform( uniform ) {
  23473. const index = this.uniforms.indexOf( uniform );
  23474. if ( index !== - 1 ) {
  23475. this.uniforms.splice( index, 1 );
  23476. }
  23477. return this;
  23478. }
  23479. get values() {
  23480. if ( this._values === null ) {
  23481. this._values = Array.from( this.buffer );
  23482. }
  23483. return this._values;
  23484. }
  23485. get buffer() {
  23486. let buffer = this._buffer;
  23487. if ( buffer === null ) {
  23488. const byteLength = this.byteLength;
  23489. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  23490. this._buffer = buffer;
  23491. }
  23492. return buffer;
  23493. }
  23494. get byteLength() {
  23495. let offset = 0; // global buffer offset in bytes
  23496. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  23497. const uniform = this.uniforms[ i ];
  23498. const { boundary, itemSize } = uniform;
  23499. // offset within a single chunk in bytes
  23500. const chunkOffset = offset % GPU_CHUNK_BYTES;
  23501. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  23502. // conformance tests
  23503. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  23504. // check for chunk overflow
  23505. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  23506. } else if ( chunkOffset % boundary !== 0 ) {
  23507. // check for correct alignment
  23508. offset += ( chunkOffset % boundary );
  23509. }
  23510. uniform.offset = ( offset / this.bytesPerElement );
  23511. offset += ( itemSize * this.bytesPerElement );
  23512. }
  23513. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  23514. }
  23515. update() {
  23516. let updated = false;
  23517. for ( const uniform of this.uniforms ) {
  23518. if ( this.updateByType( uniform ) === true ) {
  23519. updated = true;
  23520. }
  23521. }
  23522. return updated;
  23523. }
  23524. updateByType( uniform ) {
  23525. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  23526. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  23527. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  23528. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  23529. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  23530. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  23531. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  23532. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  23533. }
  23534. updateNumber( uniform ) {
  23535. let updated = false;
  23536. const a = this.values;
  23537. const v = uniform.getValue();
  23538. const offset = uniform.offset;
  23539. const type = uniform.getType();
  23540. if ( a[ offset ] !== v ) {
  23541. const b = this._getBufferForType( type );
  23542. b[ offset ] = a[ offset ] = v;
  23543. updated = true;
  23544. }
  23545. return updated;
  23546. }
  23547. updateVector2( uniform ) {
  23548. let updated = false;
  23549. const a = this.values;
  23550. const v = uniform.getValue();
  23551. const offset = uniform.offset;
  23552. const type = uniform.getType();
  23553. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  23554. const b = this._getBufferForType( type );
  23555. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  23556. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  23557. updated = true;
  23558. }
  23559. return updated;
  23560. }
  23561. updateVector3( uniform ) {
  23562. let updated = false;
  23563. const a = this.values;
  23564. const v = uniform.getValue();
  23565. const offset = uniform.offset;
  23566. const type = uniform.getType();
  23567. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  23568. const b = this._getBufferForType( type );
  23569. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  23570. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  23571. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  23572. updated = true;
  23573. }
  23574. return updated;
  23575. }
  23576. updateVector4( uniform ) {
  23577. let updated = false;
  23578. const a = this.values;
  23579. const v = uniform.getValue();
  23580. const offset = uniform.offset;
  23581. const type = uniform.getType();
  23582. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  23583. const b = this._getBufferForType( type );
  23584. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  23585. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  23586. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  23587. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  23588. updated = true;
  23589. }
  23590. return updated;
  23591. }
  23592. updateColor( uniform ) {
  23593. let updated = false;
  23594. const a = this.values;
  23595. const c = uniform.getValue();
  23596. const offset = uniform.offset;
  23597. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  23598. const b = this.buffer;
  23599. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  23600. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  23601. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  23602. updated = true;
  23603. }
  23604. return updated;
  23605. }
  23606. updateMatrix3( uniform ) {
  23607. let updated = false;
  23608. const a = this.values;
  23609. const e = uniform.getValue().elements;
  23610. const offset = uniform.offset;
  23611. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  23612. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  23613. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  23614. const b = this.buffer;
  23615. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  23616. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  23617. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  23618. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  23619. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  23620. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  23621. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  23622. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  23623. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  23624. updated = true;
  23625. }
  23626. return updated;
  23627. }
  23628. updateMatrix4( uniform ) {
  23629. let updated = false;
  23630. const a = this.values;
  23631. const e = uniform.getValue().elements;
  23632. const offset = uniform.offset;
  23633. if ( arraysEqual( a, e, offset ) === false ) {
  23634. const b = this.buffer;
  23635. b.set( e, offset );
  23636. setArray( a, e, offset );
  23637. updated = true;
  23638. }
  23639. return updated;
  23640. }
  23641. _getBufferForType( type ) {
  23642. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  23643. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  23644. return this.buffer;
  23645. }
  23646. }
  23647. function setArray( a, b, offset ) {
  23648. for ( let i = 0, l = b.length; i < l; i ++ ) {
  23649. a[ offset + i ] = b[ i ];
  23650. }
  23651. }
  23652. function arraysEqual( a, b, offset ) {
  23653. for ( let i = 0, l = b.length; i < l; i ++ ) {
  23654. if ( a[ offset + i ] !== b[ i ] ) return false;
  23655. }
  23656. return true;
  23657. }
  23658. let _id$3 = 0;
  23659. class NodeUniformsGroup extends UniformsGroup {
  23660. constructor( name, groupNode ) {
  23661. super( name );
  23662. this.id = _id$3 ++;
  23663. this.groupNode = groupNode;
  23664. this.isNodeUniformsGroup = true;
  23665. }
  23666. getNodes() {
  23667. const nodes = [];
  23668. for ( const uniform of this.uniforms ) {
  23669. const node = uniform.nodeUniform.node;
  23670. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  23671. nodes.push( node );
  23672. }
  23673. return nodes;
  23674. }
  23675. }
  23676. let _id$2 = 0;
  23677. class SampledTexture extends Binding {
  23678. constructor( name, texture ) {
  23679. super( name );
  23680. this.id = _id$2 ++;
  23681. this.texture = texture;
  23682. this.version = texture ? texture.version : 0;
  23683. this.store = false;
  23684. this.generation = null;
  23685. this.isSampledTexture = true;
  23686. }
  23687. needsBindingsUpdate( generation ) {
  23688. const { texture } = this;
  23689. if ( generation !== this.generation ) {
  23690. this.generation = generation;
  23691. return true;
  23692. }
  23693. return texture.isVideoTexture;
  23694. }
  23695. update() {
  23696. const { texture, version } = this;
  23697. if ( version !== texture.version ) {
  23698. this.version = texture.version;
  23699. return true;
  23700. }
  23701. return false;
  23702. }
  23703. }
  23704. class NodeSampledTexture extends SampledTexture {
  23705. constructor( name, textureNode, groupNode, access = null ) {
  23706. super( name, textureNode ? textureNode.value : null );
  23707. this.textureNode = textureNode;
  23708. this.groupNode = groupNode;
  23709. this.access = access;
  23710. }
  23711. needsBindingsUpdate( generation ) {
  23712. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  23713. }
  23714. update() {
  23715. const { textureNode } = this;
  23716. if ( this.texture !== textureNode.value ) {
  23717. this.texture = textureNode.value;
  23718. return true;
  23719. }
  23720. return super.update();
  23721. }
  23722. }
  23723. class NodeSampledCubeTexture extends NodeSampledTexture {
  23724. constructor( name, textureNode, groupNode, access ) {
  23725. super( name, textureNode, groupNode, access );
  23726. this.isSampledCubeTexture = true;
  23727. }
  23728. }
  23729. class NodeSampledTexture3D extends NodeSampledTexture {
  23730. constructor( name, textureNode, groupNode, access ) {
  23731. super( name, textureNode, groupNode, access );
  23732. this.isSampledTexture3D = true;
  23733. }
  23734. }
  23735. const glslMethods = {
  23736. atan2: 'atan',
  23737. textureDimensions: 'textureSize',
  23738. equals: 'equal'
  23739. };
  23740. const precisionLib = {
  23741. low: 'lowp',
  23742. medium: 'mediump',
  23743. high: 'highp'
  23744. };
  23745. const supports$1 = {
  23746. swizzleAssign: true,
  23747. storageBuffer: false
  23748. };
  23749. const defaultPrecisions = `
  23750. precision highp float;
  23751. precision highp int;
  23752. precision highp sampler2D;
  23753. precision highp sampler3D;
  23754. precision highp samplerCube;
  23755. precision highp sampler2DArray;
  23756. precision highp usampler2D;
  23757. precision highp usampler3D;
  23758. precision highp usamplerCube;
  23759. precision highp usampler2DArray;
  23760. precision highp isampler2D;
  23761. precision highp isampler3D;
  23762. precision highp isamplerCube;
  23763. precision highp isampler2DArray;
  23764. precision lowp sampler2DShadow;
  23765. `;
  23766. class GLSLNodeBuilder extends NodeBuilder {
  23767. constructor( object, renderer ) {
  23768. super( object, renderer, new GLSLNodeParser() );
  23769. this.uniformGroups = {};
  23770. this.transforms = [];
  23771. this.extensions = {};
  23772. this.builtins = { vertex: [], fragment: [], compute: [] };
  23773. this.useComparisonMethod = true;
  23774. }
  23775. needsToWorkingColorSpace( texture ) {
  23776. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  23777. }
  23778. getMethod( method ) {
  23779. return glslMethods[ method ] || method;
  23780. }
  23781. getOutputStructName() {
  23782. return '';
  23783. }
  23784. buildFunctionCode( shaderNode ) {
  23785. const layout = shaderNode.layout;
  23786. const flowData = this.flowShaderNode( shaderNode );
  23787. const parameters = [];
  23788. for ( const input of layout.inputs ) {
  23789. parameters.push( this.getType( input.type ) + ' ' + input.name );
  23790. }
  23791. //
  23792. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  23793. ${ flowData.vars }
  23794. ${ flowData.code }
  23795. return ${ flowData.result };
  23796. }`;
  23797. //
  23798. return code;
  23799. }
  23800. setupPBO( storageBufferNode ) {
  23801. const attribute = storageBufferNode.value;
  23802. if ( attribute.pbo === undefined ) {
  23803. const originalArray = attribute.array;
  23804. const numElements = attribute.count * attribute.itemSize;
  23805. const { itemSize } = attribute;
  23806. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  23807. let format = isInteger ? RedIntegerFormat : RedFormat;
  23808. if ( itemSize === 2 ) {
  23809. format = isInteger ? RGIntegerFormat : RGFormat;
  23810. } else if ( itemSize === 3 ) {
  23811. format = isInteger ? RGBIntegerFormat : RGBFormat;
  23812. } else if ( itemSize === 4 ) {
  23813. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  23814. }
  23815. const typeMap = {
  23816. Float32Array: FloatType,
  23817. Uint8Array: UnsignedByteType,
  23818. Uint16Array: UnsignedShortType,
  23819. Uint32Array: UnsignedIntType,
  23820. Int8Array: ByteType,
  23821. Int16Array: ShortType,
  23822. Int32Array: IntType,
  23823. Uint8ClampedArray: UnsignedByteType,
  23824. };
  23825. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  23826. let height = Math.ceil( ( numElements / itemSize ) / width );
  23827. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  23828. const newSize = width * height * itemSize;
  23829. const newArray = new originalArray.constructor( newSize );
  23830. newArray.set( originalArray, 0 );
  23831. attribute.array = newArray;
  23832. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  23833. pboTexture.needsUpdate = true;
  23834. pboTexture.isPBOTexture = true;
  23835. const pbo = new TextureNode( pboTexture, null, null );
  23836. pbo.setPrecision( 'high' );
  23837. attribute.pboNode = pbo;
  23838. attribute.pbo = pbo.value;
  23839. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  23840. }
  23841. }
  23842. getPropertyName( node, shaderStage = this.shaderStage ) {
  23843. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  23844. return shaderStage.charAt( 0 ) + '_' + node.name;
  23845. }
  23846. return super.getPropertyName( node, shaderStage );
  23847. }
  23848. generatePBO( storageArrayElementNode ) {
  23849. const { node, indexNode } = storageArrayElementNode;
  23850. const attribute = node.value;
  23851. if ( this.renderer.backend.has( attribute ) ) {
  23852. const attributeData = this.renderer.backend.get( attribute );
  23853. attributeData.pbo = attribute.pbo;
  23854. }
  23855. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  23856. const textureName = this.getPropertyName( nodeUniform );
  23857. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  23858. const indexSnippet = indexNode.build( this, 'uint' );
  23859. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  23860. let propertyName = elementNodeData.propertyName;
  23861. if ( propertyName === undefined ) {
  23862. // property element
  23863. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  23864. propertyName = this.getPropertyName( nodeVar );
  23865. // property size
  23866. const bufferNodeData = this.getDataFromNode( node );
  23867. let propertySizeName = bufferNodeData.propertySizeName;
  23868. if ( propertySizeName === undefined ) {
  23869. propertySizeName = propertyName + 'Size';
  23870. this.getVarFromNode( node, propertySizeName, 'uint' );
  23871. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  23872. bufferNodeData.propertySizeName = propertySizeName;
  23873. }
  23874. //
  23875. const { itemSize } = attribute;
  23876. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  23877. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  23878. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  23879. //
  23880. let prefix = 'vec4';
  23881. if ( attribute.pbo.type === UnsignedIntType ) {
  23882. prefix = 'uvec4';
  23883. } else if ( attribute.pbo.type === IntType ) {
  23884. prefix = 'ivec4';
  23885. }
  23886. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  23887. elementNodeData.propertyName = propertyName;
  23888. }
  23889. return propertyName;
  23890. }
  23891. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  23892. if ( depthSnippet ) {
  23893. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  23894. } else {
  23895. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  23896. }
  23897. }
  23898. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  23899. if ( texture.isDepthTexture ) {
  23900. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  23901. } else {
  23902. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  23903. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  23904. }
  23905. }
  23906. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  23907. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  23908. }
  23909. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  23910. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  23911. }
  23912. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  23913. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  23914. }
  23915. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  23916. if ( shaderStage === 'fragment' ) {
  23917. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  23918. } else {
  23919. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  23920. }
  23921. }
  23922. getVars( shaderStage ) {
  23923. const snippets = [];
  23924. const vars = this.vars[ shaderStage ];
  23925. if ( vars !== undefined ) {
  23926. for ( const variable of vars ) {
  23927. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  23928. }
  23929. }
  23930. return snippets.join( '\n\t' );
  23931. }
  23932. getUniforms( shaderStage ) {
  23933. const uniforms = this.uniforms[ shaderStage ];
  23934. const bindingSnippets = [];
  23935. const uniformGroups = {};
  23936. for ( const uniform of uniforms ) {
  23937. let snippet = null;
  23938. let group = false;
  23939. if ( uniform.type === 'texture' ) {
  23940. const texture = uniform.node.value;
  23941. let typePrefix = '';
  23942. if ( texture.isDataTexture === true ) {
  23943. if ( texture.type === UnsignedIntType ) {
  23944. typePrefix = 'u';
  23945. } else if ( texture.type === IntType ) {
  23946. typePrefix = 'i';
  23947. }
  23948. }
  23949. if ( texture.compareFunction ) {
  23950. snippet = `sampler2DShadow ${ uniform.name };`;
  23951. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23952. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  23953. } else {
  23954. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  23955. }
  23956. } else if ( uniform.type === 'cubeTexture' ) {
  23957. snippet = `samplerCube ${ uniform.name };`;
  23958. } else if ( uniform.type === 'texture3D' ) {
  23959. snippet = `sampler3D ${ uniform.name };`;
  23960. } else if ( uniform.type === 'buffer' ) {
  23961. const bufferNode = uniform.node;
  23962. const bufferType = this.getType( bufferNode.bufferType );
  23963. const bufferCount = bufferNode.bufferCount;
  23964. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  23965. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  23966. } else {
  23967. const vectorType = this.getVectorType( uniform.type );
  23968. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  23969. group = true;
  23970. }
  23971. const precision = uniform.node.precision;
  23972. if ( precision !== null ) {
  23973. snippet = precisionLib[ precision ] + ' ' + snippet;
  23974. }
  23975. if ( group ) {
  23976. snippet = '\t' + snippet;
  23977. const groupName = uniform.groupNode.name;
  23978. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  23979. groupSnippets.push( snippet );
  23980. } else {
  23981. snippet = 'uniform ' + snippet;
  23982. bindingSnippets.push( snippet );
  23983. }
  23984. }
  23985. let output = '';
  23986. for ( const name in uniformGroups ) {
  23987. const groupSnippets = uniformGroups[ name ];
  23988. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  23989. }
  23990. output += bindingSnippets.join( '\n' );
  23991. return output;
  23992. }
  23993. getTypeFromAttribute( attribute ) {
  23994. let nodeType = super.getTypeFromAttribute( attribute );
  23995. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  23996. let dataAttribute = attribute;
  23997. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  23998. const array = dataAttribute.array;
  23999. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  24000. nodeType = nodeType.slice( 1 );
  24001. }
  24002. }
  24003. return nodeType;
  24004. }
  24005. getAttributes( shaderStage ) {
  24006. let snippet = '';
  24007. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  24008. const attributes = this.getAttributesArray();
  24009. let location = 0;
  24010. for ( const attribute of attributes ) {
  24011. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  24012. }
  24013. }
  24014. return snippet;
  24015. }
  24016. getStructMembers( struct ) {
  24017. const snippets = [];
  24018. const members = struct.getMemberTypes();
  24019. for ( let i = 0; i < members.length; i ++ ) {
  24020. const member = members[ i ];
  24021. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  24022. }
  24023. return snippets.join( '\n' );
  24024. }
  24025. getStructs( shaderStage ) {
  24026. const snippets = [];
  24027. const structs = this.structs[ shaderStage ];
  24028. if ( structs.length === 0 ) {
  24029. return 'layout( location = 0 ) out vec4 fragColor;\n';
  24030. }
  24031. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  24032. const struct = structs[ index ];
  24033. let snippet = '\n';
  24034. snippet += this.getStructMembers( struct );
  24035. snippet += '\n';
  24036. snippets.push( snippet );
  24037. }
  24038. return snippets.join( '\n\n' );
  24039. }
  24040. getVaryings( shaderStage ) {
  24041. let snippet = '';
  24042. const varyings = this.varyings;
  24043. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  24044. for ( const varying of varyings ) {
  24045. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  24046. const type = this.getType( varying.type );
  24047. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  24048. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  24049. }
  24050. } else if ( shaderStage === 'fragment' ) {
  24051. for ( const varying of varyings ) {
  24052. if ( varying.needsInterpolation ) {
  24053. const type = this.getType( varying.type );
  24054. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  24055. snippet += `${flat}in ${type} ${varying.name};\n`;
  24056. }
  24057. }
  24058. }
  24059. for ( const builtin of this.builtins[ shaderStage ] ) {
  24060. snippet += `${builtin};\n`;
  24061. }
  24062. return snippet;
  24063. }
  24064. getVertexIndex() {
  24065. return 'uint( gl_VertexID )';
  24066. }
  24067. getInstanceIndex() {
  24068. return 'uint( gl_InstanceID )';
  24069. }
  24070. getInvocationLocalIndex() {
  24071. const workgroupSize = this.object.workgroupSize;
  24072. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  24073. return `uint( gl_InstanceID ) % ${size}u`;
  24074. }
  24075. getDrawIndex() {
  24076. const extensions = this.renderer.backend.extensions;
  24077. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  24078. return 'uint( gl_DrawID )';
  24079. }
  24080. return null;
  24081. }
  24082. getFrontFacing() {
  24083. return 'gl_FrontFacing';
  24084. }
  24085. getFragCoord() {
  24086. return 'gl_FragCoord.xy';
  24087. }
  24088. getFragDepth() {
  24089. return 'gl_FragDepth';
  24090. }
  24091. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  24092. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  24093. if ( map.has( name ) === false ) {
  24094. map.set( name, {
  24095. name,
  24096. behavior
  24097. } );
  24098. }
  24099. }
  24100. getExtensions( shaderStage ) {
  24101. const snippets = [];
  24102. if ( shaderStage === 'vertex' ) {
  24103. const ext = this.renderer.backend.extensions;
  24104. const isBatchedMesh = this.object.isBatchedMesh;
  24105. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  24106. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  24107. }
  24108. }
  24109. const extensions = this.extensions[ shaderStage ];
  24110. if ( extensions !== undefined ) {
  24111. for ( const { name, behavior } of extensions.values() ) {
  24112. snippets.push( `#extension ${name} : ${behavior}` );
  24113. }
  24114. }
  24115. return snippets.join( '\n' );
  24116. }
  24117. getClipDistance() {
  24118. return 'gl_ClipDistance';
  24119. }
  24120. isAvailable( name ) {
  24121. let result = supports$1[ name ];
  24122. if ( result === undefined ) {
  24123. let extensionName;
  24124. result = false;
  24125. switch ( name ) {
  24126. case 'float32Filterable':
  24127. extensionName = 'OES_texture_float_linear';
  24128. break;
  24129. case 'clipDistance':
  24130. extensionName = 'WEBGL_clip_cull_distance';
  24131. break;
  24132. }
  24133. if ( extensionName !== undefined ) {
  24134. const extensions = this.renderer.backend.extensions;
  24135. if ( extensions.has( extensionName ) ) {
  24136. extensions.get( extensionName );
  24137. result = true;
  24138. }
  24139. }
  24140. supports$1[ name ] = result;
  24141. }
  24142. return result;
  24143. }
  24144. isFlipY() {
  24145. return true;
  24146. }
  24147. enableHardwareClipping( planeCount ) {
  24148. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  24149. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  24150. }
  24151. registerTransform( varyingName, attributeNode ) {
  24152. this.transforms.push( { varyingName, attributeNode } );
  24153. }
  24154. getTransforms( /* shaderStage */ ) {
  24155. const transforms = this.transforms;
  24156. let snippet = '';
  24157. for ( let i = 0; i < transforms.length; i ++ ) {
  24158. const transform = transforms[ i ];
  24159. const attributeName = this.getPropertyName( transform.attributeNode );
  24160. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  24161. }
  24162. return snippet;
  24163. }
  24164. _getGLSLUniformStruct( name, vars ) {
  24165. return `
  24166. layout( std140 ) uniform ${name} {
  24167. ${vars}
  24168. };`;
  24169. }
  24170. _getGLSLVertexCode( shaderData ) {
  24171. return `#version 300 es
  24172. ${ this.getSignature() }
  24173. // extensions
  24174. ${shaderData.extensions}
  24175. // precision
  24176. ${ defaultPrecisions }
  24177. // uniforms
  24178. ${shaderData.uniforms}
  24179. // varyings
  24180. ${shaderData.varyings}
  24181. // attributes
  24182. ${shaderData.attributes}
  24183. // codes
  24184. ${shaderData.codes}
  24185. void main() {
  24186. // vars
  24187. ${shaderData.vars}
  24188. // transforms
  24189. ${shaderData.transforms}
  24190. // flow
  24191. ${shaderData.flow}
  24192. gl_PointSize = 1.0;
  24193. }
  24194. `;
  24195. }
  24196. _getGLSLFragmentCode( shaderData ) {
  24197. return `#version 300 es
  24198. ${ this.getSignature() }
  24199. // precision
  24200. ${ defaultPrecisions }
  24201. // uniforms
  24202. ${shaderData.uniforms}
  24203. // varyings
  24204. ${shaderData.varyings}
  24205. // codes
  24206. ${shaderData.codes}
  24207. ${shaderData.structs}
  24208. void main() {
  24209. // vars
  24210. ${shaderData.vars}
  24211. // flow
  24212. ${shaderData.flow}
  24213. }
  24214. `;
  24215. }
  24216. buildCode() {
  24217. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  24218. this.sortBindingGroups();
  24219. for ( const shaderStage in shadersData ) {
  24220. let flow = '// code\n\n';
  24221. flow += this.flowCode[ shaderStage ];
  24222. const flowNodes = this.flowNodes[ shaderStage ];
  24223. const mainNode = flowNodes[ flowNodes.length - 1 ];
  24224. for ( const node of flowNodes ) {
  24225. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  24226. const slotName = node.name;
  24227. if ( slotName ) {
  24228. if ( flow.length > 0 ) flow += '\n';
  24229. flow += `\t// flow -> ${ slotName }\n\t`;
  24230. }
  24231. flow += `${ flowSlotData.code }\n\t`;
  24232. if ( node === mainNode && shaderStage !== 'compute' ) {
  24233. flow += '// result\n\t';
  24234. if ( shaderStage === 'vertex' ) {
  24235. flow += 'gl_Position = ';
  24236. flow += `${ flowSlotData.result };`;
  24237. } else if ( shaderStage === 'fragment' ) {
  24238. if ( ! node.outputNode.isOutputStructNode ) {
  24239. flow += 'fragColor = ';
  24240. flow += `${ flowSlotData.result };`;
  24241. }
  24242. }
  24243. }
  24244. }
  24245. const stageData = shadersData[ shaderStage ];
  24246. stageData.extensions = this.getExtensions( shaderStage );
  24247. stageData.uniforms = this.getUniforms( shaderStage );
  24248. stageData.attributes = this.getAttributes( shaderStage );
  24249. stageData.varyings = this.getVaryings( shaderStage );
  24250. stageData.vars = this.getVars( shaderStage );
  24251. stageData.structs = this.getStructs( shaderStage );
  24252. stageData.codes = this.getCodes( shaderStage );
  24253. stageData.transforms = this.getTransforms( shaderStage );
  24254. stageData.flow = flow;
  24255. }
  24256. if ( this.material !== null ) {
  24257. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  24258. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  24259. } else {
  24260. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  24261. }
  24262. }
  24263. getUniformFromNode( node, type, shaderStage, name = null ) {
  24264. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  24265. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  24266. let uniformGPU = nodeData.uniformGPU;
  24267. if ( uniformGPU === undefined ) {
  24268. const group = node.groupNode;
  24269. const groupName = group.name;
  24270. const bindings = this.getBindGroupArray( groupName, shaderStage );
  24271. if ( type === 'texture' ) {
  24272. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  24273. bindings.push( uniformGPU );
  24274. } else if ( type === 'cubeTexture' ) {
  24275. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  24276. bindings.push( uniformGPU );
  24277. } else if ( type === 'texture3D' ) {
  24278. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  24279. bindings.push( uniformGPU );
  24280. } else if ( type === 'buffer' ) {
  24281. node.name = `NodeBuffer_${ node.id }`;
  24282. uniformNode.name = `buffer${ node.id }`;
  24283. const buffer = new NodeUniformBuffer( node, group );
  24284. buffer.name = node.name;
  24285. bindings.push( buffer );
  24286. uniformGPU = buffer;
  24287. } else {
  24288. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  24289. let uniformsGroup = uniformsStage[ groupName ];
  24290. if ( uniformsGroup === undefined ) {
  24291. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  24292. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  24293. uniformsStage[ groupName ] = uniformsGroup;
  24294. bindings.push( uniformsGroup );
  24295. }
  24296. uniformGPU = this.getNodeUniform( uniformNode, type );
  24297. uniformsGroup.addUniform( uniformGPU );
  24298. }
  24299. nodeData.uniformGPU = uniformGPU;
  24300. }
  24301. return uniformNode;
  24302. }
  24303. }
  24304. let vector2 = null;
  24305. let vector4 = null;
  24306. let color4 = null;
  24307. class Backend {
  24308. constructor( parameters = {} ) {
  24309. this.parameters = Object.assign( {}, parameters );
  24310. this.data = new WeakMap();
  24311. this.renderer = null;
  24312. this.domElement = null;
  24313. }
  24314. async init( renderer ) {
  24315. this.renderer = renderer;
  24316. }
  24317. // render context
  24318. begin( /*renderContext*/ ) { }
  24319. finish( /*renderContext*/ ) { }
  24320. // render object
  24321. draw( /*renderObject, info*/ ) { }
  24322. // program
  24323. createProgram( /*program*/ ) { }
  24324. destroyProgram( /*program*/ ) { }
  24325. // bindings
  24326. createBindings( /*bingGroup, bindings*/ ) { }
  24327. updateBindings( /*bingGroup, bindings*/ ) { }
  24328. // pipeline
  24329. createRenderPipeline( /*renderObject*/ ) { }
  24330. createComputePipeline( /*computeNode, pipeline*/ ) { }
  24331. destroyPipeline( /*pipeline*/ ) { }
  24332. // cache key
  24333. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  24334. getRenderCacheKey( /*renderObject*/ ) { } // return String
  24335. // node builder
  24336. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  24337. // textures
  24338. createSampler( /*texture*/ ) { }
  24339. createDefaultTexture( /*texture*/ ) { }
  24340. createTexture( /*texture*/ ) { }
  24341. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  24342. // attributes
  24343. createAttribute( /*attribute*/ ) { }
  24344. createIndexAttribute( /*attribute*/ ) { }
  24345. updateAttribute( /*attribute*/ ) { }
  24346. destroyAttribute( /*attribute*/ ) { }
  24347. // canvas
  24348. getContext() { }
  24349. updateSize() { }
  24350. // utils
  24351. resolveTimestampAsync( /*renderContext, type*/ ) { }
  24352. hasFeatureAsync( /*name*/ ) { } // return Boolean
  24353. hasFeature( /*name*/ ) { } // return Boolean
  24354. getInstanceCount( renderObject ) {
  24355. const { object, geometry } = renderObject;
  24356. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  24357. }
  24358. getDrawingBufferSize() {
  24359. vector2 = vector2 || new Vector2();
  24360. return this.renderer.getDrawingBufferSize( vector2 );
  24361. }
  24362. getScissor() {
  24363. vector4 = vector4 || new Vector4();
  24364. return this.renderer.getScissor( vector4 );
  24365. }
  24366. setScissorTest( /*boolean*/ ) { }
  24367. getClearColor() {
  24368. const renderer = this.renderer;
  24369. color4 = color4 || new Color4();
  24370. renderer.getClearColor( color4 );
  24371. color4.getRGB( color4, this.renderer.currentColorSpace );
  24372. return color4;
  24373. }
  24374. getDomElement() {
  24375. let domElement = this.domElement;
  24376. if ( domElement === null ) {
  24377. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  24378. // OffscreenCanvas does not have setAttribute, see #22811
  24379. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  24380. this.domElement = domElement;
  24381. }
  24382. return domElement;
  24383. }
  24384. // resource properties
  24385. set( object, value ) {
  24386. this.data.set( object, value );
  24387. }
  24388. get( object ) {
  24389. let map = this.data.get( object );
  24390. if ( map === undefined ) {
  24391. map = {};
  24392. this.data.set( object, map );
  24393. }
  24394. return map;
  24395. }
  24396. has( object ) {
  24397. return this.data.has( object );
  24398. }
  24399. delete( object ) {
  24400. this.data.delete( object );
  24401. }
  24402. dispose() { }
  24403. }
  24404. let _id$1 = 0;
  24405. class DualAttributeData {
  24406. constructor( attributeData, dualBuffer ) {
  24407. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  24408. this.type = attributeData.type;
  24409. this.bufferType = attributeData.bufferType;
  24410. this.pbo = attributeData.pbo;
  24411. this.byteLength = attributeData.byteLength;
  24412. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  24413. this.version = attributeData.version;
  24414. this.isInteger = attributeData.isInteger;
  24415. this.activeBufferIndex = 0;
  24416. this.baseId = attributeData.id;
  24417. }
  24418. get id() {
  24419. return `${ this.baseId }|${ this.activeBufferIndex }`;
  24420. }
  24421. get bufferGPU() {
  24422. return this.buffers[ this.activeBufferIndex ];
  24423. }
  24424. get transformBuffer() {
  24425. return this.buffers[ this.activeBufferIndex ^ 1 ];
  24426. }
  24427. switchBuffers() {
  24428. this.activeBufferIndex ^= 1;
  24429. }
  24430. }
  24431. class WebGLAttributeUtils {
  24432. constructor( backend ) {
  24433. this.backend = backend;
  24434. }
  24435. createAttribute( attribute, bufferType ) {
  24436. const backend = this.backend;
  24437. const { gl } = backend;
  24438. const array = attribute.array;
  24439. const usage = attribute.usage || gl.STATIC_DRAW;
  24440. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  24441. const bufferData = backend.get( bufferAttribute );
  24442. let bufferGPU = bufferData.bufferGPU;
  24443. if ( bufferGPU === undefined ) {
  24444. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  24445. bufferData.bufferGPU = bufferGPU;
  24446. bufferData.bufferType = bufferType;
  24447. bufferData.version = bufferAttribute.version;
  24448. }
  24449. //attribute.onUploadCallback();
  24450. let type;
  24451. if ( array instanceof Float32Array ) {
  24452. type = gl.FLOAT;
  24453. } else if ( array instanceof Uint16Array ) {
  24454. if ( attribute.isFloat16BufferAttribute ) {
  24455. type = gl.HALF_FLOAT;
  24456. } else {
  24457. type = gl.UNSIGNED_SHORT;
  24458. }
  24459. } else if ( array instanceof Int16Array ) {
  24460. type = gl.SHORT;
  24461. } else if ( array instanceof Uint32Array ) {
  24462. type = gl.UNSIGNED_INT;
  24463. } else if ( array instanceof Int32Array ) {
  24464. type = gl.INT;
  24465. } else if ( array instanceof Int8Array ) {
  24466. type = gl.BYTE;
  24467. } else if ( array instanceof Uint8Array ) {
  24468. type = gl.UNSIGNED_BYTE;
  24469. } else if ( array instanceof Uint8ClampedArray ) {
  24470. type = gl.UNSIGNED_BYTE;
  24471. } else {
  24472. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  24473. }
  24474. let attributeData = {
  24475. bufferGPU,
  24476. bufferType,
  24477. type,
  24478. byteLength: array.byteLength,
  24479. bytesPerElement: array.BYTES_PER_ELEMENT,
  24480. version: attribute.version,
  24481. pbo: attribute.pbo,
  24482. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  24483. id: _id$1 ++
  24484. };
  24485. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  24486. // create buffer for tranform feedback use
  24487. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  24488. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  24489. }
  24490. backend.set( attribute, attributeData );
  24491. }
  24492. updateAttribute( attribute ) {
  24493. const backend = this.backend;
  24494. const { gl } = backend;
  24495. const array = attribute.array;
  24496. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  24497. const bufferData = backend.get( bufferAttribute );
  24498. const bufferType = bufferData.bufferType;
  24499. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  24500. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  24501. if ( updateRanges.length === 0 ) {
  24502. // Not using update ranges
  24503. gl.bufferSubData( bufferType, 0, array );
  24504. } else {
  24505. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  24506. const range = updateRanges[ i ];
  24507. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  24508. array, range.start, range.count );
  24509. }
  24510. bufferAttribute.clearUpdateRanges();
  24511. }
  24512. gl.bindBuffer( bufferType, null );
  24513. bufferData.version = bufferAttribute.version;
  24514. }
  24515. destroyAttribute( attribute ) {
  24516. const backend = this.backend;
  24517. const { gl } = backend;
  24518. if ( attribute.isInterleavedBufferAttribute ) {
  24519. backend.delete( attribute.data );
  24520. }
  24521. const attributeData = backend.get( attribute );
  24522. gl.deleteBuffer( attributeData.bufferGPU );
  24523. backend.delete( attribute );
  24524. }
  24525. async getArrayBufferAsync( attribute ) {
  24526. const backend = this.backend;
  24527. const { gl } = backend;
  24528. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  24529. const { bufferGPU } = backend.get( bufferAttribute );
  24530. const array = attribute.array;
  24531. const byteLength = array.byteLength;
  24532. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  24533. const writeBuffer = gl.createBuffer();
  24534. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  24535. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  24536. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  24537. await backend.utils._clientWaitAsync();
  24538. const dstBuffer = new attribute.array.constructor( array.length );
  24539. // Ensure the buffer is bound before reading
  24540. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  24541. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  24542. gl.deleteBuffer( writeBuffer );
  24543. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  24544. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  24545. return dstBuffer.buffer;
  24546. }
  24547. _createBuffer( gl, bufferType, array, usage ) {
  24548. const bufferGPU = gl.createBuffer();
  24549. gl.bindBuffer( bufferType, bufferGPU );
  24550. gl.bufferData( bufferType, array, usage );
  24551. gl.bindBuffer( bufferType, null );
  24552. return bufferGPU;
  24553. }
  24554. }
  24555. let initialized$1 = false, equationToGL, factorToGL;
  24556. class WebGLState {
  24557. constructor( backend ) {
  24558. this.backend = backend;
  24559. this.gl = this.backend.gl;
  24560. this.enabled = {};
  24561. this.currentFlipSided = null;
  24562. this.currentCullFace = null;
  24563. this.currentProgram = null;
  24564. this.currentBlendingEnabled = false;
  24565. this.currentBlending = null;
  24566. this.currentBlendSrc = null;
  24567. this.currentBlendDst = null;
  24568. this.currentBlendSrcAlpha = null;
  24569. this.currentBlendDstAlpha = null;
  24570. this.currentPremultipledAlpha = null;
  24571. this.currentPolygonOffsetFactor = null;
  24572. this.currentPolygonOffsetUnits = null;
  24573. this.currentColorMask = null;
  24574. this.currentDepthFunc = null;
  24575. this.currentDepthMask = null;
  24576. this.currentStencilFunc = null;
  24577. this.currentStencilRef = null;
  24578. this.currentStencilFuncMask = null;
  24579. this.currentStencilFail = null;
  24580. this.currentStencilZFail = null;
  24581. this.currentStencilZPass = null;
  24582. this.currentStencilMask = null;
  24583. this.currentLineWidth = null;
  24584. this.currentClippingPlanes = 0;
  24585. this.currentBoundFramebuffers = {};
  24586. this.currentDrawbuffers = new WeakMap();
  24587. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  24588. this.currentTextureSlot = null;
  24589. this.currentBoundTextures = {};
  24590. this.currentBoundBufferBases = {};
  24591. if ( initialized$1 === false ) {
  24592. this._init( this.gl );
  24593. initialized$1 = true;
  24594. }
  24595. }
  24596. _init( gl ) {
  24597. // Store only WebGL constants here.
  24598. equationToGL = {
  24599. [ AddEquation ]: gl.FUNC_ADD,
  24600. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  24601. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  24602. };
  24603. factorToGL = {
  24604. [ ZeroFactor ]: gl.ZERO,
  24605. [ OneFactor ]: gl.ONE,
  24606. [ SrcColorFactor ]: gl.SRC_COLOR,
  24607. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  24608. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  24609. [ DstColorFactor ]: gl.DST_COLOR,
  24610. [ DstAlphaFactor ]: gl.DST_ALPHA,
  24611. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  24612. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  24613. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  24614. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  24615. };
  24616. }
  24617. enable( id ) {
  24618. const { enabled } = this;
  24619. if ( enabled[ id ] !== true ) {
  24620. this.gl.enable( id );
  24621. enabled[ id ] = true;
  24622. }
  24623. }
  24624. disable( id ) {
  24625. const { enabled } = this;
  24626. if ( enabled[ id ] !== false ) {
  24627. this.gl.disable( id );
  24628. enabled[ id ] = false;
  24629. }
  24630. }
  24631. setFlipSided( flipSided ) {
  24632. if ( this.currentFlipSided !== flipSided ) {
  24633. const { gl } = this;
  24634. if ( flipSided ) {
  24635. gl.frontFace( gl.CW );
  24636. } else {
  24637. gl.frontFace( gl.CCW );
  24638. }
  24639. this.currentFlipSided = flipSided;
  24640. }
  24641. }
  24642. setCullFace( cullFace ) {
  24643. const { gl } = this;
  24644. if ( cullFace !== CullFaceNone ) {
  24645. this.enable( gl.CULL_FACE );
  24646. if ( cullFace !== this.currentCullFace ) {
  24647. if ( cullFace === CullFaceBack ) {
  24648. gl.cullFace( gl.BACK );
  24649. } else if ( cullFace === CullFaceFront ) {
  24650. gl.cullFace( gl.FRONT );
  24651. } else {
  24652. gl.cullFace( gl.FRONT_AND_BACK );
  24653. }
  24654. }
  24655. } else {
  24656. this.disable( gl.CULL_FACE );
  24657. }
  24658. this.currentCullFace = cullFace;
  24659. }
  24660. setLineWidth( width ) {
  24661. const { currentLineWidth, gl } = this;
  24662. if ( width !== currentLineWidth ) {
  24663. gl.lineWidth( width );
  24664. this.currentLineWidth = width;
  24665. }
  24666. }
  24667. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  24668. const { gl } = this;
  24669. if ( blending === NoBlending ) {
  24670. if ( this.currentBlendingEnabled === true ) {
  24671. this.disable( gl.BLEND );
  24672. this.currentBlendingEnabled = false;
  24673. }
  24674. return;
  24675. }
  24676. if ( this.currentBlendingEnabled === false ) {
  24677. this.enable( gl.BLEND );
  24678. this.currentBlendingEnabled = true;
  24679. }
  24680. if ( blending !== CustomBlending ) {
  24681. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  24682. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  24683. gl.blendEquation( gl.FUNC_ADD );
  24684. this.currentBlendEquation = AddEquation;
  24685. this.currentBlendEquationAlpha = AddEquation;
  24686. }
  24687. if ( premultipliedAlpha ) {
  24688. switch ( blending ) {
  24689. case NormalBlending:
  24690. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  24691. break;
  24692. case AdditiveBlending:
  24693. gl.blendFunc( gl.ONE, gl.ONE );
  24694. break;
  24695. case SubtractiveBlending:
  24696. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  24697. break;
  24698. case MultiplyBlending:
  24699. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  24700. break;
  24701. default:
  24702. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  24703. break;
  24704. }
  24705. } else {
  24706. switch ( blending ) {
  24707. case NormalBlending:
  24708. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  24709. break;
  24710. case AdditiveBlending:
  24711. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  24712. break;
  24713. case SubtractiveBlending:
  24714. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  24715. break;
  24716. case MultiplyBlending:
  24717. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  24718. break;
  24719. default:
  24720. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  24721. break;
  24722. }
  24723. }
  24724. this.currentBlendSrc = null;
  24725. this.currentBlendDst = null;
  24726. this.currentBlendSrcAlpha = null;
  24727. this.currentBlendDstAlpha = null;
  24728. this.currentBlending = blending;
  24729. this.currentPremultipledAlpha = premultipliedAlpha;
  24730. }
  24731. return;
  24732. }
  24733. // custom blending
  24734. blendEquationAlpha = blendEquationAlpha || blendEquation;
  24735. blendSrcAlpha = blendSrcAlpha || blendSrc;
  24736. blendDstAlpha = blendDstAlpha || blendDst;
  24737. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  24738. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  24739. this.currentBlendEquation = blendEquation;
  24740. this.currentBlendEquationAlpha = blendEquationAlpha;
  24741. }
  24742. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  24743. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  24744. this.currentBlendSrc = blendSrc;
  24745. this.currentBlendDst = blendDst;
  24746. this.currentBlendSrcAlpha = blendSrcAlpha;
  24747. this.currentBlendDstAlpha = blendDstAlpha;
  24748. }
  24749. this.currentBlending = blending;
  24750. this.currentPremultipledAlpha = false;
  24751. }
  24752. setColorMask( colorMask ) {
  24753. if ( this.currentColorMask !== colorMask ) {
  24754. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  24755. this.currentColorMask = colorMask;
  24756. }
  24757. }
  24758. setDepthTest( depthTest ) {
  24759. const { gl } = this;
  24760. if ( depthTest ) {
  24761. this.enable( gl.DEPTH_TEST );
  24762. } else {
  24763. this.disable( gl.DEPTH_TEST );
  24764. }
  24765. }
  24766. setDepthMask( depthMask ) {
  24767. if ( this.currentDepthMask !== depthMask ) {
  24768. this.gl.depthMask( depthMask );
  24769. this.currentDepthMask = depthMask;
  24770. }
  24771. }
  24772. setDepthFunc( depthFunc ) {
  24773. if ( this.currentDepthFunc !== depthFunc ) {
  24774. const { gl } = this;
  24775. switch ( depthFunc ) {
  24776. case NeverDepth:
  24777. gl.depthFunc( gl.NEVER );
  24778. break;
  24779. case AlwaysDepth:
  24780. gl.depthFunc( gl.ALWAYS );
  24781. break;
  24782. case LessDepth:
  24783. gl.depthFunc( gl.LESS );
  24784. break;
  24785. case LessEqualDepth:
  24786. gl.depthFunc( gl.LEQUAL );
  24787. break;
  24788. case EqualDepth:
  24789. gl.depthFunc( gl.EQUAL );
  24790. break;
  24791. case GreaterEqualDepth:
  24792. gl.depthFunc( gl.GEQUAL );
  24793. break;
  24794. case GreaterDepth:
  24795. gl.depthFunc( gl.GREATER );
  24796. break;
  24797. case NotEqualDepth:
  24798. gl.depthFunc( gl.NOTEQUAL );
  24799. break;
  24800. default:
  24801. gl.depthFunc( gl.LEQUAL );
  24802. }
  24803. this.currentDepthFunc = depthFunc;
  24804. }
  24805. }
  24806. setStencilTest( stencilTest ) {
  24807. const { gl } = this;
  24808. if ( stencilTest ) {
  24809. this.enable( gl.STENCIL_TEST );
  24810. } else {
  24811. this.disable( gl.STENCIL_TEST );
  24812. }
  24813. }
  24814. setStencilMask( stencilMask ) {
  24815. if ( this.currentStencilMask !== stencilMask ) {
  24816. this.gl.stencilMask( stencilMask );
  24817. this.currentStencilMask = stencilMask;
  24818. }
  24819. }
  24820. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  24821. if ( this.currentStencilFunc !== stencilFunc ||
  24822. this.currentStencilRef !== stencilRef ||
  24823. this.currentStencilFuncMask !== stencilMask ) {
  24824. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  24825. this.currentStencilFunc = stencilFunc;
  24826. this.currentStencilRef = stencilRef;
  24827. this.currentStencilFuncMask = stencilMask;
  24828. }
  24829. }
  24830. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  24831. if ( this.currentStencilFail !== stencilFail ||
  24832. this.currentStencilZFail !== stencilZFail ||
  24833. this.currentStencilZPass !== stencilZPass ) {
  24834. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  24835. this.currentStencilFail = stencilFail;
  24836. this.currentStencilZFail = stencilZFail;
  24837. this.currentStencilZPass = stencilZPass;
  24838. }
  24839. }
  24840. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  24841. const { gl } = this;
  24842. material.side === DoubleSide
  24843. ? this.disable( gl.CULL_FACE )
  24844. : this.enable( gl.CULL_FACE );
  24845. let flipSided = ( material.side === BackSide );
  24846. if ( frontFaceCW ) flipSided = ! flipSided;
  24847. this.setFlipSided( flipSided );
  24848. ( material.blending === NormalBlending && material.transparent === false )
  24849. ? this.setBlending( NoBlending )
  24850. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  24851. this.setDepthFunc( material.depthFunc );
  24852. this.setDepthTest( material.depthTest );
  24853. this.setDepthMask( material.depthWrite );
  24854. this.setColorMask( material.colorWrite );
  24855. const stencilWrite = material.stencilWrite;
  24856. this.setStencilTest( stencilWrite );
  24857. if ( stencilWrite ) {
  24858. this.setStencilMask( material.stencilWriteMask );
  24859. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  24860. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  24861. }
  24862. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  24863. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  24864. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  24865. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  24866. if ( hardwareClippingPlanes > 0 ) {
  24867. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  24868. const CLIP_DISTANCE0_WEBGL = 0x3000;
  24869. for ( let i = 0; i < 8; i ++ ) {
  24870. if ( i < hardwareClippingPlanes ) {
  24871. this.enable( CLIP_DISTANCE0_WEBGL + i );
  24872. } else {
  24873. this.disable( CLIP_DISTANCE0_WEBGL + i );
  24874. }
  24875. }
  24876. }
  24877. }
  24878. }
  24879. setPolygonOffset( polygonOffset, factor, units ) {
  24880. const { gl } = this;
  24881. if ( polygonOffset ) {
  24882. this.enable( gl.POLYGON_OFFSET_FILL );
  24883. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  24884. gl.polygonOffset( factor, units );
  24885. this.currentPolygonOffsetFactor = factor;
  24886. this.currentPolygonOffsetUnits = units;
  24887. }
  24888. } else {
  24889. this.disable( gl.POLYGON_OFFSET_FILL );
  24890. }
  24891. }
  24892. useProgram( program ) {
  24893. if ( this.currentProgram !== program ) {
  24894. this.gl.useProgram( program );
  24895. this.currentProgram = program;
  24896. return true;
  24897. }
  24898. return false;
  24899. }
  24900. // framebuffer
  24901. bindFramebuffer( target, framebuffer ) {
  24902. const { gl, currentBoundFramebuffers } = this;
  24903. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  24904. gl.bindFramebuffer( target, framebuffer );
  24905. currentBoundFramebuffers[ target ] = framebuffer;
  24906. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  24907. if ( target === gl.DRAW_FRAMEBUFFER ) {
  24908. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  24909. }
  24910. if ( target === gl.FRAMEBUFFER ) {
  24911. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  24912. }
  24913. return true;
  24914. }
  24915. return false;
  24916. }
  24917. drawBuffers( renderContext, framebuffer ) {
  24918. const { gl } = this;
  24919. let drawBuffers = [];
  24920. let needsUpdate = false;
  24921. if ( renderContext.textures !== null ) {
  24922. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  24923. if ( drawBuffers === undefined ) {
  24924. drawBuffers = [];
  24925. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  24926. }
  24927. const textures = renderContext.textures;
  24928. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  24929. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  24930. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  24931. }
  24932. drawBuffers.length = textures.length;
  24933. needsUpdate = true;
  24934. }
  24935. } else {
  24936. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  24937. drawBuffers[ 0 ] = gl.BACK;
  24938. needsUpdate = true;
  24939. }
  24940. }
  24941. if ( needsUpdate ) {
  24942. gl.drawBuffers( drawBuffers );
  24943. }
  24944. }
  24945. // texture
  24946. activeTexture( webglSlot ) {
  24947. const { gl, currentTextureSlot, maxTextures } = this;
  24948. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24949. if ( currentTextureSlot !== webglSlot ) {
  24950. gl.activeTexture( webglSlot );
  24951. this.currentTextureSlot = webglSlot;
  24952. }
  24953. }
  24954. bindTexture( webglType, webglTexture, webglSlot ) {
  24955. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  24956. if ( webglSlot === undefined ) {
  24957. if ( currentTextureSlot === null ) {
  24958. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24959. } else {
  24960. webglSlot = currentTextureSlot;
  24961. }
  24962. }
  24963. let boundTexture = currentBoundTextures[ webglSlot ];
  24964. if ( boundTexture === undefined ) {
  24965. boundTexture = { type: undefined, texture: undefined };
  24966. currentBoundTextures[ webglSlot ] = boundTexture;
  24967. }
  24968. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  24969. if ( currentTextureSlot !== webglSlot ) {
  24970. gl.activeTexture( webglSlot );
  24971. this.currentTextureSlot = webglSlot;
  24972. }
  24973. gl.bindTexture( webglType, webglTexture );
  24974. boundTexture.type = webglType;
  24975. boundTexture.texture = webglTexture;
  24976. }
  24977. }
  24978. bindBufferBase( target, index, buffer ) {
  24979. const { gl } = this;
  24980. const key = `${target}-${index}`;
  24981. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  24982. gl.bindBufferBase( target, index, buffer );
  24983. this.currentBoundBufferBases[ key ] = buffer;
  24984. return true;
  24985. }
  24986. return false;
  24987. }
  24988. unbindTexture() {
  24989. const { gl, currentTextureSlot, currentBoundTextures } = this;
  24990. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  24991. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  24992. gl.bindTexture( boundTexture.type, null );
  24993. boundTexture.type = undefined;
  24994. boundTexture.texture = undefined;
  24995. }
  24996. }
  24997. }
  24998. class WebGLUtils {
  24999. constructor( backend ) {
  25000. this.backend = backend;
  25001. this.gl = this.backend.gl;
  25002. this.extensions = backend.extensions;
  25003. }
  25004. convert( p, colorSpace = NoColorSpace ) {
  25005. const { gl, extensions } = this;
  25006. let extension;
  25007. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  25008. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  25009. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  25010. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  25011. if ( p === ByteType ) return gl.BYTE;
  25012. if ( p === ShortType ) return gl.SHORT;
  25013. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  25014. if ( p === IntType ) return gl.INT;
  25015. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  25016. if ( p === FloatType ) return gl.FLOAT;
  25017. if ( p === HalfFloatType ) {
  25018. return gl.HALF_FLOAT;
  25019. }
  25020. if ( p === AlphaFormat ) return gl.ALPHA;
  25021. if ( p === RGBFormat ) return gl.RGB;
  25022. if ( p === RGBAFormat ) return gl.RGBA;
  25023. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  25024. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  25025. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  25026. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  25027. // WebGL2 formats.
  25028. if ( p === RedFormat ) return gl.RED;
  25029. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  25030. if ( p === RGFormat ) return gl.RG;
  25031. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  25032. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  25033. // S3TC
  25034. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  25035. if ( colorSpace === SRGBColorSpace ) {
  25036. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  25037. if ( extension !== null ) {
  25038. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  25039. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  25040. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  25041. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  25042. } else {
  25043. return null;
  25044. }
  25045. } else {
  25046. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  25047. if ( extension !== null ) {
  25048. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  25049. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  25050. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  25051. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  25052. } else {
  25053. return null;
  25054. }
  25055. }
  25056. }
  25057. // PVRTC
  25058. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  25059. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  25060. if ( extension !== null ) {
  25061. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  25062. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  25063. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  25064. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  25065. } else {
  25066. return null;
  25067. }
  25068. }
  25069. // ETC
  25070. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  25071. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  25072. if ( extension !== null ) {
  25073. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  25074. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  25075. } else {
  25076. return null;
  25077. }
  25078. }
  25079. // ASTC
  25080. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  25081. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  25082. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  25083. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  25084. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  25085. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  25086. if ( extension !== null ) {
  25087. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  25088. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  25089. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  25090. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  25091. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  25092. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  25093. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  25094. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  25095. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  25096. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  25097. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  25098. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  25099. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  25100. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  25101. } else {
  25102. return null;
  25103. }
  25104. }
  25105. // BPTC
  25106. if ( p === RGBA_BPTC_Format ) {
  25107. extension = extensions.get( 'EXT_texture_compression_bptc' );
  25108. if ( extension !== null ) {
  25109. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  25110. } else {
  25111. return null;
  25112. }
  25113. }
  25114. // RGTC
  25115. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  25116. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  25117. if ( extension !== null ) {
  25118. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  25119. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  25120. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  25121. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  25122. } else {
  25123. return null;
  25124. }
  25125. }
  25126. //
  25127. if ( p === UnsignedInt248Type ) {
  25128. return gl.UNSIGNED_INT_24_8;
  25129. }
  25130. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  25131. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  25132. }
  25133. _clientWaitAsync() {
  25134. const { gl } = this;
  25135. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  25136. gl.flush();
  25137. return new Promise( ( resolve, reject ) => {
  25138. function test() {
  25139. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  25140. if ( res === gl.WAIT_FAILED ) {
  25141. gl.deleteSync( sync );
  25142. reject();
  25143. return;
  25144. }
  25145. if ( res === gl.TIMEOUT_EXPIRED ) {
  25146. requestAnimationFrame( test );
  25147. return;
  25148. }
  25149. gl.deleteSync( sync );
  25150. resolve();
  25151. }
  25152. test();
  25153. } );
  25154. }
  25155. }
  25156. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  25157. class WebGLTextureUtils {
  25158. constructor( backend ) {
  25159. this.backend = backend;
  25160. this.gl = backend.gl;
  25161. this.extensions = backend.extensions;
  25162. this.defaultTextures = {};
  25163. if ( initialized === false ) {
  25164. this._init( this.gl );
  25165. initialized = true;
  25166. }
  25167. }
  25168. _init( gl ) {
  25169. // Store only WebGL constants here.
  25170. wrappingToGL = {
  25171. [ RepeatWrapping ]: gl.REPEAT,
  25172. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  25173. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  25174. };
  25175. filterToGL = {
  25176. [ NearestFilter ]: gl.NEAREST,
  25177. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  25178. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  25179. [ LinearFilter ]: gl.LINEAR,
  25180. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  25181. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  25182. };
  25183. compareToGL = {
  25184. [ NeverCompare ]: gl.NEVER,
  25185. [ AlwaysCompare ]: gl.ALWAYS,
  25186. [ LessCompare ]: gl.LESS,
  25187. [ LessEqualCompare ]: gl.LEQUAL,
  25188. [ EqualCompare ]: gl.EQUAL,
  25189. [ GreaterEqualCompare ]: gl.GEQUAL,
  25190. [ GreaterCompare ]: gl.GREATER,
  25191. [ NotEqualCompare ]: gl.NOTEQUAL
  25192. };
  25193. }
  25194. filterFallback( f ) {
  25195. const { gl } = this;
  25196. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  25197. return gl.NEAREST;
  25198. }
  25199. return gl.LINEAR;
  25200. }
  25201. getGLTextureType( texture ) {
  25202. const { gl } = this;
  25203. let glTextureType;
  25204. if ( texture.isCubeTexture === true ) {
  25205. glTextureType = gl.TEXTURE_CUBE_MAP;
  25206. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  25207. glTextureType = gl.TEXTURE_2D_ARRAY;
  25208. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  25209. glTextureType = gl.TEXTURE_3D;
  25210. } else {
  25211. glTextureType = gl.TEXTURE_2D;
  25212. }
  25213. return glTextureType;
  25214. }
  25215. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  25216. const { gl, extensions } = this;
  25217. if ( internalFormatName !== null ) {
  25218. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  25219. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  25220. }
  25221. let internalFormat = glFormat;
  25222. if ( glFormat === gl.RED ) {
  25223. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  25224. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  25225. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  25226. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  25227. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  25228. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  25229. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  25230. if ( glType === gl.INT ) internalFormat = gl.R32I;
  25231. }
  25232. if ( glFormat === gl.RED_INTEGER ) {
  25233. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  25234. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  25235. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  25236. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  25237. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  25238. if ( glType === gl.INT ) internalFormat = gl.R32I;
  25239. }
  25240. if ( glFormat === gl.RG ) {
  25241. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  25242. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  25243. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  25244. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  25245. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  25246. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  25247. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  25248. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  25249. }
  25250. if ( glFormat === gl.RG_INTEGER ) {
  25251. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  25252. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  25253. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  25254. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  25255. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  25256. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  25257. }
  25258. if ( glFormat === gl.RGB ) {
  25259. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  25260. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  25261. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  25262. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  25263. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  25264. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  25265. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  25266. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  25267. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  25268. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  25269. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  25270. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  25271. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  25272. }
  25273. if ( glFormat === gl.RGB_INTEGER ) {
  25274. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  25275. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  25276. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  25277. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  25278. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  25279. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  25280. }
  25281. if ( glFormat === gl.RGBA ) {
  25282. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  25283. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  25284. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  25285. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  25286. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  25287. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  25288. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  25289. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  25290. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  25291. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  25292. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  25293. }
  25294. if ( glFormat === gl.RGBA_INTEGER ) {
  25295. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  25296. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  25297. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  25298. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  25299. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  25300. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  25301. }
  25302. if ( glFormat === gl.DEPTH_COMPONENT ) {
  25303. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  25304. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  25305. }
  25306. if ( glFormat === gl.DEPTH_STENCIL ) {
  25307. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  25308. }
  25309. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  25310. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  25311. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  25312. extensions.get( 'EXT_color_buffer_float' );
  25313. }
  25314. return internalFormat;
  25315. }
  25316. setTextureParameters( textureType, texture ) {
  25317. const { gl, extensions, backend } = this;
  25318. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  25319. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  25320. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  25321. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  25322. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  25323. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  25324. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  25325. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  25326. }
  25327. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  25328. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  25329. // follow WebGPU backend mapping for texture filtering
  25330. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  25331. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  25332. if ( texture.compareFunction ) {
  25333. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  25334. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  25335. }
  25336. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  25337. if ( texture.magFilter === NearestFilter ) return;
  25338. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  25339. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  25340. if ( texture.anisotropy > 1 ) {
  25341. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  25342. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  25343. }
  25344. }
  25345. }
  25346. createDefaultTexture( texture ) {
  25347. const { gl, backend, defaultTextures } = this;
  25348. const glTextureType = this.getGLTextureType( texture );
  25349. let textureGPU = defaultTextures[ glTextureType ];
  25350. if ( textureGPU === undefined ) {
  25351. textureGPU = gl.createTexture();
  25352. backend.state.bindTexture( glTextureType, textureGPU );
  25353. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  25354. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  25355. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  25356. defaultTextures[ glTextureType ] = textureGPU;
  25357. }
  25358. backend.set( texture, {
  25359. textureGPU,
  25360. glTextureType,
  25361. isDefault: true
  25362. } );
  25363. }
  25364. createTexture( texture, options ) {
  25365. const { gl, backend } = this;
  25366. const { levels, width, height, depth } = options;
  25367. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  25368. const glType = backend.utils.convert( texture.type );
  25369. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  25370. const textureGPU = gl.createTexture();
  25371. const glTextureType = this.getGLTextureType( texture );
  25372. backend.state.bindTexture( glTextureType, textureGPU );
  25373. this.setTextureParameters( glTextureType, texture );
  25374. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  25375. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  25376. } else if ( texture.isData3DTexture ) {
  25377. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  25378. } else if ( ! texture.isVideoTexture ) {
  25379. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  25380. }
  25381. backend.set( texture, {
  25382. textureGPU,
  25383. glTextureType,
  25384. glFormat,
  25385. glType,
  25386. glInternalFormat
  25387. } );
  25388. }
  25389. copyBufferToTexture( buffer, texture ) {
  25390. const { gl, backend } = this;
  25391. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  25392. const { width, height } = texture.source.data;
  25393. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  25394. backend.state.bindTexture( glTextureType, textureGPU );
  25395. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  25396. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  25397. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  25398. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  25399. backend.state.unbindTexture();
  25400. // debug
  25401. // const framebuffer = gl.createFramebuffer();
  25402. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  25403. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  25404. // const readout = new Float32Array( width * height * 4 );
  25405. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  25406. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  25407. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  25408. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  25409. // console.log( readout );
  25410. }
  25411. updateTexture( texture, options ) {
  25412. const { gl } = this;
  25413. const { width, height } = options;
  25414. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  25415. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  25416. return;
  25417. const getImage = ( source ) => {
  25418. if ( source.isDataTexture ) {
  25419. return source.image.data;
  25420. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  25421. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  25422. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  25423. source instanceof OffscreenCanvas ) {
  25424. return source;
  25425. }
  25426. return source.data;
  25427. };
  25428. this.backend.state.bindTexture( glTextureType, textureGPU );
  25429. this.setTextureParameters( glTextureType, texture );
  25430. if ( texture.isCompressedTexture ) {
  25431. const mipmaps = texture.mipmaps;
  25432. const image = options.image;
  25433. for ( let i = 0; i < mipmaps.length; i ++ ) {
  25434. const mipmap = mipmaps[ i ];
  25435. if ( texture.isCompressedArrayTexture ) {
  25436. if ( texture.format !== gl.RGBA ) {
  25437. if ( glFormat !== null ) {
  25438. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  25439. } else {
  25440. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  25441. }
  25442. } else {
  25443. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  25444. }
  25445. } else {
  25446. if ( glFormat !== null ) {
  25447. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  25448. } else {
  25449. console.warn( 'Unsupported compressed texture format' );
  25450. }
  25451. }
  25452. }
  25453. } else if ( texture.isCubeTexture ) {
  25454. const images = options.images;
  25455. for ( let i = 0; i < 6; i ++ ) {
  25456. const image = getImage( images[ i ] );
  25457. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  25458. }
  25459. } else if ( texture.isDataArrayTexture ) {
  25460. const image = options.image;
  25461. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  25462. } else if ( texture.isData3DTexture ) {
  25463. const image = options.image;
  25464. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  25465. } else if ( texture.isVideoTexture ) {
  25466. texture.update();
  25467. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  25468. } else {
  25469. const image = getImage( options.image );
  25470. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  25471. }
  25472. }
  25473. generateMipmaps( texture ) {
  25474. const { gl, backend } = this;
  25475. const { textureGPU, glTextureType } = backend.get( texture );
  25476. backend.state.bindTexture( glTextureType, textureGPU );
  25477. gl.generateMipmap( glTextureType );
  25478. }
  25479. deallocateRenderBuffers( renderTarget ) {
  25480. const { gl, backend } = this;
  25481. // remove framebuffer reference
  25482. if ( renderTarget ) {
  25483. const renderContextData = backend.get( renderTarget );
  25484. renderContextData.renderBufferStorageSetup = undefined;
  25485. if ( renderContextData.framebuffers ) {
  25486. for ( const cacheKey in renderContextData.framebuffers ) {
  25487. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  25488. }
  25489. delete renderContextData.framebuffers;
  25490. }
  25491. if ( renderContextData.depthRenderbuffer ) {
  25492. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  25493. delete renderContextData.depthRenderbuffer;
  25494. }
  25495. if ( renderContextData.stencilRenderbuffer ) {
  25496. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  25497. delete renderContextData.stencilRenderbuffer;
  25498. }
  25499. if ( renderContextData.msaaFrameBuffer ) {
  25500. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  25501. delete renderContextData.msaaFrameBuffer;
  25502. }
  25503. if ( renderContextData.msaaRenderbuffers ) {
  25504. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  25505. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  25506. }
  25507. delete renderContextData.msaaRenderbuffers;
  25508. }
  25509. }
  25510. }
  25511. destroyTexture( texture ) {
  25512. const { gl, backend } = this;
  25513. const { textureGPU, renderTarget } = backend.get( texture );
  25514. this.deallocateRenderBuffers( renderTarget );
  25515. gl.deleteTexture( textureGPU );
  25516. backend.delete( texture );
  25517. }
  25518. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  25519. const { gl, backend } = this;
  25520. const { state } = this.backend;
  25521. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  25522. let width, height, minX, minY;
  25523. let dstX, dstY;
  25524. if ( srcRegion !== null ) {
  25525. width = srcRegion.max.x - srcRegion.min.x;
  25526. height = srcRegion.max.y - srcRegion.min.y;
  25527. minX = srcRegion.min.x;
  25528. minY = srcRegion.min.y;
  25529. } else {
  25530. width = srcTexture.image.width;
  25531. height = srcTexture.image.height;
  25532. minX = 0;
  25533. minY = 0;
  25534. }
  25535. if ( dstPosition !== null ) {
  25536. dstX = dstPosition.x;
  25537. dstY = dstPosition.y;
  25538. } else {
  25539. dstX = 0;
  25540. dstY = 0;
  25541. }
  25542. state.bindTexture( glTextureType, dstTextureGPU );
  25543. // As another texture upload may have changed pixelStorei
  25544. // parameters, make sure they are correct for the dstTexture
  25545. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  25546. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  25547. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  25548. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  25549. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  25550. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  25551. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  25552. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  25553. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  25554. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  25555. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  25556. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  25557. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  25558. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  25559. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  25560. const srcTextureData = backend.get( srcTexture );
  25561. const dstTextureData = backend.get( dstTexture );
  25562. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  25563. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  25564. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  25565. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  25566. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  25567. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  25568. let mask = gl.COLOR_BUFFER_BIT;
  25569. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  25570. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  25571. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  25572. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  25573. } else {
  25574. if ( srcTexture.isDataTexture ) {
  25575. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  25576. } else {
  25577. if ( srcTexture.isCompressedTexture ) {
  25578. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  25579. } else {
  25580. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  25581. }
  25582. }
  25583. }
  25584. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  25585. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  25586. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  25587. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  25588. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  25589. // Generate mipmaps only when copying level 0
  25590. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  25591. state.unbindTexture();
  25592. }
  25593. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  25594. const { gl } = this;
  25595. const { state } = this.backend;
  25596. const { textureGPU } = this.backend.get( texture );
  25597. const { x, y, z: width, w: height } = rectangle;
  25598. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  25599. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  25600. if ( requireDrawFrameBuffer ) {
  25601. const partial = ( x !== 0 || y !== 0 );
  25602. let mask;
  25603. let attachment;
  25604. if ( texture.isDepthTexture === true ) {
  25605. mask = gl.DEPTH_BUFFER_BIT;
  25606. attachment = gl.DEPTH_ATTACHMENT;
  25607. if ( renderContext.stencil ) {
  25608. mask |= gl.STENCIL_BUFFER_BIT;
  25609. }
  25610. } else {
  25611. mask = gl.COLOR_BUFFER_BIT;
  25612. attachment = gl.COLOR_ATTACHMENT0;
  25613. }
  25614. if ( partial ) {
  25615. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  25616. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  25617. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  25618. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  25619. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  25620. const flippedY = srcHeight - y - height;
  25621. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  25622. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  25623. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  25624. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  25625. state.unbindTexture();
  25626. } else {
  25627. const fb = gl.createFramebuffer();
  25628. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  25629. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  25630. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  25631. gl.deleteFramebuffer( fb );
  25632. }
  25633. } else {
  25634. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  25635. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  25636. state.unbindTexture();
  25637. }
  25638. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  25639. this.backend._setFramebuffer( renderContext );
  25640. }
  25641. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  25642. setupRenderBufferStorage( renderbuffer, renderContext ) {
  25643. const { gl } = this;
  25644. const renderTarget = renderContext.renderTarget;
  25645. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  25646. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  25647. if ( depthBuffer && ! stencilBuffer ) {
  25648. let glInternalFormat = gl.DEPTH_COMPONENT24;
  25649. if ( samples > 0 ) {
  25650. if ( depthTexture && depthTexture.isDepthTexture ) {
  25651. if ( depthTexture.type === gl.FLOAT ) {
  25652. glInternalFormat = gl.DEPTH_COMPONENT32F;
  25653. }
  25654. }
  25655. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  25656. } else {
  25657. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  25658. }
  25659. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  25660. } else if ( depthBuffer && stencilBuffer ) {
  25661. if ( samples > 0 ) {
  25662. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  25663. } else {
  25664. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  25665. }
  25666. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  25667. }
  25668. }
  25669. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  25670. const { backend, gl } = this;
  25671. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  25672. const fb = gl.createFramebuffer();
  25673. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  25674. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  25675. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  25676. const typedArrayType = this._getTypedArrayType( glType );
  25677. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  25678. const elementCount = width * height;
  25679. const byteLength = elementCount * bytesPerTexel;
  25680. const buffer = gl.createBuffer();
  25681. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  25682. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  25683. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  25684. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  25685. await backend.utils._clientWaitAsync();
  25686. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  25687. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  25688. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  25689. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  25690. gl.deleteFramebuffer( fb );
  25691. return dstBuffer;
  25692. }
  25693. _getTypedArrayType( glType ) {
  25694. const { gl } = this;
  25695. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  25696. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  25697. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  25698. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  25699. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  25700. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  25701. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  25702. if ( glType === gl.FLOAT ) return Float32Array;
  25703. throw new Error( `Unsupported WebGL type: ${glType}` );
  25704. }
  25705. _getBytesPerTexel( glType, glFormat ) {
  25706. const { gl } = this;
  25707. let bytesPerComponent = 0;
  25708. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  25709. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  25710. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  25711. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  25712. glType === gl.UNSIGNED_SHORT ||
  25713. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  25714. if ( glType === gl.UNSIGNED_INT ||
  25715. glType === gl.FLOAT ) bytesPerComponent = 4;
  25716. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  25717. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  25718. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  25719. }
  25720. }
  25721. class WebGLExtensions {
  25722. constructor( backend ) {
  25723. this.backend = backend;
  25724. this.gl = this.backend.gl;
  25725. this.availableExtensions = this.gl.getSupportedExtensions();
  25726. this.extensions = {};
  25727. }
  25728. get( name ) {
  25729. let extension = this.extensions[ name ];
  25730. if ( extension === undefined ) {
  25731. extension = this.gl.getExtension( name );
  25732. this.extensions[ name ] = extension;
  25733. }
  25734. return extension;
  25735. }
  25736. has( name ) {
  25737. return this.availableExtensions.includes( name );
  25738. }
  25739. }
  25740. class WebGLCapabilities {
  25741. constructor( backend ) {
  25742. this.backend = backend;
  25743. this.maxAnisotropy = null;
  25744. }
  25745. getMaxAnisotropy() {
  25746. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  25747. const gl = this.backend.gl;
  25748. const extensions = this.backend.extensions;
  25749. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  25750. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  25751. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  25752. } else {
  25753. this.maxAnisotropy = 0;
  25754. }
  25755. return this.maxAnisotropy;
  25756. }
  25757. }
  25758. const GLFeatureName = {
  25759. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  25760. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  25761. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  25762. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  25763. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  25764. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  25765. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  25766. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  25767. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  25768. };
  25769. class WebGLBufferRenderer {
  25770. constructor( backend ) {
  25771. this.gl = backend.gl;
  25772. this.extensions = backend.extensions;
  25773. this.info = backend.renderer.info;
  25774. this.mode = null;
  25775. this.index = 0;
  25776. this.type = null;
  25777. this.object = null;
  25778. }
  25779. render( start, count ) {
  25780. const { gl, mode, object, type, info, index } = this;
  25781. if ( index !== 0 ) {
  25782. gl.drawElements( mode, count, type, start );
  25783. } else {
  25784. gl.drawArrays( mode, start, count );
  25785. }
  25786. info.update( object, count, mode, 1 );
  25787. }
  25788. renderInstances( start, count, primcount ) {
  25789. const { gl, mode, type, index, object, info } = this;
  25790. if ( primcount === 0 ) return;
  25791. if ( index !== 0 ) {
  25792. gl.drawElementsInstanced( mode, count, type, start, primcount );
  25793. } else {
  25794. gl.drawArraysInstanced( mode, start, count, primcount );
  25795. }
  25796. info.update( object, count, mode, primcount );
  25797. }
  25798. renderMultiDraw( starts, counts, drawCount ) {
  25799. const { extensions, mode, object, info } = this;
  25800. if ( drawCount === 0 ) return;
  25801. const extension = extensions.get( 'WEBGL_multi_draw' );
  25802. if ( extension === null ) {
  25803. for ( let i = 0; i < drawCount; i ++ ) {
  25804. this.render( starts[ i ], counts[ i ] );
  25805. }
  25806. } else {
  25807. if ( this.index !== 0 ) {
  25808. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  25809. } else {
  25810. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  25811. }
  25812. let elementCount = 0;
  25813. for ( let i = 0; i < drawCount; i ++ ) {
  25814. elementCount += counts[ i ];
  25815. }
  25816. info.update( object, elementCount, mode, 1 );
  25817. }
  25818. }
  25819. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  25820. const { extensions, mode, object, info } = this;
  25821. if ( drawCount === 0 ) return;
  25822. const extension = extensions.get( 'WEBGL_multi_draw' );
  25823. if ( extension === null ) {
  25824. for ( let i = 0; i < drawCount; i ++ ) {
  25825. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  25826. }
  25827. } else {
  25828. if ( this.index !== 0 ) {
  25829. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  25830. } else {
  25831. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  25832. }
  25833. let elementCount = 0;
  25834. for ( let i = 0; i < drawCount; i ++ ) {
  25835. elementCount += counts[ i ] * primcount[ i ];
  25836. }
  25837. info.update( object, elementCount, mode, 1 );
  25838. }
  25839. }
  25840. //
  25841. }
  25842. //
  25843. class WebGLBackend extends Backend {
  25844. constructor( parameters = {} ) {
  25845. super( parameters );
  25846. this.isWebGLBackend = true;
  25847. }
  25848. init( renderer ) {
  25849. super.init( renderer );
  25850. //
  25851. const parameters = this.parameters;
  25852. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  25853. function onContextLost( event ) {
  25854. event.preventDefault();
  25855. const contextLossInfo = {
  25856. api: 'WebGL',
  25857. message: event.statusMessage || 'Unknown reason',
  25858. reason: null,
  25859. originalEvent: event
  25860. };
  25861. renderer.onDeviceLost( contextLossInfo );
  25862. }
  25863. this._onContextLost = onContextLost;
  25864. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  25865. this.gl = glContext;
  25866. this.extensions = new WebGLExtensions( this );
  25867. this.capabilities = new WebGLCapabilities( this );
  25868. this.attributeUtils = new WebGLAttributeUtils( this );
  25869. this.textureUtils = new WebGLTextureUtils( this );
  25870. this.bufferRenderer = new WebGLBufferRenderer( this );
  25871. this.state = new WebGLState( this );
  25872. this.utils = new WebGLUtils( this );
  25873. this.vaoCache = {};
  25874. this.transformFeedbackCache = {};
  25875. this.discard = false;
  25876. this.trackTimestamp = ( parameters.trackTimestamp === true );
  25877. this.extensions.get( 'EXT_color_buffer_float' );
  25878. this.extensions.get( 'WEBGL_clip_cull_distance' );
  25879. this.extensions.get( 'OES_texture_float_linear' );
  25880. this.extensions.get( 'EXT_color_buffer_half_float' );
  25881. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  25882. this.extensions.get( 'WEBGL_render_shared_exponent' );
  25883. this.extensions.get( 'WEBGL_multi_draw' );
  25884. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  25885. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  25886. this._knownBindings = new WeakSet();
  25887. this._currentContext = null;
  25888. }
  25889. get coordinateSystem() {
  25890. return WebGLCoordinateSystem;
  25891. }
  25892. async getArrayBufferAsync( attribute ) {
  25893. return await this.attributeUtils.getArrayBufferAsync( attribute );
  25894. }
  25895. async waitForGPU() {
  25896. await this.utils._clientWaitAsync();
  25897. }
  25898. initTimestampQuery( renderContext ) {
  25899. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25900. const renderContextData = this.get( renderContext );
  25901. if ( this.queryRunning ) {
  25902. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  25903. renderContextData.queryQueue.push( renderContext );
  25904. return;
  25905. }
  25906. if ( renderContextData.activeQuery ) {
  25907. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25908. renderContextData.activeQuery = null;
  25909. }
  25910. renderContextData.activeQuery = this.gl.createQuery();
  25911. if ( renderContextData.activeQuery !== null ) {
  25912. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  25913. this.queryRunning = true;
  25914. }
  25915. }
  25916. // timestamp utils
  25917. prepareTimestampBuffer( renderContext ) {
  25918. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25919. const renderContextData = this.get( renderContext );
  25920. if ( renderContextData.activeQuery ) {
  25921. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25922. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25923. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  25924. renderContextData.activeQuery = null;
  25925. this.queryRunning = false;
  25926. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  25927. const nextRenderContext = renderContextData.queryQueue.shift();
  25928. this.initTimestampQuery( nextRenderContext );
  25929. }
  25930. }
  25931. }
  25932. async resolveTimestampAsync( renderContext, type = 'render' ) {
  25933. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25934. const renderContextData = this.get( renderContext );
  25935. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25936. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  25937. const queryInfo = renderContextData.gpuQueries[ i ];
  25938. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  25939. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  25940. if ( available && ! disjoint ) {
  25941. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  25942. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  25943. this.gl.deleteQuery( queryInfo.query );
  25944. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  25945. i --;
  25946. this.renderer.info.updateTimestamp( type, duration );
  25947. }
  25948. }
  25949. }
  25950. getContext() {
  25951. return this.gl;
  25952. }
  25953. beginRender( renderContext ) {
  25954. const { gl } = this;
  25955. const renderContextData = this.get( renderContext );
  25956. //
  25957. //
  25958. this.initTimestampQuery( renderContext );
  25959. renderContextData.previousContext = this._currentContext;
  25960. this._currentContext = renderContext;
  25961. this._setFramebuffer( renderContext );
  25962. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  25963. //
  25964. if ( renderContext.viewport ) {
  25965. this.updateViewport( renderContext );
  25966. } else {
  25967. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  25968. }
  25969. if ( renderContext.scissor ) {
  25970. const { x, y, width, height } = renderContext.scissorValue;
  25971. gl.scissor( x, renderContext.height - height - y, width, height );
  25972. }
  25973. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25974. if ( occlusionQueryCount > 0 ) {
  25975. // Get a reference to the array of objects with queries. The renderContextData property
  25976. // can be changed by another render pass before the async reading of all previous queries complete
  25977. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  25978. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  25979. renderContextData.lastOcclusionObject = null;
  25980. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  25981. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  25982. renderContextData.occlusionQueryIndex = 0;
  25983. }
  25984. }
  25985. finishRender( renderContext ) {
  25986. const { gl, state } = this;
  25987. const renderContextData = this.get( renderContext );
  25988. const previousContext = renderContextData.previousContext;
  25989. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25990. if ( occlusionQueryCount > 0 ) {
  25991. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  25992. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  25993. }
  25994. this.resolveOccludedAsync( renderContext );
  25995. }
  25996. const textures = renderContext.textures;
  25997. if ( textures !== null ) {
  25998. for ( let i = 0; i < textures.length; i ++ ) {
  25999. const texture = textures[ i ];
  26000. if ( texture.generateMipmaps ) {
  26001. this.generateMipmaps( texture );
  26002. }
  26003. }
  26004. }
  26005. this._currentContext = previousContext;
  26006. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  26007. const renderTargetContextData = this.get( renderContext.renderTarget );
  26008. const { samples } = renderContext.renderTarget;
  26009. if ( samples > 0 ) {
  26010. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  26011. const mask = gl.COLOR_BUFFER_BIT;
  26012. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  26013. const textures = renderContext.textures;
  26014. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  26015. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  26016. for ( let i = 0; i < textures.length; i ++ ) {
  26017. // TODO Add support for MRT
  26018. if ( renderContext.scissor ) {
  26019. const { x, y, width, height } = renderContext.scissorValue;
  26020. const viewY = renderContext.height - height - y;
  26021. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  26022. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  26023. } else {
  26024. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  26025. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  26026. }
  26027. }
  26028. }
  26029. }
  26030. if ( previousContext !== null ) {
  26031. this._setFramebuffer( previousContext );
  26032. if ( previousContext.viewport ) {
  26033. this.updateViewport( previousContext );
  26034. } else {
  26035. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  26036. }
  26037. }
  26038. this.prepareTimestampBuffer( renderContext );
  26039. }
  26040. resolveOccludedAsync( renderContext ) {
  26041. const renderContextData = this.get( renderContext );
  26042. // handle occlusion query results
  26043. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  26044. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  26045. const occluded = new WeakSet();
  26046. const { gl } = this;
  26047. renderContextData.currentOcclusionQueryObjects = null;
  26048. renderContextData.currentOcclusionQueries = null;
  26049. const check = () => {
  26050. let completed = 0;
  26051. // check all queries and requeue as appropriate
  26052. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  26053. const query = currentOcclusionQueries[ i ];
  26054. if ( query === null ) continue;
  26055. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  26056. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  26057. currentOcclusionQueries[ i ] = null;
  26058. gl.deleteQuery( query );
  26059. completed ++;
  26060. }
  26061. }
  26062. if ( completed < currentOcclusionQueries.length ) {
  26063. requestAnimationFrame( check );
  26064. } else {
  26065. renderContextData.occluded = occluded;
  26066. }
  26067. };
  26068. check();
  26069. }
  26070. }
  26071. isOccluded( renderContext, object ) {
  26072. const renderContextData = this.get( renderContext );
  26073. return renderContextData.occluded && renderContextData.occluded.has( object );
  26074. }
  26075. updateViewport( renderContext ) {
  26076. const gl = this.gl;
  26077. const { x, y, width, height } = renderContext.viewportValue;
  26078. gl.viewport( x, renderContext.height - height - y, width, height );
  26079. }
  26080. setScissorTest( boolean ) {
  26081. const gl = this.gl;
  26082. if ( boolean ) {
  26083. gl.enable( gl.SCISSOR_TEST );
  26084. } else {
  26085. gl.disable( gl.SCISSOR_TEST );
  26086. }
  26087. }
  26088. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  26089. const { gl } = this;
  26090. if ( descriptor === null ) {
  26091. const clearColor = this.getClearColor();
  26092. // premultiply alpha
  26093. clearColor.r *= clearColor.a;
  26094. clearColor.g *= clearColor.a;
  26095. clearColor.b *= clearColor.a;
  26096. descriptor = {
  26097. textures: null,
  26098. clearColorValue: clearColor
  26099. };
  26100. }
  26101. //
  26102. let clear = 0;
  26103. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  26104. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  26105. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  26106. if ( clear !== 0 ) {
  26107. let clearColor;
  26108. if ( descriptor.clearColorValue ) {
  26109. clearColor = descriptor.clearColorValue;
  26110. } else {
  26111. clearColor = this.getClearColor();
  26112. // premultiply alpha
  26113. clearColor.r *= clearColor.a;
  26114. clearColor.g *= clearColor.a;
  26115. clearColor.b *= clearColor.a;
  26116. }
  26117. if ( depth ) this.state.setDepthMask( true );
  26118. if ( descriptor.textures === null ) {
  26119. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  26120. gl.clear( clear );
  26121. } else {
  26122. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  26123. if ( color ) {
  26124. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  26125. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  26126. }
  26127. }
  26128. if ( depth && stencil ) {
  26129. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  26130. } else if ( depth ) {
  26131. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  26132. } else if ( stencil ) {
  26133. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  26134. }
  26135. }
  26136. }
  26137. }
  26138. beginCompute( computeGroup ) {
  26139. const { state, gl } = this;
  26140. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  26141. this.initTimestampQuery( computeGroup );
  26142. }
  26143. compute( computeGroup, computeNode, bindings, pipeline ) {
  26144. const { state, gl } = this;
  26145. if ( ! this.discard ) {
  26146. // required here to handle async behaviour of render.compute()
  26147. gl.enable( gl.RASTERIZER_DISCARD );
  26148. this.discard = true;
  26149. }
  26150. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  26151. const vaoKey = this._getVaoKey( null, attributes );
  26152. const vaoGPU = this.vaoCache[ vaoKey ];
  26153. if ( vaoGPU === undefined ) {
  26154. this._createVao( null, attributes );
  26155. } else {
  26156. gl.bindVertexArray( vaoGPU );
  26157. }
  26158. state.useProgram( programGPU );
  26159. this._bindUniforms( bindings );
  26160. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  26161. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  26162. gl.beginTransformFeedback( gl.POINTS );
  26163. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  26164. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  26165. } else {
  26166. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  26167. }
  26168. gl.endTransformFeedback();
  26169. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  26170. // switch active buffers
  26171. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  26172. const dualAttributeData = transformBuffers[ i ];
  26173. if ( dualAttributeData.pbo ) {
  26174. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  26175. }
  26176. dualAttributeData.switchBuffers();
  26177. }
  26178. }
  26179. finishCompute( computeGroup ) {
  26180. const gl = this.gl;
  26181. this.discard = false;
  26182. gl.disable( gl.RASTERIZER_DISCARD );
  26183. this.prepareTimestampBuffer( computeGroup );
  26184. if ( this._currentContext ) {
  26185. this._setFramebuffer( this._currentContext );
  26186. }
  26187. }
  26188. draw( renderObject/*, info*/ ) {
  26189. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  26190. const { programGPU } = this.get( pipeline );
  26191. const { gl, state } = this;
  26192. const contextData = this.get( context );
  26193. const drawParams = renderObject.getDrawParameters();
  26194. if ( drawParams === null ) return;
  26195. //
  26196. this._bindUniforms( renderObject.getBindings() );
  26197. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  26198. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  26199. state.useProgram( programGPU );
  26200. //
  26201. const renderObjectData = this.get( renderObject );
  26202. let vaoGPU = renderObjectData.staticVao;
  26203. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  26204. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  26205. vaoGPU = this.vaoCache[ vaoKey ];
  26206. if ( vaoGPU === undefined ) {
  26207. let staticVao;
  26208. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  26209. if ( staticVao ) {
  26210. renderObjectData.staticVao = vaoGPU;
  26211. renderObjectData.geometryId = renderObject.geometry.id;
  26212. }
  26213. }
  26214. }
  26215. gl.bindVertexArray( vaoGPU );
  26216. //
  26217. const index = renderObject.getIndex();
  26218. //
  26219. const lastObject = contextData.lastOcclusionObject;
  26220. if ( lastObject !== object && lastObject !== undefined ) {
  26221. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  26222. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  26223. contextData.occlusionQueryIndex ++;
  26224. }
  26225. if ( object.occlusionTest === true ) {
  26226. const query = gl.createQuery();
  26227. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  26228. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  26229. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  26230. }
  26231. contextData.lastOcclusionObject = object;
  26232. }
  26233. //
  26234. const renderer = this.bufferRenderer;
  26235. if ( object.isPoints ) renderer.mode = gl.POINTS;
  26236. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  26237. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  26238. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  26239. else {
  26240. if ( material.wireframe === true ) {
  26241. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  26242. renderer.mode = gl.LINES;
  26243. } else {
  26244. renderer.mode = gl.TRIANGLES;
  26245. }
  26246. }
  26247. //
  26248. const { vertexCount, instanceCount } = drawParams;
  26249. let { firstVertex } = drawParams;
  26250. renderer.object = object;
  26251. if ( index !== null ) {
  26252. firstVertex *= index.array.BYTES_PER_ELEMENT;
  26253. const indexData = this.get( index );
  26254. renderer.index = index.count;
  26255. renderer.type = indexData.type;
  26256. } else {
  26257. renderer.index = 0;
  26258. }
  26259. if ( object.isBatchedMesh ) {
  26260. if ( object._multiDrawInstances !== null ) {
  26261. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  26262. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  26263. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  26264. } else {
  26265. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  26266. }
  26267. } else if ( instanceCount > 1 ) {
  26268. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  26269. } else {
  26270. renderer.render( firstVertex, vertexCount );
  26271. }
  26272. //
  26273. gl.bindVertexArray( null );
  26274. }
  26275. needsRenderUpdate( /*renderObject*/ ) {
  26276. return false;
  26277. }
  26278. getRenderCacheKey( /*renderObject*/ ) {
  26279. return '';
  26280. }
  26281. // textures
  26282. createDefaultTexture( texture ) {
  26283. this.textureUtils.createDefaultTexture( texture );
  26284. }
  26285. createTexture( texture, options ) {
  26286. this.textureUtils.createTexture( texture, options );
  26287. }
  26288. updateTexture( texture, options ) {
  26289. this.textureUtils.updateTexture( texture, options );
  26290. }
  26291. generateMipmaps( texture ) {
  26292. this.textureUtils.generateMipmaps( texture );
  26293. }
  26294. destroyTexture( texture ) {
  26295. this.textureUtils.destroyTexture( texture );
  26296. }
  26297. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  26298. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  26299. }
  26300. createSampler( /*texture*/ ) {
  26301. //console.warn( 'Abstract class.' );
  26302. }
  26303. destroySampler() {}
  26304. // node builder
  26305. createNodeBuilder( object, renderer ) {
  26306. return new GLSLNodeBuilder( object, renderer );
  26307. }
  26308. // program
  26309. createProgram( program ) {
  26310. const gl = this.gl;
  26311. const { stage, code } = program;
  26312. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  26313. gl.shaderSource( shader, code );
  26314. gl.compileShader( shader );
  26315. this.set( program, {
  26316. shaderGPU: shader
  26317. } );
  26318. }
  26319. destroyProgram( /*program*/ ) {
  26320. console.warn( 'Abstract class.' );
  26321. }
  26322. createRenderPipeline( renderObject, promises ) {
  26323. const gl = this.gl;
  26324. const pipeline = renderObject.pipeline;
  26325. // Program
  26326. const { fragmentProgram, vertexProgram } = pipeline;
  26327. const programGPU = gl.createProgram();
  26328. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  26329. const vertexShader = this.get( vertexProgram ).shaderGPU;
  26330. gl.attachShader( programGPU, fragmentShader );
  26331. gl.attachShader( programGPU, vertexShader );
  26332. gl.linkProgram( programGPU );
  26333. this.set( pipeline, {
  26334. programGPU,
  26335. fragmentShader,
  26336. vertexShader
  26337. } );
  26338. if ( promises !== null && this.parallel ) {
  26339. const p = new Promise( ( resolve /*, reject*/ ) => {
  26340. const parallel = this.parallel;
  26341. const checkStatus = () => {
  26342. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  26343. this._completeCompile( renderObject, pipeline );
  26344. resolve();
  26345. } else {
  26346. requestAnimationFrame( checkStatus );
  26347. }
  26348. };
  26349. checkStatus();
  26350. } );
  26351. promises.push( p );
  26352. return;
  26353. }
  26354. this._completeCompile( renderObject, pipeline );
  26355. }
  26356. _handleSource( string, errorLine ) {
  26357. const lines = string.split( '\n' );
  26358. const lines2 = [];
  26359. const from = Math.max( errorLine - 6, 0 );
  26360. const to = Math.min( errorLine + 6, lines.length );
  26361. for ( let i = from; i < to; i ++ ) {
  26362. const line = i + 1;
  26363. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  26364. }
  26365. return lines2.join( '\n' );
  26366. }
  26367. _getShaderErrors( gl, shader, type ) {
  26368. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  26369. const errors = gl.getShaderInfoLog( shader ).trim();
  26370. if ( status && errors === '' ) return '';
  26371. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  26372. if ( errorMatches ) {
  26373. const errorLine = parseInt( errorMatches[ 1 ] );
  26374. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  26375. } else {
  26376. return errors;
  26377. }
  26378. }
  26379. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  26380. if ( this.renderer.debug.checkShaderErrors ) {
  26381. const gl = this.gl;
  26382. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  26383. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  26384. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  26385. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  26386. } else {
  26387. // default error reporting
  26388. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  26389. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  26390. console.error(
  26391. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  26392. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  26393. 'Program Info Log: ' + programLog + '\n' +
  26394. vertexErrors + '\n' +
  26395. fragmentErrors
  26396. );
  26397. }
  26398. } else if ( programLog !== '' ) {
  26399. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  26400. }
  26401. }
  26402. }
  26403. _completeCompile( renderObject, pipeline ) {
  26404. const { state, gl } = this;
  26405. const pipelineData = this.get( pipeline );
  26406. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  26407. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  26408. this._logProgramError( programGPU, fragmentShader, vertexShader );
  26409. }
  26410. state.useProgram( programGPU );
  26411. // Bindings
  26412. const bindings = renderObject.getBindings();
  26413. this._setupBindings( bindings, programGPU );
  26414. //
  26415. this.set( pipeline, {
  26416. programGPU
  26417. } );
  26418. }
  26419. createComputePipeline( computePipeline, bindings ) {
  26420. const { state, gl } = this;
  26421. // Program
  26422. const fragmentProgram = {
  26423. stage: 'fragment',
  26424. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  26425. };
  26426. this.createProgram( fragmentProgram );
  26427. const { computeProgram } = computePipeline;
  26428. const programGPU = gl.createProgram();
  26429. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  26430. const vertexShader = this.get( computeProgram ).shaderGPU;
  26431. const transforms = computeProgram.transforms;
  26432. const transformVaryingNames = [];
  26433. const transformAttributeNodes = [];
  26434. for ( let i = 0; i < transforms.length; i ++ ) {
  26435. const transform = transforms[ i ];
  26436. transformVaryingNames.push( transform.varyingName );
  26437. transformAttributeNodes.push( transform.attributeNode );
  26438. }
  26439. gl.attachShader( programGPU, fragmentShader );
  26440. gl.attachShader( programGPU, vertexShader );
  26441. gl.transformFeedbackVaryings(
  26442. programGPU,
  26443. transformVaryingNames,
  26444. gl.SEPARATE_ATTRIBS
  26445. );
  26446. gl.linkProgram( programGPU );
  26447. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  26448. this._logProgramError( programGPU, fragmentShader, vertexShader );
  26449. }
  26450. state.useProgram( programGPU );
  26451. // Bindings
  26452. this._setupBindings( bindings, programGPU );
  26453. const attributeNodes = computeProgram.attributes;
  26454. const attributes = [];
  26455. const transformBuffers = [];
  26456. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  26457. const attribute = attributeNodes[ i ].node.attribute;
  26458. attributes.push( attribute );
  26459. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  26460. }
  26461. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  26462. const attribute = transformAttributeNodes[ i ].attribute;
  26463. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  26464. const attributeData = this.get( attribute );
  26465. transformBuffers.push( attributeData );
  26466. }
  26467. //
  26468. this.set( computePipeline, {
  26469. programGPU,
  26470. transformBuffers,
  26471. attributes
  26472. } );
  26473. }
  26474. createBindings( bindGroup, bindings ) {
  26475. if ( this._knownBindings.has( bindings ) === false ) {
  26476. this._knownBindings.add( bindings );
  26477. let uniformBuffers = 0;
  26478. let textures = 0;
  26479. for ( const bindGroup of bindings ) {
  26480. this.set( bindGroup, {
  26481. textures: textures,
  26482. uniformBuffers: uniformBuffers
  26483. } );
  26484. for ( const binding of bindGroup.bindings ) {
  26485. if ( binding.isUniformBuffer ) uniformBuffers ++;
  26486. if ( binding.isSampledTexture ) textures ++;
  26487. }
  26488. }
  26489. }
  26490. this.updateBindings( bindGroup, bindings );
  26491. }
  26492. updateBindings( bindGroup /*, bindings*/ ) {
  26493. const { gl } = this;
  26494. const bindGroupData = this.get( bindGroup );
  26495. let i = bindGroupData.uniformBuffers;
  26496. let t = bindGroupData.textures;
  26497. for ( const binding of bindGroup.bindings ) {
  26498. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  26499. const data = binding.buffer;
  26500. const bufferGPU = gl.createBuffer();
  26501. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  26502. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  26503. this.set( binding, {
  26504. index: i ++,
  26505. bufferGPU
  26506. } );
  26507. } else if ( binding.isSampledTexture ) {
  26508. const { textureGPU, glTextureType } = this.get( binding.texture );
  26509. this.set( binding, {
  26510. index: t ++,
  26511. textureGPU,
  26512. glTextureType
  26513. } );
  26514. }
  26515. }
  26516. }
  26517. updateBinding( binding ) {
  26518. const gl = this.gl;
  26519. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  26520. const bindingData = this.get( binding );
  26521. const bufferGPU = bindingData.bufferGPU;
  26522. const data = binding.buffer;
  26523. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  26524. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  26525. }
  26526. }
  26527. // attributes
  26528. createIndexAttribute( attribute ) {
  26529. const gl = this.gl;
  26530. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  26531. }
  26532. createAttribute( attribute ) {
  26533. if ( this.has( attribute ) ) return;
  26534. const gl = this.gl;
  26535. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  26536. }
  26537. createStorageAttribute( attribute ) {
  26538. if ( this.has( attribute ) ) return;
  26539. const gl = this.gl;
  26540. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  26541. }
  26542. updateAttribute( attribute ) {
  26543. this.attributeUtils.updateAttribute( attribute );
  26544. }
  26545. destroyAttribute( attribute ) {
  26546. this.attributeUtils.destroyAttribute( attribute );
  26547. }
  26548. updateSize() {
  26549. //console.warn( 'Abstract class.' );
  26550. }
  26551. hasFeature( name ) {
  26552. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  26553. const extensions = this.extensions;
  26554. for ( let i = 0; i < keysMatching.length; i ++ ) {
  26555. if ( extensions.has( keysMatching[ i ] ) ) return true;
  26556. }
  26557. return false;
  26558. }
  26559. getMaxAnisotropy() {
  26560. return this.capabilities.getMaxAnisotropy();
  26561. }
  26562. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  26563. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  26564. }
  26565. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  26566. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  26567. }
  26568. _setFramebuffer( descriptor ) {
  26569. const { gl, state } = this;
  26570. let currentFrameBuffer = null;
  26571. if ( descriptor.textures !== null ) {
  26572. const renderTarget = descriptor.renderTarget;
  26573. const renderTargetContextData = this.get( renderTarget );
  26574. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  26575. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  26576. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  26577. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  26578. const cacheKey = getCacheKey( descriptor );
  26579. let fb;
  26580. if ( isCube ) {
  26581. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  26582. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  26583. } else {
  26584. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  26585. fb = renderTargetContextData.framebuffers[ cacheKey ];
  26586. }
  26587. if ( fb === undefined ) {
  26588. fb = gl.createFramebuffer();
  26589. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  26590. const textures = descriptor.textures;
  26591. if ( isCube ) {
  26592. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  26593. const { textureGPU } = this.get( textures[ 0 ] );
  26594. const cubeFace = this.renderer._activeCubeFace;
  26595. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  26596. } else {
  26597. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  26598. for ( let i = 0; i < textures.length; i ++ ) {
  26599. const texture = textures[ i ];
  26600. const textureData = this.get( texture );
  26601. textureData.renderTarget = descriptor.renderTarget;
  26602. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  26603. const attachment = gl.COLOR_ATTACHMENT0 + i;
  26604. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  26605. }
  26606. state.drawBuffers( descriptor, fb );
  26607. }
  26608. if ( descriptor.depthTexture !== null ) {
  26609. const textureData = this.get( descriptor.depthTexture );
  26610. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  26611. textureData.renderTarget = descriptor.renderTarget;
  26612. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  26613. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  26614. }
  26615. }
  26616. if ( samples > 0 ) {
  26617. if ( msaaFb === undefined ) {
  26618. const invalidationArray = [];
  26619. msaaFb = gl.createFramebuffer();
  26620. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  26621. const msaaRenderbuffers = [];
  26622. const textures = descriptor.textures;
  26623. for ( let i = 0; i < textures.length; i ++ ) {
  26624. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  26625. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  26626. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  26627. if ( depthBuffer ) {
  26628. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  26629. invalidationArray.push( depthStyle );
  26630. }
  26631. const texture = descriptor.textures[ i ];
  26632. const textureData = this.get( texture );
  26633. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  26634. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  26635. }
  26636. renderTargetContextData.msaaFrameBuffer = msaaFb;
  26637. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  26638. if ( depthRenderbuffer === undefined ) {
  26639. depthRenderbuffer = gl.createRenderbuffer();
  26640. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  26641. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  26642. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  26643. invalidationArray.push( depthStyle );
  26644. }
  26645. renderTargetContextData.invalidationArray = invalidationArray;
  26646. }
  26647. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  26648. } else {
  26649. currentFrameBuffer = fb;
  26650. }
  26651. }
  26652. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  26653. }
  26654. _getVaoKey( index, attributes ) {
  26655. let key = [];
  26656. if ( index !== null ) {
  26657. const indexData = this.get( index );
  26658. key += ':' + indexData.id;
  26659. }
  26660. for ( let i = 0; i < attributes.length; i ++ ) {
  26661. const attributeData = this.get( attributes[ i ] );
  26662. key += ':' + attributeData.id;
  26663. }
  26664. return key;
  26665. }
  26666. _createVao( index, attributes ) {
  26667. const { gl } = this;
  26668. const vaoGPU = gl.createVertexArray();
  26669. let key = '';
  26670. let staticVao = true;
  26671. gl.bindVertexArray( vaoGPU );
  26672. if ( index !== null ) {
  26673. const indexData = this.get( index );
  26674. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  26675. key += ':' + indexData.id;
  26676. }
  26677. for ( let i = 0; i < attributes.length; i ++ ) {
  26678. const attribute = attributes[ i ];
  26679. const attributeData = this.get( attribute );
  26680. key += ':' + attributeData.id;
  26681. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  26682. gl.enableVertexAttribArray( i );
  26683. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  26684. let stride, offset;
  26685. if ( attribute.isInterleavedBufferAttribute === true ) {
  26686. stride = attribute.data.stride * attributeData.bytesPerElement;
  26687. offset = attribute.offset * attributeData.bytesPerElement;
  26688. } else {
  26689. stride = 0;
  26690. offset = 0;
  26691. }
  26692. if ( attributeData.isInteger ) {
  26693. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  26694. } else {
  26695. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  26696. }
  26697. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  26698. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  26699. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  26700. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  26701. }
  26702. }
  26703. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  26704. this.vaoCache[ key ] = vaoGPU;
  26705. return { vaoGPU, staticVao };
  26706. }
  26707. _getTransformFeedback( transformBuffers ) {
  26708. let key = '';
  26709. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  26710. key += ':' + transformBuffers[ i ].id;
  26711. }
  26712. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  26713. if ( transformFeedbackGPU !== undefined ) {
  26714. return transformFeedbackGPU;
  26715. }
  26716. const { gl } = this;
  26717. transformFeedbackGPU = gl.createTransformFeedback();
  26718. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  26719. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  26720. const attributeData = transformBuffers[ i ];
  26721. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  26722. }
  26723. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  26724. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  26725. return transformFeedbackGPU;
  26726. }
  26727. _setupBindings( bindings, programGPU ) {
  26728. const gl = this.gl;
  26729. for ( const bindGroup of bindings ) {
  26730. for ( const binding of bindGroup.bindings ) {
  26731. const bindingData = this.get( binding );
  26732. const index = bindingData.index;
  26733. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  26734. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  26735. gl.uniformBlockBinding( programGPU, location, index );
  26736. } else if ( binding.isSampledTexture ) {
  26737. const location = gl.getUniformLocation( programGPU, binding.name );
  26738. gl.uniform1i( location, index );
  26739. }
  26740. }
  26741. }
  26742. }
  26743. _bindUniforms( bindings ) {
  26744. const { gl, state } = this;
  26745. for ( const bindGroup of bindings ) {
  26746. for ( const binding of bindGroup.bindings ) {
  26747. const bindingData = this.get( binding );
  26748. const index = bindingData.index;
  26749. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  26750. // TODO USE bindBufferRange to group multiple uniform buffers
  26751. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  26752. } else if ( binding.isSampledTexture ) {
  26753. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  26754. }
  26755. }
  26756. }
  26757. }
  26758. dispose() {
  26759. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  26760. }
  26761. }
  26762. const GPUPrimitiveTopology = {
  26763. PointList: 'point-list',
  26764. LineList: 'line-list',
  26765. LineStrip: 'line-strip',
  26766. TriangleList: 'triangle-list',
  26767. TriangleStrip: 'triangle-strip',
  26768. };
  26769. const GPUCompareFunction = {
  26770. Never: 'never',
  26771. Less: 'less',
  26772. Equal: 'equal',
  26773. LessEqual: 'less-equal',
  26774. Greater: 'greater',
  26775. NotEqual: 'not-equal',
  26776. GreaterEqual: 'greater-equal',
  26777. Always: 'always'
  26778. };
  26779. const GPUStoreOp = {
  26780. Store: 'store',
  26781. Discard: 'discard'
  26782. };
  26783. const GPULoadOp = {
  26784. Load: 'load',
  26785. Clear: 'clear'
  26786. };
  26787. const GPUFrontFace = {
  26788. CCW: 'ccw',
  26789. CW: 'cw'
  26790. };
  26791. const GPUCullMode = {
  26792. None: 'none',
  26793. Front: 'front',
  26794. Back: 'back'
  26795. };
  26796. const GPUIndexFormat = {
  26797. Uint16: 'uint16',
  26798. Uint32: 'uint32'
  26799. };
  26800. const GPUTextureFormat = {
  26801. // 8-bit formats
  26802. R8Unorm: 'r8unorm',
  26803. R8Snorm: 'r8snorm',
  26804. R8Uint: 'r8uint',
  26805. R8Sint: 'r8sint',
  26806. // 16-bit formats
  26807. R16Uint: 'r16uint',
  26808. R16Sint: 'r16sint',
  26809. R16Float: 'r16float',
  26810. RG8Unorm: 'rg8unorm',
  26811. RG8Snorm: 'rg8snorm',
  26812. RG8Uint: 'rg8uint',
  26813. RG8Sint: 'rg8sint',
  26814. // 32-bit formats
  26815. R32Uint: 'r32uint',
  26816. R32Sint: 'r32sint',
  26817. R32Float: 'r32float',
  26818. RG16Uint: 'rg16uint',
  26819. RG16Sint: 'rg16sint',
  26820. RG16Float: 'rg16float',
  26821. RGBA8Unorm: 'rgba8unorm',
  26822. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  26823. RGBA8Snorm: 'rgba8snorm',
  26824. RGBA8Uint: 'rgba8uint',
  26825. RGBA8Sint: 'rgba8sint',
  26826. BGRA8Unorm: 'bgra8unorm',
  26827. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  26828. // Packed 32-bit formats
  26829. RGB9E5UFloat: 'rgb9e5ufloat',
  26830. RGB10A2Unorm: 'rgb10a2unorm',
  26831. RG11B10uFloat: 'rgb10a2unorm',
  26832. // 64-bit formats
  26833. RG32Uint: 'rg32uint',
  26834. RG32Sint: 'rg32sint',
  26835. RG32Float: 'rg32float',
  26836. RGBA16Uint: 'rgba16uint',
  26837. RGBA16Sint: 'rgba16sint',
  26838. RGBA16Float: 'rgba16float',
  26839. // 128-bit formats
  26840. RGBA32Uint: 'rgba32uint',
  26841. RGBA32Sint: 'rgba32sint',
  26842. RGBA32Float: 'rgba32float',
  26843. // Depth and stencil formats
  26844. Stencil8: 'stencil8',
  26845. Depth16Unorm: 'depth16unorm',
  26846. Depth24Plus: 'depth24plus',
  26847. Depth24PlusStencil8: 'depth24plus-stencil8',
  26848. Depth32Float: 'depth32float',
  26849. // 'depth32float-stencil8' extension
  26850. Depth32FloatStencil8: 'depth32float-stencil8',
  26851. // BC compressed formats usable if 'texture-compression-bc' is both
  26852. // supported by the device/user agent and enabled in requestDevice.
  26853. BC1RGBAUnorm: 'bc1-rgba-unorm',
  26854. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  26855. BC2RGBAUnorm: 'bc2-rgba-unorm',
  26856. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  26857. BC3RGBAUnorm: 'bc3-rgba-unorm',
  26858. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  26859. BC4RUnorm: 'bc4-r-unorm',
  26860. BC4RSnorm: 'bc4-r-snorm',
  26861. BC5RGUnorm: 'bc5-rg-unorm',
  26862. BC5RGSnorm: 'bc5-rg-snorm',
  26863. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  26864. BC6HRGBFloat: 'bc6h-rgb-float',
  26865. BC7RGBAUnorm: 'bc7-rgba-unorm',
  26866. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  26867. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  26868. // supported by the device/user agent and enabled in requestDevice.
  26869. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  26870. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  26871. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  26872. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  26873. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  26874. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  26875. EACR11Unorm: 'eac-r11unorm',
  26876. EACR11Snorm: 'eac-r11snorm',
  26877. EACRG11Unorm: 'eac-rg11unorm',
  26878. EACRG11Snorm: 'eac-rg11snorm',
  26879. // ASTC compressed formats usable if 'texture-compression-astc' is both
  26880. // supported by the device/user agent and enabled in requestDevice.
  26881. ASTC4x4Unorm: 'astc-4x4-unorm',
  26882. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  26883. ASTC5x4Unorm: 'astc-5x4-unorm',
  26884. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  26885. ASTC5x5Unorm: 'astc-5x5-unorm',
  26886. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  26887. ASTC6x5Unorm: 'astc-6x5-unorm',
  26888. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  26889. ASTC6x6Unorm: 'astc-6x6-unorm',
  26890. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  26891. ASTC8x5Unorm: 'astc-8x5-unorm',
  26892. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  26893. ASTC8x6Unorm: 'astc-8x6-unorm',
  26894. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  26895. ASTC8x8Unorm: 'astc-8x8-unorm',
  26896. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  26897. ASTC10x5Unorm: 'astc-10x5-unorm',
  26898. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  26899. ASTC10x6Unorm: 'astc-10x6-unorm',
  26900. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  26901. ASTC10x8Unorm: 'astc-10x8-unorm',
  26902. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  26903. ASTC10x10Unorm: 'astc-10x10-unorm',
  26904. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  26905. ASTC12x10Unorm: 'astc-12x10-unorm',
  26906. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  26907. ASTC12x12Unorm: 'astc-12x12-unorm',
  26908. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  26909. };
  26910. const GPUAddressMode = {
  26911. ClampToEdge: 'clamp-to-edge',
  26912. Repeat: 'repeat',
  26913. MirrorRepeat: 'mirror-repeat'
  26914. };
  26915. const GPUFilterMode = {
  26916. Linear: 'linear',
  26917. Nearest: 'nearest'
  26918. };
  26919. const GPUBlendFactor = {
  26920. Zero: 'zero',
  26921. One: 'one',
  26922. Src: 'src',
  26923. OneMinusSrc: 'one-minus-src',
  26924. SrcAlpha: 'src-alpha',
  26925. OneMinusSrcAlpha: 'one-minus-src-alpha',
  26926. Dst: 'dst',
  26927. OneMinusDstColor: 'one-minus-dst',
  26928. DstAlpha: 'dst-alpha',
  26929. OneMinusDstAlpha: 'one-minus-dst-alpha',
  26930. SrcAlphaSaturated: 'src-alpha-saturated',
  26931. Constant: 'constant',
  26932. OneMinusConstant: 'one-minus-constant'
  26933. };
  26934. const GPUBlendOperation = {
  26935. Add: 'add',
  26936. Subtract: 'subtract',
  26937. ReverseSubtract: 'reverse-subtract',
  26938. Min: 'min',
  26939. Max: 'max'
  26940. };
  26941. const GPUColorWriteFlags = {
  26942. None: 0,
  26943. Red: 0x1,
  26944. Green: 0x2,
  26945. Blue: 0x4,
  26946. Alpha: 0x8,
  26947. All: 0xF
  26948. };
  26949. const GPUStencilOperation = {
  26950. Keep: 'keep',
  26951. Zero: 'zero',
  26952. Replace: 'replace',
  26953. Invert: 'invert',
  26954. IncrementClamp: 'increment-clamp',
  26955. DecrementClamp: 'decrement-clamp',
  26956. IncrementWrap: 'increment-wrap',
  26957. DecrementWrap: 'decrement-wrap'
  26958. };
  26959. const GPUBufferBindingType = {
  26960. Uniform: 'uniform',
  26961. Storage: 'storage',
  26962. ReadOnlyStorage: 'read-only-storage'
  26963. };
  26964. const GPUStorageTextureAccess = {
  26965. WriteOnly: 'write-only',
  26966. ReadOnly: 'read-only',
  26967. ReadWrite: 'read-write',
  26968. };
  26969. const GPUTextureSampleType = {
  26970. Float: 'float',
  26971. UnfilterableFloat: 'unfilterable-float',
  26972. Depth: 'depth',
  26973. SInt: 'sint',
  26974. UInt: 'uint'
  26975. };
  26976. const GPUTextureDimension = {
  26977. OneD: '1d',
  26978. TwoD: '2d',
  26979. ThreeD: '3d'
  26980. };
  26981. const GPUTextureViewDimension = {
  26982. OneD: '1d',
  26983. TwoD: '2d',
  26984. TwoDArray: '2d-array',
  26985. Cube: 'cube',
  26986. CubeArray: 'cube-array',
  26987. ThreeD: '3d'
  26988. };
  26989. const GPUTextureAspect = {
  26990. All: 'all',
  26991. StencilOnly: 'stencil-only',
  26992. DepthOnly: 'depth-only'
  26993. };
  26994. const GPUInputStepMode = {
  26995. Vertex: 'vertex',
  26996. Instance: 'instance'
  26997. };
  26998. const GPUFeatureName = {
  26999. DepthClipControl: 'depth-clip-control',
  27000. Depth32FloatStencil8: 'depth32float-stencil8',
  27001. TextureCompressionBC: 'texture-compression-bc',
  27002. TextureCompressionETC2: 'texture-compression-etc2',
  27003. TextureCompressionASTC: 'texture-compression-astc',
  27004. TimestampQuery: 'timestamp-query',
  27005. IndirectFirstInstance: 'indirect-first-instance',
  27006. ShaderF16: 'shader-f16',
  27007. RG11B10UFloat: 'rg11b10ufloat-renderable',
  27008. BGRA8UNormStorage: 'bgra8unorm-storage',
  27009. Float32Filterable: 'float32-filterable',
  27010. ClipDistances: 'clip-distances',
  27011. DualSourceBlending: 'dual-source-blending',
  27012. Subgroups: 'subgroups'
  27013. };
  27014. class Sampler extends Binding {
  27015. constructor( name, texture ) {
  27016. super( name );
  27017. this.texture = texture;
  27018. this.version = texture ? texture.version : 0;
  27019. this.isSampler = true;
  27020. }
  27021. }
  27022. class NodeSampler extends Sampler {
  27023. constructor( name, textureNode, groupNode ) {
  27024. super( name, textureNode ? textureNode.value : null );
  27025. this.textureNode = textureNode;
  27026. this.groupNode = groupNode;
  27027. }
  27028. update() {
  27029. this.texture = this.textureNode.value;
  27030. }
  27031. }
  27032. class StorageBuffer extends Buffer {
  27033. constructor( name, attribute ) {
  27034. super( name, attribute ? attribute.array : null );
  27035. this.attribute = attribute;
  27036. this.isStorageBuffer = true;
  27037. }
  27038. }
  27039. let _id = 0;
  27040. class NodeStorageBuffer extends StorageBuffer {
  27041. constructor( nodeUniform, groupNode ) {
  27042. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  27043. this.nodeUniform = nodeUniform;
  27044. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  27045. this.groupNode = groupNode;
  27046. }
  27047. get buffer() {
  27048. return this.nodeUniform.value;
  27049. }
  27050. }
  27051. class WebGPUTexturePassUtils extends DataMap {
  27052. constructor( device ) {
  27053. super();
  27054. this.device = device;
  27055. const mipmapVertexSource = `
  27056. struct VarysStruct {
  27057. @builtin( position ) Position: vec4<f32>,
  27058. @location( 0 ) vTex : vec2<f32>
  27059. };
  27060. @vertex
  27061. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  27062. var Varys : VarysStruct;
  27063. var pos = array< vec2<f32>, 4 >(
  27064. vec2<f32>( -1.0, 1.0 ),
  27065. vec2<f32>( 1.0, 1.0 ),
  27066. vec2<f32>( -1.0, -1.0 ),
  27067. vec2<f32>( 1.0, -1.0 )
  27068. );
  27069. var tex = array< vec2<f32>, 4 >(
  27070. vec2<f32>( 0.0, 0.0 ),
  27071. vec2<f32>( 1.0, 0.0 ),
  27072. vec2<f32>( 0.0, 1.0 ),
  27073. vec2<f32>( 1.0, 1.0 )
  27074. );
  27075. Varys.vTex = tex[ vertexIndex ];
  27076. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  27077. return Varys;
  27078. }
  27079. `;
  27080. const mipmapFragmentSource = `
  27081. @group( 0 ) @binding( 0 )
  27082. var imgSampler : sampler;
  27083. @group( 0 ) @binding( 1 )
  27084. var img : texture_2d<f32>;
  27085. @fragment
  27086. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  27087. return textureSample( img, imgSampler, vTex );
  27088. }
  27089. `;
  27090. const flipYFragmentSource = `
  27091. @group( 0 ) @binding( 0 )
  27092. var imgSampler : sampler;
  27093. @group( 0 ) @binding( 1 )
  27094. var img : texture_2d<f32>;
  27095. @fragment
  27096. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  27097. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  27098. }
  27099. `;
  27100. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  27101. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  27102. // We'll need a new pipeline for every texture format used.
  27103. this.transferPipelines = {};
  27104. this.flipYPipelines = {};
  27105. this.mipmapVertexShaderModule = device.createShaderModule( {
  27106. label: 'mipmapVertex',
  27107. code: mipmapVertexSource
  27108. } );
  27109. this.mipmapFragmentShaderModule = device.createShaderModule( {
  27110. label: 'mipmapFragment',
  27111. code: mipmapFragmentSource
  27112. } );
  27113. this.flipYFragmentShaderModule = device.createShaderModule( {
  27114. label: 'flipYFragment',
  27115. code: flipYFragmentSource
  27116. } );
  27117. }
  27118. getTransferPipeline( format ) {
  27119. let pipeline = this.transferPipelines[ format ];
  27120. if ( pipeline === undefined ) {
  27121. pipeline = this.device.createRenderPipeline( {
  27122. label: `mipmap-${ format }`,
  27123. vertex: {
  27124. module: this.mipmapVertexShaderModule,
  27125. entryPoint: 'main'
  27126. },
  27127. fragment: {
  27128. module: this.mipmapFragmentShaderModule,
  27129. entryPoint: 'main',
  27130. targets: [ { format } ]
  27131. },
  27132. primitive: {
  27133. topology: GPUPrimitiveTopology.TriangleStrip,
  27134. stripIndexFormat: GPUIndexFormat.Uint32
  27135. },
  27136. layout: 'auto'
  27137. } );
  27138. this.transferPipelines[ format ] = pipeline;
  27139. }
  27140. return pipeline;
  27141. }
  27142. getFlipYPipeline( format ) {
  27143. let pipeline = this.flipYPipelines[ format ];
  27144. if ( pipeline === undefined ) {
  27145. pipeline = this.device.createRenderPipeline( {
  27146. label: `flipY-${ format }`,
  27147. vertex: {
  27148. module: this.mipmapVertexShaderModule,
  27149. entryPoint: 'main'
  27150. },
  27151. fragment: {
  27152. module: this.flipYFragmentShaderModule,
  27153. entryPoint: 'main',
  27154. targets: [ { format } ]
  27155. },
  27156. primitive: {
  27157. topology: GPUPrimitiveTopology.TriangleStrip,
  27158. stripIndexFormat: GPUIndexFormat.Uint32
  27159. },
  27160. layout: 'auto'
  27161. } );
  27162. this.flipYPipelines[ format ] = pipeline;
  27163. }
  27164. return pipeline;
  27165. }
  27166. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  27167. const format = textureGPUDescriptor.format;
  27168. const { width, height } = textureGPUDescriptor.size;
  27169. const transferPipeline = this.getTransferPipeline( format );
  27170. const flipYPipeline = this.getFlipYPipeline( format );
  27171. const tempTexture = this.device.createTexture( {
  27172. size: { width, height, depthOrArrayLayers: 1 },
  27173. format,
  27174. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  27175. } );
  27176. const srcView = textureGPU.createView( {
  27177. baseMipLevel: 0,
  27178. mipLevelCount: 1,
  27179. dimension: GPUTextureViewDimension.TwoD,
  27180. baseArrayLayer
  27181. } );
  27182. const dstView = tempTexture.createView( {
  27183. baseMipLevel: 0,
  27184. mipLevelCount: 1,
  27185. dimension: GPUTextureViewDimension.TwoD,
  27186. baseArrayLayer: 0
  27187. } );
  27188. const commandEncoder = this.device.createCommandEncoder( {} );
  27189. const pass = ( pipeline, sourceView, destinationView ) => {
  27190. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  27191. const bindGroup = this.device.createBindGroup( {
  27192. layout: bindGroupLayout,
  27193. entries: [ {
  27194. binding: 0,
  27195. resource: this.flipYSampler
  27196. }, {
  27197. binding: 1,
  27198. resource: sourceView
  27199. } ]
  27200. } );
  27201. const passEncoder = commandEncoder.beginRenderPass( {
  27202. colorAttachments: [ {
  27203. view: destinationView,
  27204. loadOp: GPULoadOp.Clear,
  27205. storeOp: GPUStoreOp.Store,
  27206. clearValue: [ 0, 0, 0, 0 ]
  27207. } ]
  27208. } );
  27209. passEncoder.setPipeline( pipeline );
  27210. passEncoder.setBindGroup( 0, bindGroup );
  27211. passEncoder.draw( 4, 1, 0, 0 );
  27212. passEncoder.end();
  27213. };
  27214. pass( transferPipeline, srcView, dstView );
  27215. pass( flipYPipeline, dstView, srcView );
  27216. this.device.queue.submit( [ commandEncoder.finish() ] );
  27217. tempTexture.destroy();
  27218. }
  27219. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  27220. const textureData = this.get( textureGPU );
  27221. if ( textureData.useCount === undefined ) {
  27222. textureData.useCount = 0;
  27223. textureData.layers = [];
  27224. }
  27225. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  27226. const commandEncoder = this.device.createCommandEncoder( {} );
  27227. this._mipmapRunBundles( commandEncoder, passes );
  27228. this.device.queue.submit( [ commandEncoder.finish() ] );
  27229. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  27230. textureData.useCount ++;
  27231. }
  27232. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  27233. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  27234. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  27235. let srcView = textureGPU.createView( {
  27236. baseMipLevel: 0,
  27237. mipLevelCount: 1,
  27238. dimension: GPUTextureViewDimension.TwoD,
  27239. baseArrayLayer
  27240. } );
  27241. const passes = [];
  27242. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  27243. const bindGroup = this.device.createBindGroup( {
  27244. layout: bindGroupLayout,
  27245. entries: [ {
  27246. binding: 0,
  27247. resource: this.mipmapSampler
  27248. }, {
  27249. binding: 1,
  27250. resource: srcView
  27251. } ]
  27252. } );
  27253. const dstView = textureGPU.createView( {
  27254. baseMipLevel: i,
  27255. mipLevelCount: 1,
  27256. dimension: GPUTextureViewDimension.TwoD,
  27257. baseArrayLayer
  27258. } );
  27259. const passDescriptor = {
  27260. colorAttachments: [ {
  27261. view: dstView,
  27262. loadOp: GPULoadOp.Clear,
  27263. storeOp: GPUStoreOp.Store,
  27264. clearValue: [ 0, 0, 0, 0 ]
  27265. } ]
  27266. };
  27267. const passEncoder = this.device.createRenderBundleEncoder( {
  27268. colorFormats: [ textureGPUDescriptor.format ]
  27269. } );
  27270. passEncoder.setPipeline( pipeline );
  27271. passEncoder.setBindGroup( 0, bindGroup );
  27272. passEncoder.draw( 4, 1, 0, 0 );
  27273. passes.push( {
  27274. renderBundles: [ passEncoder.finish() ],
  27275. passDescriptor
  27276. } );
  27277. srcView = dstView;
  27278. }
  27279. return passes;
  27280. }
  27281. _mipmapRunBundles( commandEncoder, passes ) {
  27282. const levels = passes.length;
  27283. for ( let i = 0; i < levels; i ++ ) {
  27284. const pass = passes[ i ];
  27285. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  27286. passEncoder.executeBundles( pass.renderBundles );
  27287. passEncoder.end();
  27288. }
  27289. }
  27290. }
  27291. const _compareToWebGPU = {
  27292. [ NeverCompare ]: 'never',
  27293. [ LessCompare ]: 'less',
  27294. [ EqualCompare ]: 'equal',
  27295. [ LessEqualCompare ]: 'less-equal',
  27296. [ GreaterCompare ]: 'greater',
  27297. [ GreaterEqualCompare ]: 'greater-equal',
  27298. [ AlwaysCompare ]: 'always',
  27299. [ NotEqualCompare ]: 'not-equal'
  27300. };
  27301. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  27302. class WebGPUTextureUtils {
  27303. constructor( backend ) {
  27304. this.backend = backend;
  27305. this._passUtils = null;
  27306. this.defaultTexture = {};
  27307. this.defaultCubeTexture = {};
  27308. this.defaultVideoFrame = null;
  27309. this.colorBuffer = null;
  27310. this.depthTexture = new DepthTexture();
  27311. this.depthTexture.name = 'depthBuffer';
  27312. }
  27313. createSampler( texture ) {
  27314. const backend = this.backend;
  27315. const device = backend.device;
  27316. const textureGPU = backend.get( texture );
  27317. const samplerDescriptorGPU = {
  27318. addressModeU: this._convertAddressMode( texture.wrapS ),
  27319. addressModeV: this._convertAddressMode( texture.wrapT ),
  27320. addressModeW: this._convertAddressMode( texture.wrapR ),
  27321. magFilter: this._convertFilterMode( texture.magFilter ),
  27322. minFilter: this._convertFilterMode( texture.minFilter ),
  27323. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  27324. maxAnisotropy: 1
  27325. };
  27326. // anisotropy can only be used when all filter modes are set to linear.
  27327. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  27328. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  27329. }
  27330. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  27331. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  27332. }
  27333. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  27334. }
  27335. createDefaultTexture( texture ) {
  27336. let textureGPU;
  27337. const format = getFormat( texture );
  27338. if ( texture.isCubeTexture ) {
  27339. textureGPU = this._getDefaultCubeTextureGPU( format );
  27340. } else if ( texture.isVideoTexture ) {
  27341. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  27342. } else {
  27343. textureGPU = this._getDefaultTextureGPU( format );
  27344. }
  27345. this.backend.get( texture ).texture = textureGPU;
  27346. }
  27347. createTexture( texture, options = {} ) {
  27348. const backend = this.backend;
  27349. const textureData = backend.get( texture );
  27350. if ( textureData.initialized ) {
  27351. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  27352. }
  27353. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  27354. if ( options.levels === undefined ) options.levels = 1;
  27355. if ( options.depth === undefined ) options.depth = 1;
  27356. const { width, height, depth, levels } = options;
  27357. if ( texture.isFramebufferTexture ) {
  27358. if ( options.renderTarget ) {
  27359. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  27360. } else {
  27361. options.format = this.backend.utils.getPreferredCanvasFormat();
  27362. }
  27363. }
  27364. const dimension = this._getDimension( texture );
  27365. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  27366. textureData.format = format;
  27367. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  27368. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  27369. if ( texture.isStorageTexture === true ) {
  27370. usage |= GPUTextureUsage.STORAGE_BINDING;
  27371. }
  27372. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  27373. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  27374. }
  27375. const textureDescriptorGPU = {
  27376. label: texture.name,
  27377. size: {
  27378. width: width,
  27379. height: height,
  27380. depthOrArrayLayers: depth,
  27381. },
  27382. mipLevelCount: levels,
  27383. sampleCount: primarySamples,
  27384. dimension: dimension,
  27385. format: format,
  27386. usage: usage
  27387. };
  27388. // texture creation
  27389. if ( texture.isVideoTexture ) {
  27390. const video = texture.source.data;
  27391. const videoFrame = new VideoFrame( video );
  27392. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  27393. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  27394. videoFrame.close();
  27395. textureData.externalTexture = video;
  27396. } else {
  27397. if ( format === undefined ) {
  27398. console.warn( 'WebGPURenderer: Texture format not supported.' );
  27399. return this.createDefaultTexture( texture );
  27400. }
  27401. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  27402. }
  27403. if ( isMSAA ) {
  27404. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  27405. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  27406. msaaTextureDescriptorGPU.sampleCount = samples;
  27407. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  27408. }
  27409. textureData.initialized = true;
  27410. textureData.textureDescriptorGPU = textureDescriptorGPU;
  27411. }
  27412. destroyTexture( texture ) {
  27413. const backend = this.backend;
  27414. const textureData = backend.get( texture );
  27415. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  27416. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  27417. backend.delete( texture );
  27418. }
  27419. destroySampler( texture ) {
  27420. const backend = this.backend;
  27421. const textureData = backend.get( texture );
  27422. delete textureData.sampler;
  27423. }
  27424. generateMipmaps( texture ) {
  27425. const textureData = this.backend.get( texture );
  27426. if ( texture.isCubeTexture ) {
  27427. for ( let i = 0; i < 6; i ++ ) {
  27428. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  27429. }
  27430. } else {
  27431. const depth = texture.image.depth || 1;
  27432. for ( let i = 0; i < depth; i ++ ) {
  27433. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  27434. }
  27435. }
  27436. }
  27437. getColorBuffer() {
  27438. if ( this.colorBuffer ) this.colorBuffer.destroy();
  27439. const backend = this.backend;
  27440. const { width, height } = backend.getDrawingBufferSize();
  27441. this.colorBuffer = backend.device.createTexture( {
  27442. label: 'colorBuffer',
  27443. size: {
  27444. width: width,
  27445. height: height,
  27446. depthOrArrayLayers: 1
  27447. },
  27448. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  27449. format: backend.utils.getPreferredCanvasFormat(),
  27450. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  27451. } );
  27452. return this.colorBuffer;
  27453. }
  27454. getDepthBuffer( depth = true, stencil = false ) {
  27455. const backend = this.backend;
  27456. const { width, height } = backend.getDrawingBufferSize();
  27457. const depthTexture = this.depthTexture;
  27458. const depthTextureGPU = backend.get( depthTexture ).texture;
  27459. let format, type;
  27460. if ( stencil ) {
  27461. format = DepthStencilFormat;
  27462. type = UnsignedInt248Type;
  27463. } else if ( depth ) {
  27464. format = DepthFormat;
  27465. type = UnsignedIntType;
  27466. }
  27467. if ( depthTextureGPU !== undefined ) {
  27468. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  27469. return depthTextureGPU;
  27470. }
  27471. this.destroyTexture( depthTexture );
  27472. }
  27473. depthTexture.name = 'depthBuffer';
  27474. depthTexture.format = format;
  27475. depthTexture.type = type;
  27476. depthTexture.image.width = width;
  27477. depthTexture.image.height = height;
  27478. this.createTexture( depthTexture, { width, height } );
  27479. return backend.get( depthTexture ).texture;
  27480. }
  27481. updateTexture( texture, options ) {
  27482. const textureData = this.backend.get( texture );
  27483. const { textureDescriptorGPU } = textureData;
  27484. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  27485. return;
  27486. // transfer texture data
  27487. if ( texture.isDataTexture ) {
  27488. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  27489. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  27490. for ( let i = 0; i < options.image.depth; i ++ ) {
  27491. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  27492. }
  27493. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  27494. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  27495. } else if ( texture.isCubeTexture ) {
  27496. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  27497. } else if ( texture.isVideoTexture ) {
  27498. const video = texture.source.data;
  27499. textureData.externalTexture = video;
  27500. } else {
  27501. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  27502. }
  27503. //
  27504. textureData.version = texture.version;
  27505. if ( texture.onUpdate ) texture.onUpdate( texture );
  27506. }
  27507. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  27508. const device = this.backend.device;
  27509. const textureData = this.backend.get( texture );
  27510. const textureGPU = textureData.texture;
  27511. const format = textureData.textureDescriptorGPU.format;
  27512. const bytesPerTexel = this._getBytesPerTexel( format );
  27513. let bytesPerRow = width * bytesPerTexel;
  27514. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  27515. const readBuffer = device.createBuffer(
  27516. {
  27517. size: width * height * bytesPerTexel,
  27518. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  27519. }
  27520. );
  27521. const encoder = device.createCommandEncoder();
  27522. encoder.copyTextureToBuffer(
  27523. {
  27524. texture: textureGPU,
  27525. origin: { x, y, z: faceIndex },
  27526. },
  27527. {
  27528. buffer: readBuffer,
  27529. bytesPerRow: bytesPerRow
  27530. },
  27531. {
  27532. width: width,
  27533. height: height
  27534. }
  27535. );
  27536. const typedArrayType = this._getTypedArrayType( format );
  27537. device.queue.submit( [ encoder.finish() ] );
  27538. await readBuffer.mapAsync( GPUMapMode.READ );
  27539. const buffer = readBuffer.getMappedRange();
  27540. return new typedArrayType( buffer );
  27541. }
  27542. _isEnvironmentTexture( texture ) {
  27543. const mapping = texture.mapping;
  27544. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  27545. }
  27546. _getDefaultTextureGPU( format ) {
  27547. let defaultTexture = this.defaultTexture[ format ];
  27548. if ( defaultTexture === undefined ) {
  27549. const texture = new Texture();
  27550. texture.minFilter = NearestFilter;
  27551. texture.magFilter = NearestFilter;
  27552. this.createTexture( texture, { width: 1, height: 1, format } );
  27553. this.defaultTexture[ format ] = defaultTexture = texture;
  27554. }
  27555. return this.backend.get( defaultTexture ).texture;
  27556. }
  27557. _getDefaultCubeTextureGPU( format ) {
  27558. let defaultCubeTexture = this.defaultTexture[ format ];
  27559. if ( defaultCubeTexture === undefined ) {
  27560. const texture = new CubeTexture();
  27561. texture.minFilter = NearestFilter;
  27562. texture.magFilter = NearestFilter;
  27563. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  27564. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  27565. }
  27566. return this.backend.get( defaultCubeTexture ).texture;
  27567. }
  27568. _getDefaultVideoFrame() {
  27569. let defaultVideoFrame = this.defaultVideoFrame;
  27570. if ( defaultVideoFrame === null ) {
  27571. const init = {
  27572. timestamp: 0,
  27573. codedWidth: 1,
  27574. codedHeight: 1,
  27575. format: 'RGBA',
  27576. };
  27577. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  27578. }
  27579. return defaultVideoFrame;
  27580. }
  27581. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  27582. for ( let i = 0; i < 6; i ++ ) {
  27583. const image = images[ i ];
  27584. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  27585. if ( image.isDataTexture ) {
  27586. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  27587. } else {
  27588. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  27589. }
  27590. }
  27591. }
  27592. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  27593. const device = this.backend.device;
  27594. device.queue.copyExternalImageToTexture(
  27595. {
  27596. source: image
  27597. }, {
  27598. texture: textureGPU,
  27599. mipLevel: 0,
  27600. origin: { x: 0, y: 0, z: originDepth }
  27601. }, {
  27602. width: image.width,
  27603. height: image.height,
  27604. depthOrArrayLayers: 1
  27605. }
  27606. );
  27607. if ( flipY === true ) {
  27608. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  27609. }
  27610. }
  27611. _getPassUtils() {
  27612. let passUtils = this._passUtils;
  27613. if ( passUtils === null ) {
  27614. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  27615. }
  27616. return passUtils;
  27617. }
  27618. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  27619. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  27620. }
  27621. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  27622. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  27623. }
  27624. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  27625. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  27626. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  27627. const device = this.backend.device;
  27628. const data = image.data;
  27629. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  27630. const bytesPerRow = image.width * bytesPerTexel;
  27631. device.queue.writeTexture(
  27632. {
  27633. texture: textureGPU,
  27634. mipLevel: 0,
  27635. origin: { x: 0, y: 0, z: originDepth }
  27636. },
  27637. data,
  27638. {
  27639. offset: image.width * image.height * bytesPerTexel * depth,
  27640. bytesPerRow
  27641. },
  27642. {
  27643. width: image.width,
  27644. height: image.height,
  27645. depthOrArrayLayers: 1
  27646. } );
  27647. if ( flipY === true ) {
  27648. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  27649. }
  27650. }
  27651. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  27652. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  27653. const device = this.backend.device;
  27654. const blockData = this._getBlockData( textureDescriptorGPU.format );
  27655. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  27656. for ( let i = 0; i < mipmaps.length; i ++ ) {
  27657. const mipmap = mipmaps[ i ];
  27658. const width = mipmap.width;
  27659. const height = mipmap.height;
  27660. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  27661. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  27662. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  27663. for ( let j = 0; j < depth; j ++ ) {
  27664. device.queue.writeTexture(
  27665. {
  27666. texture: textureGPU,
  27667. mipLevel: i,
  27668. origin: { x: 0, y: 0, z: j }
  27669. },
  27670. mipmap.data,
  27671. {
  27672. offset: j * bytesPerImage,
  27673. bytesPerRow,
  27674. rowsPerImage: Math.ceil( height / blockData.height )
  27675. },
  27676. {
  27677. width: Math.ceil( width / blockData.width ) * blockData.width,
  27678. height: Math.ceil( height / blockData.height ) * blockData.height,
  27679. depthOrArrayLayers: 1
  27680. }
  27681. );
  27682. }
  27683. }
  27684. }
  27685. _getBlockData( format ) {
  27686. // this method is only relevant for compressed texture formats
  27687. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  27688. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  27689. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  27690. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  27691. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  27692. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  27693. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  27694. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  27695. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  27696. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  27697. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  27698. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  27699. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  27700. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  27701. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  27702. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  27703. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  27704. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  27705. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  27706. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  27707. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  27708. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  27709. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  27710. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  27711. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  27712. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  27713. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  27714. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  27715. }
  27716. _convertAddressMode( value ) {
  27717. let addressMode = GPUAddressMode.ClampToEdge;
  27718. if ( value === RepeatWrapping ) {
  27719. addressMode = GPUAddressMode.Repeat;
  27720. } else if ( value === MirroredRepeatWrapping ) {
  27721. addressMode = GPUAddressMode.MirrorRepeat;
  27722. }
  27723. return addressMode;
  27724. }
  27725. _convertFilterMode( value ) {
  27726. let filterMode = GPUFilterMode.Linear;
  27727. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  27728. filterMode = GPUFilterMode.Nearest;
  27729. }
  27730. return filterMode;
  27731. }
  27732. _getBytesPerTexel( format ) {
  27733. // 8-bit formats
  27734. if ( format === GPUTextureFormat.R8Unorm ||
  27735. format === GPUTextureFormat.R8Snorm ||
  27736. format === GPUTextureFormat.R8Uint ||
  27737. format === GPUTextureFormat.R8Sint ) return 1;
  27738. // 16-bit formats
  27739. if ( format === GPUTextureFormat.R16Uint ||
  27740. format === GPUTextureFormat.R16Sint ||
  27741. format === GPUTextureFormat.R16Float ||
  27742. format === GPUTextureFormat.RG8Unorm ||
  27743. format === GPUTextureFormat.RG8Snorm ||
  27744. format === GPUTextureFormat.RG8Uint ||
  27745. format === GPUTextureFormat.RG8Sint ) return 2;
  27746. // 32-bit formats
  27747. if ( format === GPUTextureFormat.R32Uint ||
  27748. format === GPUTextureFormat.R32Sint ||
  27749. format === GPUTextureFormat.R32Float ||
  27750. format === GPUTextureFormat.RG16Uint ||
  27751. format === GPUTextureFormat.RG16Sint ||
  27752. format === GPUTextureFormat.RG16Float ||
  27753. format === GPUTextureFormat.RGBA8Unorm ||
  27754. format === GPUTextureFormat.RGBA8UnormSRGB ||
  27755. format === GPUTextureFormat.RGBA8Snorm ||
  27756. format === GPUTextureFormat.RGBA8Uint ||
  27757. format === GPUTextureFormat.RGBA8Sint ||
  27758. format === GPUTextureFormat.BGRA8Unorm ||
  27759. format === GPUTextureFormat.BGRA8UnormSRGB ||
  27760. // Packed 32-bit formats
  27761. format === GPUTextureFormat.RGB9E5UFloat ||
  27762. format === GPUTextureFormat.RGB10A2Unorm ||
  27763. format === GPUTextureFormat.RG11B10UFloat ||
  27764. format === GPUTextureFormat.Depth32Float ||
  27765. format === GPUTextureFormat.Depth24Plus ||
  27766. format === GPUTextureFormat.Depth24PlusStencil8 ||
  27767. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  27768. // 64-bit formats
  27769. if ( format === GPUTextureFormat.RG32Uint ||
  27770. format === GPUTextureFormat.RG32Sint ||
  27771. format === GPUTextureFormat.RG32Float ||
  27772. format === GPUTextureFormat.RGBA16Uint ||
  27773. format === GPUTextureFormat.RGBA16Sint ||
  27774. format === GPUTextureFormat.RGBA16Float ) return 8;
  27775. // 128-bit formats
  27776. if ( format === GPUTextureFormat.RGBA32Uint ||
  27777. format === GPUTextureFormat.RGBA32Sint ||
  27778. format === GPUTextureFormat.RGBA32Float ) return 16;
  27779. }
  27780. _getTypedArrayType( format ) {
  27781. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  27782. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  27783. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  27784. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  27785. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  27786. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  27787. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  27788. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  27789. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  27790. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  27791. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  27792. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  27793. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  27794. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  27795. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  27796. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  27797. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  27798. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  27799. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  27800. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  27801. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  27802. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  27803. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  27804. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  27805. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  27806. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  27807. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  27808. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  27809. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  27810. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  27811. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  27812. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  27813. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  27814. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  27815. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  27816. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  27817. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  27818. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  27819. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  27820. }
  27821. _getDimension( texture ) {
  27822. let dimension;
  27823. if ( texture.isData3DTexture ) {
  27824. dimension = GPUTextureDimension.ThreeD;
  27825. } else {
  27826. dimension = GPUTextureDimension.TwoD;
  27827. }
  27828. return dimension;
  27829. }
  27830. }
  27831. function getFormat( texture, device = null ) {
  27832. const format = texture.format;
  27833. const type = texture.type;
  27834. const colorSpace = texture.colorSpace;
  27835. let formatGPU;
  27836. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  27837. switch ( format ) {
  27838. case RGBA_S3TC_DXT1_Format:
  27839. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  27840. break;
  27841. case RGBA_S3TC_DXT3_Format:
  27842. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  27843. break;
  27844. case RGBA_S3TC_DXT5_Format:
  27845. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  27846. break;
  27847. case RGB_ETC2_Format:
  27848. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  27849. break;
  27850. case RGBA_ETC2_EAC_Format:
  27851. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  27852. break;
  27853. case RGBA_ASTC_4x4_Format:
  27854. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  27855. break;
  27856. case RGBA_ASTC_5x4_Format:
  27857. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  27858. break;
  27859. case RGBA_ASTC_5x5_Format:
  27860. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  27861. break;
  27862. case RGBA_ASTC_6x5_Format:
  27863. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  27864. break;
  27865. case RGBA_ASTC_6x6_Format:
  27866. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  27867. break;
  27868. case RGBA_ASTC_8x5_Format:
  27869. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  27870. break;
  27871. case RGBA_ASTC_8x6_Format:
  27872. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  27873. break;
  27874. case RGBA_ASTC_8x8_Format:
  27875. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  27876. break;
  27877. case RGBA_ASTC_10x5_Format:
  27878. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  27879. break;
  27880. case RGBA_ASTC_10x6_Format:
  27881. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  27882. break;
  27883. case RGBA_ASTC_10x8_Format:
  27884. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  27885. break;
  27886. case RGBA_ASTC_10x10_Format:
  27887. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  27888. break;
  27889. case RGBA_ASTC_12x10_Format:
  27890. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  27891. break;
  27892. case RGBA_ASTC_12x12_Format:
  27893. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  27894. break;
  27895. case RGBAFormat:
  27896. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27897. break;
  27898. default:
  27899. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  27900. }
  27901. } else {
  27902. switch ( format ) {
  27903. case RGBAFormat:
  27904. switch ( type ) {
  27905. case ByteType:
  27906. formatGPU = GPUTextureFormat.RGBA8Snorm;
  27907. break;
  27908. case ShortType:
  27909. formatGPU = GPUTextureFormat.RGBA16Sint;
  27910. break;
  27911. case UnsignedShortType:
  27912. formatGPU = GPUTextureFormat.RGBA16Uint;
  27913. break;
  27914. case UnsignedIntType:
  27915. formatGPU = GPUTextureFormat.RGBA32Uint;
  27916. break;
  27917. case IntType:
  27918. formatGPU = GPUTextureFormat.RGBA32Sint;
  27919. break;
  27920. case UnsignedByteType:
  27921. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27922. break;
  27923. case HalfFloatType:
  27924. formatGPU = GPUTextureFormat.RGBA16Float;
  27925. break;
  27926. case FloatType:
  27927. formatGPU = GPUTextureFormat.RGBA32Float;
  27928. break;
  27929. default:
  27930. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  27931. }
  27932. break;
  27933. case RGBFormat:
  27934. switch ( type ) {
  27935. case UnsignedInt5999Type:
  27936. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  27937. break;
  27938. default:
  27939. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  27940. }
  27941. break;
  27942. case RedFormat:
  27943. switch ( type ) {
  27944. case ByteType:
  27945. formatGPU = GPUTextureFormat.R8Snorm;
  27946. break;
  27947. case ShortType:
  27948. formatGPU = GPUTextureFormat.R16Sint;
  27949. break;
  27950. case UnsignedShortType:
  27951. formatGPU = GPUTextureFormat.R16Uint;
  27952. break;
  27953. case UnsignedIntType:
  27954. formatGPU = GPUTextureFormat.R32Uint;
  27955. break;
  27956. case IntType:
  27957. formatGPU = GPUTextureFormat.R32Sint;
  27958. break;
  27959. case UnsignedByteType:
  27960. formatGPU = GPUTextureFormat.R8Unorm;
  27961. break;
  27962. case HalfFloatType:
  27963. formatGPU = GPUTextureFormat.R16Float;
  27964. break;
  27965. case FloatType:
  27966. formatGPU = GPUTextureFormat.R32Float;
  27967. break;
  27968. default:
  27969. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  27970. }
  27971. break;
  27972. case RGFormat:
  27973. switch ( type ) {
  27974. case ByteType:
  27975. formatGPU = GPUTextureFormat.RG8Snorm;
  27976. break;
  27977. case ShortType:
  27978. formatGPU = GPUTextureFormat.RG16Sint;
  27979. break;
  27980. case UnsignedShortType:
  27981. formatGPU = GPUTextureFormat.RG16Uint;
  27982. break;
  27983. case UnsignedIntType:
  27984. formatGPU = GPUTextureFormat.RG32Uint;
  27985. break;
  27986. case IntType:
  27987. formatGPU = GPUTextureFormat.RG32Sint;
  27988. break;
  27989. case UnsignedByteType:
  27990. formatGPU = GPUTextureFormat.RG8Unorm;
  27991. break;
  27992. case HalfFloatType:
  27993. formatGPU = GPUTextureFormat.RG16Float;
  27994. break;
  27995. case FloatType:
  27996. formatGPU = GPUTextureFormat.RG32Float;
  27997. break;
  27998. default:
  27999. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  28000. }
  28001. break;
  28002. case DepthFormat:
  28003. switch ( type ) {
  28004. case UnsignedShortType:
  28005. formatGPU = GPUTextureFormat.Depth16Unorm;
  28006. break;
  28007. case UnsignedIntType:
  28008. formatGPU = GPUTextureFormat.Depth24Plus;
  28009. break;
  28010. case FloatType:
  28011. formatGPU = GPUTextureFormat.Depth32Float;
  28012. break;
  28013. default:
  28014. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  28015. }
  28016. break;
  28017. case DepthStencilFormat:
  28018. switch ( type ) {
  28019. case UnsignedInt248Type:
  28020. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  28021. break;
  28022. case FloatType:
  28023. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  28024. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  28025. }
  28026. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  28027. break;
  28028. default:
  28029. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  28030. }
  28031. break;
  28032. case RedIntegerFormat:
  28033. switch ( type ) {
  28034. case IntType:
  28035. formatGPU = GPUTextureFormat.R32Sint;
  28036. break;
  28037. case UnsignedIntType:
  28038. formatGPU = GPUTextureFormat.R32Uint;
  28039. break;
  28040. default:
  28041. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  28042. }
  28043. break;
  28044. case RGIntegerFormat:
  28045. switch ( type ) {
  28046. case IntType:
  28047. formatGPU = GPUTextureFormat.RG32Sint;
  28048. break;
  28049. case UnsignedIntType:
  28050. formatGPU = GPUTextureFormat.RG32Uint;
  28051. break;
  28052. default:
  28053. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  28054. }
  28055. break;
  28056. case RGBAIntegerFormat:
  28057. switch ( type ) {
  28058. case IntType:
  28059. formatGPU = GPUTextureFormat.RGBA32Sint;
  28060. break;
  28061. case UnsignedIntType:
  28062. formatGPU = GPUTextureFormat.RGBA32Uint;
  28063. break;
  28064. default:
  28065. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  28066. }
  28067. break;
  28068. default:
  28069. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  28070. }
  28071. }
  28072. return formatGPU;
  28073. }
  28074. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  28075. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  28076. const wgslTypeLib$1 = {
  28077. 'f32': 'float',
  28078. 'i32': 'int',
  28079. 'u32': 'uint',
  28080. 'bool': 'bool',
  28081. 'vec2<f32>': 'vec2',
  28082. 'vec2<i32>': 'ivec2',
  28083. 'vec2<u32>': 'uvec2',
  28084. 'vec2<bool>': 'bvec2',
  28085. 'vec2f': 'vec2',
  28086. 'vec2i': 'ivec2',
  28087. 'vec2u': 'uvec2',
  28088. 'vec2b': 'bvec2',
  28089. 'vec3<f32>': 'vec3',
  28090. 'vec3<i32>': 'ivec3',
  28091. 'vec3<u32>': 'uvec3',
  28092. 'vec3<bool>': 'bvec3',
  28093. 'vec3f': 'vec3',
  28094. 'vec3i': 'ivec3',
  28095. 'vec3u': 'uvec3',
  28096. 'vec3b': 'bvec3',
  28097. 'vec4<f32>': 'vec4',
  28098. 'vec4<i32>': 'ivec4',
  28099. 'vec4<u32>': 'uvec4',
  28100. 'vec4<bool>': 'bvec4',
  28101. 'vec4f': 'vec4',
  28102. 'vec4i': 'ivec4',
  28103. 'vec4u': 'uvec4',
  28104. 'vec4b': 'bvec4',
  28105. 'mat2x2<f32>': 'mat2',
  28106. 'mat2x2f': 'mat2',
  28107. 'mat3x3<f32>': 'mat3',
  28108. 'mat3x3f': 'mat3',
  28109. 'mat4x4<f32>': 'mat4',
  28110. 'mat4x4f': 'mat4',
  28111. 'sampler': 'sampler',
  28112. 'texture_1d': 'texture',
  28113. 'texture_2d': 'texture',
  28114. 'texture_2d_array': 'texture',
  28115. 'texture_multisampled_2d': 'cubeTexture',
  28116. 'texture_depth_2d': 'depthTexture',
  28117. 'texture_3d': 'texture3D',
  28118. 'texture_cube': 'cubeTexture',
  28119. 'texture_cube_array': 'cubeTexture',
  28120. 'texture_storage_1d': 'storageTexture',
  28121. 'texture_storage_2d': 'storageTexture',
  28122. 'texture_storage_2d_array': 'storageTexture',
  28123. 'texture_storage_3d': 'storageTexture'
  28124. };
  28125. const parse = ( source ) => {
  28126. source = source.trim();
  28127. const declaration = source.match( declarationRegexp );
  28128. if ( declaration !== null && declaration.length === 4 ) {
  28129. const inputsCode = declaration[ 2 ];
  28130. const propsMatches = [];
  28131. let match = null;
  28132. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  28133. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  28134. }
  28135. // Process matches to correctly pair names and types
  28136. const inputs = [];
  28137. for ( let i = 0; i < propsMatches.length; i ++ ) {
  28138. const { name, type } = propsMatches[ i ];
  28139. let resolvedType = type;
  28140. if ( resolvedType.startsWith( 'ptr' ) ) {
  28141. resolvedType = 'pointer';
  28142. } else {
  28143. if ( resolvedType.startsWith( 'texture' ) ) {
  28144. resolvedType = type.split( '<' )[ 0 ];
  28145. }
  28146. resolvedType = wgslTypeLib$1[ resolvedType ];
  28147. }
  28148. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  28149. }
  28150. const blockCode = source.substring( declaration[ 0 ].length );
  28151. const outputType = declaration[ 3 ] || 'void';
  28152. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  28153. const type = wgslTypeLib$1[ outputType ] || outputType;
  28154. return {
  28155. type,
  28156. inputs,
  28157. name,
  28158. inputsCode,
  28159. blockCode,
  28160. outputType
  28161. };
  28162. } else {
  28163. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  28164. }
  28165. };
  28166. /**
  28167. * This class represents a WSL node function.
  28168. *
  28169. * @augments NodeFunction
  28170. */
  28171. class WGSLNodeFunction extends NodeFunction {
  28172. /**
  28173. * Constructs a new WGSL node function.
  28174. *
  28175. * @param {String} source - The WGSL source.
  28176. */
  28177. constructor( source ) {
  28178. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  28179. super( type, inputs, name );
  28180. this.inputsCode = inputsCode;
  28181. this.blockCode = blockCode;
  28182. this.outputType = outputType;
  28183. }
  28184. /**
  28185. * This method returns the WGSL code of the node function.
  28186. *
  28187. * @param {String} [name=this.name] - The function's name.
  28188. * @return {String} The shader code.
  28189. */
  28190. getCode( name = this.name ) {
  28191. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  28192. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  28193. }
  28194. }
  28195. /**
  28196. * A WGSL node parser.
  28197. *
  28198. * @augments NodeParser
  28199. */
  28200. class WGSLNodeParser extends NodeParser {
  28201. /**
  28202. * The method parses the given WGSL code an returns a node function.
  28203. *
  28204. * @param {String} source - The WGSL code.
  28205. * @return {WGSLNodeFunction} A node function.
  28206. */
  28207. parseFunction( source ) {
  28208. return new WGSLNodeFunction( source );
  28209. }
  28210. }
  28211. // GPUShaderStage is not defined in browsers not supporting WebGPU
  28212. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  28213. const accessNames = {
  28214. [ NodeAccess.READ_ONLY ]: 'read',
  28215. [ NodeAccess.WRITE_ONLY ]: 'write',
  28216. [ NodeAccess.READ_WRITE ]: 'read_write'
  28217. };
  28218. const wrapNames = {
  28219. [ RepeatWrapping ]: 'repeat',
  28220. [ ClampToEdgeWrapping ]: 'clamp',
  28221. [ MirroredRepeatWrapping ]: 'mirror'
  28222. };
  28223. const gpuShaderStageLib = {
  28224. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  28225. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  28226. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  28227. };
  28228. const supports = {
  28229. instance: true,
  28230. swizzleAssign: false,
  28231. storageBuffer: true
  28232. };
  28233. const wgslFnOpLib = {
  28234. '^^': 'tsl_xor'
  28235. };
  28236. const wgslTypeLib = {
  28237. float: 'f32',
  28238. int: 'i32',
  28239. uint: 'u32',
  28240. bool: 'bool',
  28241. color: 'vec3<f32>',
  28242. vec2: 'vec2<f32>',
  28243. ivec2: 'vec2<i32>',
  28244. uvec2: 'vec2<u32>',
  28245. bvec2: 'vec2<bool>',
  28246. vec3: 'vec3<f32>',
  28247. ivec3: 'vec3<i32>',
  28248. uvec3: 'vec3<u32>',
  28249. bvec3: 'vec3<bool>',
  28250. vec4: 'vec4<f32>',
  28251. ivec4: 'vec4<i32>',
  28252. uvec4: 'vec4<u32>',
  28253. bvec4: 'vec4<bool>',
  28254. mat2: 'mat2x2<f32>',
  28255. mat3: 'mat3x3<f32>',
  28256. mat4: 'mat4x4<f32>'
  28257. };
  28258. const wgslCodeCache = {};
  28259. const wgslPolyfill = {
  28260. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  28261. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  28262. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  28263. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  28264. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  28265. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  28266. 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 ); }' ),
  28267. 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 ); }' ),
  28268. 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 ); }' ),
  28269. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  28270. 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 ); }' ),
  28271. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  28272. biquadraticTexture: new CodeNode( /* wgsl */`
  28273. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  28274. let res = vec2f( iRes );
  28275. let uvScaled = coord * res;
  28276. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  28277. // https://www.shadertoy.com/view/WtyXRy
  28278. let uv = uvWrapping - 0.5;
  28279. let iuv = floor( uv );
  28280. let f = fract( uv );
  28281. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  28282. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  28283. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  28284. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  28285. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  28286. }
  28287. ` )
  28288. };
  28289. const wgslMethods = {
  28290. dFdx: 'dpdx',
  28291. dFdy: '- dpdy',
  28292. mod_float: 'tsl_mod_float',
  28293. mod_vec2: 'tsl_mod_vec2',
  28294. mod_vec3: 'tsl_mod_vec3',
  28295. mod_vec4: 'tsl_mod_vec4',
  28296. equals_bool: 'tsl_equals_bool',
  28297. equals_bvec2: 'tsl_equals_bvec2',
  28298. equals_bvec3: 'tsl_equals_bvec3',
  28299. equals_bvec4: 'tsl_equals_bvec4',
  28300. inversesqrt: 'inverseSqrt',
  28301. bitcast: 'bitcast<f32>'
  28302. };
  28303. // WebGPU issue: does not support pow() with negative base on Windows
  28304. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  28305. 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 ); }' );
  28306. 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 ] );
  28307. 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 ] );
  28308. 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 ] );
  28309. wgslMethods.pow_float = 'tsl_pow_float';
  28310. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  28311. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  28312. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  28313. }
  28314. //
  28315. let diagnostics = '';
  28316. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  28317. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  28318. }
  28319. //
  28320. class WGSLNodeBuilder extends NodeBuilder {
  28321. constructor( object, renderer ) {
  28322. super( object, renderer, new WGSLNodeParser() );
  28323. this.uniformGroups = {};
  28324. this.builtins = {};
  28325. this.directives = {};
  28326. this.scopedArrays = new Map();
  28327. }
  28328. needsToWorkingColorSpace( texture ) {
  28329. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  28330. }
  28331. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28332. if ( shaderStage === 'fragment' ) {
  28333. if ( depthSnippet ) {
  28334. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  28335. } else {
  28336. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  28337. }
  28338. } else if ( this.isFilteredTexture( texture ) ) {
  28339. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  28340. } else {
  28341. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  28342. }
  28343. }
  28344. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  28345. if ( shaderStage === 'fragment' ) {
  28346. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  28347. } else {
  28348. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  28349. }
  28350. }
  28351. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28352. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  28353. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  28354. } else if ( this.isFilteredTexture( texture ) ) {
  28355. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  28356. } else {
  28357. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  28358. }
  28359. }
  28360. generateWrapFunction( texture ) {
  28361. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  28362. let nodeCode = wgslCodeCache[ functionName ];
  28363. if ( nodeCode === undefined ) {
  28364. const includes = [];
  28365. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  28366. const addWrapSnippet = ( wrap, axis ) => {
  28367. if ( wrap === RepeatWrapping ) {
  28368. includes.push( wgslPolyfill.repeatWrapping_float );
  28369. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  28370. } else if ( wrap === ClampToEdgeWrapping ) {
  28371. includes.push( wgslPolyfill.clampWrapping_float );
  28372. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  28373. } else if ( wrap === MirroredRepeatWrapping ) {
  28374. includes.push( wgslPolyfill.mirrorWrapping_float );
  28375. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  28376. } else {
  28377. code += `\t\tcoord.${ axis }`;
  28378. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  28379. }
  28380. };
  28381. addWrapSnippet( texture.wrapS, 'x' );
  28382. code += ',\n';
  28383. addWrapSnippet( texture.wrapT, 'y' );
  28384. code += '\n\t);\n\n}\n';
  28385. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  28386. }
  28387. nodeCode.build( this );
  28388. return functionName;
  28389. }
  28390. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  28391. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  28392. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  28393. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  28394. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  28395. let textureDimensionsParams;
  28396. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  28397. if ( primarySamples > 1 ) {
  28398. textureDimensionsParams = textureProperty;
  28399. } else {
  28400. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  28401. }
  28402. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  28403. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  28404. }
  28405. return textureDimensionNode.build( this );
  28406. }
  28407. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  28408. this._include( 'biquadraticTexture' );
  28409. const wrapFunction = this.generateWrapFunction( texture );
  28410. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  28411. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  28412. }
  28413. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  28414. const wrapFunction = this.generateWrapFunction( texture );
  28415. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  28416. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  28417. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  28418. }
  28419. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  28420. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  28421. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  28422. } else if ( depthSnippet ) {
  28423. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  28424. } else {
  28425. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  28426. }
  28427. }
  28428. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  28429. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  28430. }
  28431. isSampleCompare( texture ) {
  28432. return texture.isDepthTexture === true && texture.compareFunction !== null;
  28433. }
  28434. isUnfilterable( texture ) {
  28435. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  28436. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  28437. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  28438. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  28439. }
  28440. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28441. let snippet = null;
  28442. if ( texture.isVideoTexture === true ) {
  28443. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  28444. } else if ( this.isUnfilterable( texture ) ) {
  28445. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  28446. } else {
  28447. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  28448. }
  28449. return snippet;
  28450. }
  28451. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28452. if ( shaderStage === 'fragment' ) {
  28453. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  28454. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  28455. } else {
  28456. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  28457. }
  28458. }
  28459. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28460. if ( shaderStage === 'fragment' ) {
  28461. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  28462. } else {
  28463. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  28464. }
  28465. }
  28466. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28467. let snippet = null;
  28468. if ( texture.isVideoTexture === true ) {
  28469. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  28470. } else {
  28471. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  28472. }
  28473. return snippet;
  28474. }
  28475. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  28476. if ( shaderStage === 'fragment' ) {
  28477. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  28478. } else {
  28479. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  28480. }
  28481. }
  28482. getPropertyName( node, shaderStage = this.shaderStage ) {
  28483. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  28484. if ( shaderStage === 'vertex' ) {
  28485. return `varyings.${ node.name }`;
  28486. }
  28487. } else if ( node.isNodeUniform === true ) {
  28488. const name = node.name;
  28489. const type = node.type;
  28490. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  28491. return name;
  28492. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  28493. return `NodeBuffer_${ node.id }.${name}`;
  28494. } else {
  28495. return node.groupNode.name + '.' + name;
  28496. }
  28497. }
  28498. return super.getPropertyName( node );
  28499. }
  28500. getOutputStructName() {
  28501. return 'output';
  28502. }
  28503. _getUniformGroupCount( shaderStage ) {
  28504. return Object.keys( this.uniforms[ shaderStage ] ).length;
  28505. }
  28506. getFunctionOperator( op ) {
  28507. const fnOp = wgslFnOpLib[ op ];
  28508. if ( fnOp !== undefined ) {
  28509. this._include( fnOp );
  28510. return fnOp;
  28511. }
  28512. return null;
  28513. }
  28514. getNodeAccess( node, shaderStage ) {
  28515. if ( shaderStage !== 'compute' )
  28516. return NodeAccess.READ_ONLY;
  28517. return node.access;
  28518. }
  28519. getStorageAccess( node, shaderStage ) {
  28520. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  28521. }
  28522. getUniformFromNode( node, type, shaderStage, name = null ) {
  28523. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  28524. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28525. if ( nodeData.uniformGPU === undefined ) {
  28526. let uniformGPU;
  28527. const group = node.groupNode;
  28528. const groupName = group.name;
  28529. const bindings = this.getBindGroupArray( groupName, shaderStage );
  28530. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  28531. let texture = null;
  28532. const access = this.getNodeAccess( node, shaderStage );
  28533. if ( type === 'texture' || type === 'storageTexture' ) {
  28534. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  28535. } else if ( type === 'cubeTexture' ) {
  28536. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  28537. } else if ( type === 'texture3D' ) {
  28538. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  28539. }
  28540. texture.store = node.isStorageTextureNode === true;
  28541. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  28542. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  28543. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  28544. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  28545. bindings.push( sampler, texture );
  28546. uniformGPU = [ sampler, texture ];
  28547. } else {
  28548. bindings.push( texture );
  28549. uniformGPU = [ texture ];
  28550. }
  28551. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  28552. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  28553. const buffer = new bufferClass( node, group );
  28554. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  28555. bindings.push( buffer );
  28556. uniformGPU = buffer;
  28557. } else {
  28558. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  28559. let uniformsGroup = uniformsStage[ groupName ];
  28560. if ( uniformsGroup === undefined ) {
  28561. uniformsGroup = new NodeUniformsGroup( groupName, group );
  28562. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  28563. uniformsStage[ groupName ] = uniformsGroup;
  28564. bindings.push( uniformsGroup );
  28565. }
  28566. uniformGPU = this.getNodeUniform( uniformNode, type );
  28567. uniformsGroup.addUniform( uniformGPU );
  28568. }
  28569. nodeData.uniformGPU = uniformGPU;
  28570. }
  28571. return uniformNode;
  28572. }
  28573. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  28574. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  28575. if ( map.has( name ) === false ) {
  28576. map.set( name, {
  28577. name,
  28578. property,
  28579. type
  28580. } );
  28581. }
  28582. return property;
  28583. }
  28584. hasBuiltin( name, shaderStage = this.shaderStage ) {
  28585. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  28586. }
  28587. getVertexIndex() {
  28588. if ( this.shaderStage === 'vertex' ) {
  28589. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  28590. }
  28591. return 'vertexIndex';
  28592. }
  28593. buildFunctionCode( shaderNode ) {
  28594. const layout = shaderNode.layout;
  28595. const flowData = this.flowShaderNode( shaderNode );
  28596. const parameters = [];
  28597. for ( const input of layout.inputs ) {
  28598. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  28599. }
  28600. //
  28601. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  28602. ${ flowData.vars }
  28603. ${ flowData.code }
  28604. `;
  28605. if ( flowData.result ) {
  28606. code += `\treturn ${ flowData.result };\n`;
  28607. }
  28608. code += '\n}\n';
  28609. //
  28610. return code;
  28611. }
  28612. getInstanceIndex() {
  28613. if ( this.shaderStage === 'vertex' ) {
  28614. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  28615. }
  28616. return 'instanceIndex';
  28617. }
  28618. getInvocationLocalIndex() {
  28619. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  28620. }
  28621. getSubgroupSize() {
  28622. this.enableSubGroups();
  28623. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  28624. }
  28625. getInvocationSubgroupIndex() {
  28626. this.enableSubGroups();
  28627. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  28628. }
  28629. getSubgroupIndex() {
  28630. this.enableSubGroups();
  28631. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  28632. }
  28633. getDrawIndex() {
  28634. return null;
  28635. }
  28636. getFrontFacing() {
  28637. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  28638. }
  28639. getFragCoord() {
  28640. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  28641. }
  28642. getFragDepth() {
  28643. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  28644. }
  28645. getClipDistance() {
  28646. return 'varyings.hw_clip_distances';
  28647. }
  28648. isFlipY() {
  28649. return false;
  28650. }
  28651. enableDirective( name, shaderStage = this.shaderStage ) {
  28652. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  28653. stage.add( name );
  28654. }
  28655. getDirectives( shaderStage ) {
  28656. const snippets = [];
  28657. const directives = this.directives[ shaderStage ];
  28658. if ( directives !== undefined ) {
  28659. for ( const directive of directives ) {
  28660. snippets.push( `enable ${directive};` );
  28661. }
  28662. }
  28663. return snippets.join( '\n' );
  28664. }
  28665. enableSubGroups() {
  28666. this.enableDirective( 'subgroups' );
  28667. }
  28668. enableSubgroupsF16() {
  28669. this.enableDirective( 'subgroups-f16' );
  28670. }
  28671. enableClipDistances() {
  28672. this.enableDirective( 'clip_distances' );
  28673. }
  28674. enableShaderF16() {
  28675. this.enableDirective( 'f16' );
  28676. }
  28677. enableDualSourceBlending() {
  28678. this.enableDirective( 'dual_source_blending' );
  28679. }
  28680. enableHardwareClipping( planeCount ) {
  28681. this.enableClipDistances();
  28682. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  28683. }
  28684. getBuiltins( shaderStage ) {
  28685. const snippets = [];
  28686. const builtins = this.builtins[ shaderStage ];
  28687. if ( builtins !== undefined ) {
  28688. for ( const { name, property, type } of builtins.values() ) {
  28689. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  28690. }
  28691. }
  28692. return snippets.join( ',\n\t' );
  28693. }
  28694. getScopedArray( name, scope, bufferType, bufferCount ) {
  28695. if ( this.scopedArrays.has( name ) === false ) {
  28696. this.scopedArrays.set( name, {
  28697. name,
  28698. scope,
  28699. bufferType,
  28700. bufferCount
  28701. } );
  28702. }
  28703. return name;
  28704. }
  28705. getScopedArrays( shaderStage ) {
  28706. if ( shaderStage !== 'compute' ) {
  28707. return;
  28708. }
  28709. const snippets = [];
  28710. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  28711. const type = this.getType( bufferType );
  28712. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  28713. }
  28714. return snippets.join( '\n' );
  28715. }
  28716. getAttributes( shaderStage ) {
  28717. const snippets = [];
  28718. if ( shaderStage === 'compute' ) {
  28719. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  28720. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  28721. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  28722. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  28723. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  28724. this.enableDirective( 'subgroups', shaderStage );
  28725. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  28726. }
  28727. }
  28728. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  28729. const builtins = this.getBuiltins( 'attribute' );
  28730. if ( builtins ) snippets.push( builtins );
  28731. const attributes = this.getAttributesArray();
  28732. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  28733. const attribute = attributes[ index ];
  28734. const name = attribute.name;
  28735. const type = this.getType( attribute.type );
  28736. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  28737. }
  28738. }
  28739. return snippets.join( ',\n\t' );
  28740. }
  28741. getStructMembers( struct ) {
  28742. const snippets = [];
  28743. const members = struct.getMemberTypes();
  28744. for ( let i = 0; i < members.length; i ++ ) {
  28745. const member = members[ i ];
  28746. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  28747. }
  28748. const builtins = this.getBuiltins( 'output' );
  28749. if ( builtins ) snippets.push( '\t' + builtins );
  28750. return snippets.join( ',\n' );
  28751. }
  28752. getStructs( shaderStage ) {
  28753. const snippets = [];
  28754. const structs = this.structs[ shaderStage ];
  28755. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  28756. const struct = structs[ index ];
  28757. const name = struct.name;
  28758. let snippet = `\struct ${ name } {\n`;
  28759. snippet += this.getStructMembers( struct );
  28760. snippet += '\n}';
  28761. snippets.push( snippet );
  28762. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  28763. }
  28764. return snippets.join( '\n\n' );
  28765. }
  28766. getVar( type, name ) {
  28767. return `var ${ name } : ${ this.getType( type ) }`;
  28768. }
  28769. getVars( shaderStage ) {
  28770. const snippets = [];
  28771. const vars = this.vars[ shaderStage ];
  28772. if ( vars !== undefined ) {
  28773. for ( const variable of vars ) {
  28774. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  28775. }
  28776. }
  28777. return `\n${ snippets.join( '\n' ) }\n`;
  28778. }
  28779. getVaryings( shaderStage ) {
  28780. const snippets = [];
  28781. if ( shaderStage === 'vertex' ) {
  28782. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  28783. }
  28784. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  28785. const varyings = this.varyings;
  28786. const vars = this.vars[ shaderStage ];
  28787. for ( let index = 0; index < varyings.length; index ++ ) {
  28788. const varying = varyings[ index ];
  28789. if ( varying.needsInterpolation ) {
  28790. let attributesSnippet = `@location( ${index} )`;
  28791. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  28792. attributesSnippet += ' @interpolate( flat )';
  28793. }
  28794. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  28795. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  28796. vars.push( varying );
  28797. }
  28798. }
  28799. }
  28800. const builtins = this.getBuiltins( shaderStage );
  28801. if ( builtins ) snippets.push( builtins );
  28802. const code = snippets.join( ',\n\t' );
  28803. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  28804. }
  28805. getUniforms( shaderStage ) {
  28806. const uniforms = this.uniforms[ shaderStage ];
  28807. const bindingSnippets = [];
  28808. const bufferSnippets = [];
  28809. const structSnippets = [];
  28810. const uniformGroups = {};
  28811. for ( const uniform of uniforms ) {
  28812. const groupName = uniform.groupNode.name;
  28813. const uniformIndexes = this.bindingsIndexes[ groupName ];
  28814. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  28815. const texture = uniform.node.value;
  28816. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  28817. if ( this.isSampleCompare( texture ) ) {
  28818. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  28819. } else {
  28820. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  28821. }
  28822. }
  28823. let textureType;
  28824. let multisampled = '';
  28825. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  28826. if ( primarySamples > 1 ) {
  28827. multisampled = '_multisampled';
  28828. }
  28829. if ( texture.isCubeTexture === true ) {
  28830. textureType = 'texture_cube<f32>';
  28831. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  28832. textureType = 'texture_2d_array<f32>';
  28833. } else if ( texture.isDepthTexture === true ) {
  28834. textureType = `texture_depth${multisampled}_2d`;
  28835. } else if ( texture.isVideoTexture === true ) {
  28836. textureType = 'texture_external';
  28837. } else if ( texture.isData3DTexture === true ) {
  28838. textureType = 'texture_3d<f32>';
  28839. } else if ( uniform.node.isStorageTextureNode === true ) {
  28840. const format = getFormat( texture );
  28841. const access = this.getStorageAccess( uniform.node, shaderStage );
  28842. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  28843. } else {
  28844. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  28845. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  28846. }
  28847. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  28848. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  28849. const bufferNode = uniform.node;
  28850. const bufferType = this.getType( bufferNode.bufferType );
  28851. const bufferCount = bufferNode.bufferCount;
  28852. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  28853. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  28854. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  28855. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  28856. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  28857. } else {
  28858. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  28859. const groupName = uniform.groupNode.name;
  28860. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  28861. index: uniformIndexes.binding ++,
  28862. id: uniformIndexes.group,
  28863. snippets: []
  28864. } );
  28865. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  28866. }
  28867. }
  28868. for ( const name in uniformGroups ) {
  28869. const group = uniformGroups[ name ];
  28870. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  28871. }
  28872. let code = bindingSnippets.join( '\n' );
  28873. code += bufferSnippets.join( '\n' );
  28874. code += structSnippets.join( '\n' );
  28875. return code;
  28876. }
  28877. buildCode() {
  28878. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  28879. this.sortBindingGroups();
  28880. for ( const shaderStage in shadersData ) {
  28881. const stageData = shadersData[ shaderStage ];
  28882. stageData.uniforms = this.getUniforms( shaderStage );
  28883. stageData.attributes = this.getAttributes( shaderStage );
  28884. stageData.varyings = this.getVaryings( shaderStage );
  28885. stageData.structs = this.getStructs( shaderStage );
  28886. stageData.vars = this.getVars( shaderStage );
  28887. stageData.codes = this.getCodes( shaderStage );
  28888. stageData.directives = this.getDirectives( shaderStage );
  28889. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  28890. //
  28891. let flow = '// code\n\n';
  28892. flow += this.flowCode[ shaderStage ];
  28893. const flowNodes = this.flowNodes[ shaderStage ];
  28894. const mainNode = flowNodes[ flowNodes.length - 1 ];
  28895. const outputNode = mainNode.outputNode;
  28896. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  28897. for ( const node of flowNodes ) {
  28898. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  28899. const slotName = node.name;
  28900. if ( slotName ) {
  28901. if ( flow.length > 0 ) flow += '\n';
  28902. flow += `\t// flow -> ${ slotName }\n\t`;
  28903. }
  28904. flow += `${ flowSlotData.code }\n\t`;
  28905. if ( node === mainNode && shaderStage !== 'compute' ) {
  28906. flow += '// result\n\n\t';
  28907. if ( shaderStage === 'vertex' ) {
  28908. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  28909. } else if ( shaderStage === 'fragment' ) {
  28910. if ( isOutputStruct ) {
  28911. stageData.returnType = outputNode.nodeType;
  28912. flow += `return ${ flowSlotData.result };`;
  28913. } else {
  28914. let structSnippet = '\t@location(0) color: vec4<f32>';
  28915. const builtins = this.getBuiltins( 'output' );
  28916. if ( builtins ) structSnippet += ',\n\t' + builtins;
  28917. stageData.returnType = 'OutputStruct';
  28918. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  28919. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  28920. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  28921. }
  28922. }
  28923. }
  28924. }
  28925. stageData.flow = flow;
  28926. }
  28927. if ( this.material !== null ) {
  28928. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  28929. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  28930. } else {
  28931. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  28932. }
  28933. }
  28934. getMethod( method, output = null ) {
  28935. let wgslMethod;
  28936. if ( output !== null ) {
  28937. wgslMethod = this._getWGSLMethod( method + '_' + output );
  28938. }
  28939. if ( wgslMethod === undefined ) {
  28940. wgslMethod = this._getWGSLMethod( method );
  28941. }
  28942. return wgslMethod || method;
  28943. }
  28944. getType( type ) {
  28945. return wgslTypeLib[ type ] || type;
  28946. }
  28947. isAvailable( name ) {
  28948. let result = supports[ name ];
  28949. if ( result === undefined ) {
  28950. if ( name === 'float32Filterable' ) {
  28951. result = this.renderer.hasFeature( 'float32-filterable' );
  28952. } else if ( name === 'clipDistance' ) {
  28953. result = this.renderer.hasFeature( 'clip-distances' );
  28954. }
  28955. supports[ name ] = result;
  28956. }
  28957. return result;
  28958. }
  28959. _getWGSLMethod( method ) {
  28960. if ( wgslPolyfill[ method ] !== undefined ) {
  28961. this._include( method );
  28962. }
  28963. return wgslMethods[ method ];
  28964. }
  28965. _include( name ) {
  28966. const codeNode = wgslPolyfill[ name ];
  28967. codeNode.build( this );
  28968. if ( this.currentFunctionNode !== null ) {
  28969. this.currentFunctionNode.includes.push( codeNode );
  28970. }
  28971. return codeNode;
  28972. }
  28973. _getWGSLVertexCode( shaderData ) {
  28974. return `${ this.getSignature() }
  28975. // directives
  28976. ${shaderData.directives}
  28977. // uniforms
  28978. ${shaderData.uniforms}
  28979. // varyings
  28980. ${shaderData.varyings}
  28981. var<private> varyings : VaryingsStruct;
  28982. // codes
  28983. ${shaderData.codes}
  28984. @vertex
  28985. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  28986. // vars
  28987. ${shaderData.vars}
  28988. // flow
  28989. ${shaderData.flow}
  28990. return varyings;
  28991. }
  28992. `;
  28993. }
  28994. _getWGSLFragmentCode( shaderData ) {
  28995. return `${ this.getSignature() }
  28996. // global
  28997. ${ diagnostics }
  28998. // uniforms
  28999. ${shaderData.uniforms}
  29000. // structs
  29001. ${shaderData.structs}
  29002. // codes
  29003. ${shaderData.codes}
  29004. @fragment
  29005. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  29006. // vars
  29007. ${shaderData.vars}
  29008. // flow
  29009. ${shaderData.flow}
  29010. }
  29011. `;
  29012. }
  29013. _getWGSLComputeCode( shaderData, workgroupSize ) {
  29014. return `${ this.getSignature() }
  29015. // directives
  29016. ${shaderData.directives}
  29017. // system
  29018. var<private> instanceIndex : u32;
  29019. // locals
  29020. ${shaderData.scopedArrays}
  29021. // uniforms
  29022. ${shaderData.uniforms}
  29023. // codes
  29024. ${shaderData.codes}
  29025. @compute @workgroup_size( ${workgroupSize} )
  29026. fn main( ${shaderData.attributes} ) {
  29027. // system
  29028. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  29029. // vars
  29030. ${shaderData.vars}
  29031. // flow
  29032. ${shaderData.flow}
  29033. }
  29034. `;
  29035. }
  29036. _getWGSLStruct( name, vars ) {
  29037. return `
  29038. struct ${name} {
  29039. ${vars}
  29040. };`;
  29041. }
  29042. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  29043. const structName = name + 'Struct';
  29044. const structSnippet = this._getWGSLStruct( structName, vars );
  29045. return `${structSnippet}
  29046. @binding( ${binding} ) @group( ${group} )
  29047. var<${access}> ${name} : ${structName};`;
  29048. }
  29049. }
  29050. class WebGPUUtils {
  29051. constructor( backend ) {
  29052. this.backend = backend;
  29053. }
  29054. getCurrentDepthStencilFormat( renderContext ) {
  29055. let format;
  29056. if ( renderContext.depthTexture !== null ) {
  29057. format = this.getTextureFormatGPU( renderContext.depthTexture );
  29058. } else if ( renderContext.depth && renderContext.stencil ) {
  29059. format = GPUTextureFormat.Depth24PlusStencil8;
  29060. } else if ( renderContext.depth ) {
  29061. format = GPUTextureFormat.Depth24Plus;
  29062. }
  29063. return format;
  29064. }
  29065. getTextureFormatGPU( texture ) {
  29066. return this.backend.get( texture ).format;
  29067. }
  29068. getTextureSampleData( texture ) {
  29069. let samples;
  29070. if ( texture.isFramebufferTexture ) {
  29071. samples = 1;
  29072. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  29073. const renderer = this.backend.renderer;
  29074. const renderTarget = renderer.getRenderTarget();
  29075. samples = renderTarget ? renderTarget.samples : renderer.samples;
  29076. } else if ( texture.renderTarget ) {
  29077. samples = texture.renderTarget.samples;
  29078. }
  29079. samples = samples || 1;
  29080. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  29081. const primarySamples = isMSAA ? 1 : samples;
  29082. return { samples, primarySamples, isMSAA };
  29083. }
  29084. getCurrentColorFormat( renderContext ) {
  29085. let format;
  29086. if ( renderContext.textures !== null ) {
  29087. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  29088. } else {
  29089. format = this.getPreferredCanvasFormat(); // default context format
  29090. }
  29091. return format;
  29092. }
  29093. getCurrentColorSpace( renderContext ) {
  29094. if ( renderContext.textures !== null ) {
  29095. return renderContext.textures[ 0 ].colorSpace;
  29096. }
  29097. return this.backend.renderer.outputColorSpace;
  29098. }
  29099. getPrimitiveTopology( object, material ) {
  29100. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  29101. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  29102. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  29103. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  29104. }
  29105. getSampleCount( sampleCount ) {
  29106. let count = 1;
  29107. if ( sampleCount > 1 ) {
  29108. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  29109. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  29110. if ( count === 2 ) {
  29111. count = 4;
  29112. }
  29113. }
  29114. return count;
  29115. }
  29116. getSampleCountRenderContext( renderContext ) {
  29117. if ( renderContext.textures !== null ) {
  29118. return this.getSampleCount( renderContext.sampleCount );
  29119. }
  29120. return this.getSampleCount( this.backend.renderer.samples );
  29121. }
  29122. getPreferredCanvasFormat() {
  29123. // TODO: Remove this check when Quest 34.5 is out
  29124. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  29125. if ( navigator.userAgent.includes( 'Quest' ) ) {
  29126. return GPUTextureFormat.BGRA8Unorm;
  29127. } else {
  29128. return navigator.gpu.getPreferredCanvasFormat();
  29129. }
  29130. }
  29131. }
  29132. const typedArraysToVertexFormatPrefix = new Map( [
  29133. [ Int8Array, [ 'sint8', 'snorm8' ]],
  29134. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  29135. [ Int16Array, [ 'sint16', 'snorm16' ]],
  29136. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  29137. [ Int32Array, [ 'sint32', 'snorm32' ]],
  29138. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  29139. [ Float32Array, [ 'float32', ]],
  29140. ] );
  29141. const typedAttributeToVertexFormatPrefix = new Map( [
  29142. [ Float16BufferAttribute, [ 'float16', ]],
  29143. ] );
  29144. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  29145. [ Int32Array, 'sint32' ],
  29146. [ Int16Array, 'sint32' ], // patch for INT16
  29147. [ Uint32Array, 'uint32' ],
  29148. [ Uint16Array, 'uint32' ], // patch for UINT16
  29149. [ Float32Array, 'float32' ]
  29150. ] );
  29151. class WebGPUAttributeUtils {
  29152. constructor( backend ) {
  29153. this.backend = backend;
  29154. }
  29155. createAttribute( attribute, usage ) {
  29156. const bufferAttribute = this._getBufferAttribute( attribute );
  29157. const backend = this.backend;
  29158. const bufferData = backend.get( bufferAttribute );
  29159. let buffer = bufferData.buffer;
  29160. if ( buffer === undefined ) {
  29161. const device = backend.device;
  29162. let array = bufferAttribute.array;
  29163. // patch for INT16 and UINT16
  29164. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  29165. const tempArray = new Uint32Array( array.length );
  29166. for ( let i = 0; i < array.length; i ++ ) {
  29167. tempArray[ i ] = array[ i ];
  29168. }
  29169. array = tempArray;
  29170. }
  29171. bufferAttribute.array = array;
  29172. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  29173. array = new array.constructor( bufferAttribute.count * 4 );
  29174. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  29175. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  29176. }
  29177. // Update BufferAttribute
  29178. bufferAttribute.itemSize = 4;
  29179. bufferAttribute.array = array;
  29180. }
  29181. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  29182. buffer = device.createBuffer( {
  29183. label: bufferAttribute.name,
  29184. size: size,
  29185. usage: usage,
  29186. mappedAtCreation: true
  29187. } );
  29188. new array.constructor( buffer.getMappedRange() ).set( array );
  29189. buffer.unmap();
  29190. bufferData.buffer = buffer;
  29191. }
  29192. }
  29193. updateAttribute( attribute ) {
  29194. const bufferAttribute = this._getBufferAttribute( attribute );
  29195. const backend = this.backend;
  29196. const device = backend.device;
  29197. const buffer = backend.get( bufferAttribute ).buffer;
  29198. const array = bufferAttribute.array;
  29199. const isTypedArray = this._isTypedArray( array );
  29200. const updateRanges = bufferAttribute.updateRanges;
  29201. if ( updateRanges.length === 0 ) {
  29202. // Not using update ranges
  29203. device.queue.writeBuffer(
  29204. buffer,
  29205. 0,
  29206. array,
  29207. 0
  29208. );
  29209. } else {
  29210. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  29211. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  29212. const range = updateRanges[ i ];
  29213. const dataOffset = range.start * byteOffsetFactor;
  29214. const size = range.count * byteOffsetFactor;
  29215. device.queue.writeBuffer(
  29216. buffer,
  29217. 0,
  29218. array,
  29219. dataOffset,
  29220. size
  29221. );
  29222. }
  29223. bufferAttribute.clearUpdateRanges();
  29224. }
  29225. }
  29226. createShaderVertexBuffers( renderObject ) {
  29227. const attributes = renderObject.getAttributes();
  29228. const vertexBuffers = new Map();
  29229. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  29230. const geometryAttribute = attributes[ slot ];
  29231. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  29232. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  29233. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  29234. if ( vertexBufferLayout === undefined ) {
  29235. let arrayStride, stepMode;
  29236. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  29237. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  29238. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  29239. } else {
  29240. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  29241. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  29242. }
  29243. // patch for INT16 and UINT16
  29244. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  29245. arrayStride = 4;
  29246. }
  29247. vertexBufferLayout = {
  29248. arrayStride,
  29249. attributes: [],
  29250. stepMode
  29251. };
  29252. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  29253. }
  29254. const format = this._getVertexFormat( geometryAttribute );
  29255. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  29256. vertexBufferLayout.attributes.push( {
  29257. shaderLocation: slot,
  29258. offset,
  29259. format
  29260. } );
  29261. }
  29262. return Array.from( vertexBuffers.values() );
  29263. }
  29264. destroyAttribute( attribute ) {
  29265. const backend = this.backend;
  29266. const data = backend.get( this._getBufferAttribute( attribute ) );
  29267. data.buffer.destroy();
  29268. backend.delete( attribute );
  29269. }
  29270. async getArrayBufferAsync( attribute ) {
  29271. const backend = this.backend;
  29272. const device = backend.device;
  29273. const data = backend.get( this._getBufferAttribute( attribute ) );
  29274. const bufferGPU = data.buffer;
  29275. const size = bufferGPU.size;
  29276. const readBufferGPU = device.createBuffer( {
  29277. label: attribute.name,
  29278. size,
  29279. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  29280. } );
  29281. const cmdEncoder = device.createCommandEncoder( {} );
  29282. cmdEncoder.copyBufferToBuffer(
  29283. bufferGPU,
  29284. 0,
  29285. readBufferGPU,
  29286. 0,
  29287. size
  29288. );
  29289. readBufferGPU.unmap();
  29290. const gpuCommands = cmdEncoder.finish();
  29291. device.queue.submit( [ gpuCommands ] );
  29292. await readBufferGPU.mapAsync( GPUMapMode.READ );
  29293. const arrayBuffer = readBufferGPU.getMappedRange();
  29294. return arrayBuffer;
  29295. }
  29296. _getVertexFormat( geometryAttribute ) {
  29297. const { itemSize, normalized } = geometryAttribute;
  29298. const ArrayType = geometryAttribute.array.constructor;
  29299. const AttributeType = geometryAttribute.constructor;
  29300. let format;
  29301. if ( itemSize === 1 ) {
  29302. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  29303. } else {
  29304. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  29305. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  29306. if ( prefix ) {
  29307. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  29308. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  29309. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  29310. if ( paddedItemSize % 1 ) {
  29311. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  29312. }
  29313. format = `${prefix}x${paddedItemSize}`;
  29314. }
  29315. }
  29316. if ( ! format ) {
  29317. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  29318. }
  29319. return format;
  29320. }
  29321. _isTypedArray( array ) {
  29322. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  29323. }
  29324. _getBufferAttribute( attribute ) {
  29325. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29326. return attribute;
  29327. }
  29328. }
  29329. class WebGPUBindingUtils {
  29330. constructor( backend ) {
  29331. this.backend = backend;
  29332. this.bindGroupLayoutCache = new WeakMap();
  29333. }
  29334. createBindingsLayout( bindGroup ) {
  29335. const backend = this.backend;
  29336. const device = backend.device;
  29337. const entries = [];
  29338. let index = 0;
  29339. for ( const binding of bindGroup.bindings ) {
  29340. const bindingGPU = {
  29341. binding: index ++,
  29342. visibility: binding.visibility
  29343. };
  29344. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  29345. const buffer = {}; // GPUBufferBindingLayout
  29346. if ( binding.isStorageBuffer ) {
  29347. if ( binding.visibility & 4 ) {
  29348. // compute
  29349. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  29350. buffer.type = GPUBufferBindingType.Storage;
  29351. } else {
  29352. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  29353. }
  29354. } else {
  29355. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  29356. }
  29357. }
  29358. bindingGPU.buffer = buffer;
  29359. } else if ( binding.isSampler ) {
  29360. const sampler = {}; // GPUSamplerBindingLayout
  29361. if ( binding.texture.isDepthTexture ) {
  29362. if ( binding.texture.compareFunction !== null ) {
  29363. sampler.type = 'comparison';
  29364. }
  29365. }
  29366. bindingGPU.sampler = sampler;
  29367. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  29368. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  29369. } else if ( binding.isSampledTexture && binding.store ) {
  29370. const storageTexture = {}; // GPUStorageTextureBindingLayout
  29371. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  29372. const access = binding.access;
  29373. if ( access === NodeAccess.READ_WRITE ) {
  29374. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  29375. } else if ( access === NodeAccess.WRITE_ONLY ) {
  29376. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  29377. } else {
  29378. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  29379. }
  29380. bindingGPU.storageTexture = storageTexture;
  29381. } else if ( binding.isSampledTexture ) {
  29382. const texture = {}; // GPUTextureBindingLayout
  29383. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  29384. if ( primarySamples > 1 ) {
  29385. texture.multisampled = true;
  29386. if ( ! binding.texture.isDepthTexture ) {
  29387. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  29388. }
  29389. }
  29390. if ( binding.texture.isDepthTexture ) {
  29391. texture.sampleType = GPUTextureSampleType.Depth;
  29392. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  29393. const type = binding.texture.type;
  29394. if ( type === IntType ) {
  29395. texture.sampleType = GPUTextureSampleType.SInt;
  29396. } else if ( type === UnsignedIntType ) {
  29397. texture.sampleType = GPUTextureSampleType.UInt;
  29398. } else if ( type === FloatType ) {
  29399. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  29400. texture.sampleType = GPUTextureSampleType.Float;
  29401. } else {
  29402. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  29403. }
  29404. }
  29405. }
  29406. if ( binding.isSampledCubeTexture ) {
  29407. texture.viewDimension = GPUTextureViewDimension.Cube;
  29408. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  29409. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  29410. } else if ( binding.isSampledTexture3D ) {
  29411. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  29412. }
  29413. bindingGPU.texture = texture;
  29414. } else {
  29415. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  29416. }
  29417. entries.push( bindingGPU );
  29418. }
  29419. return device.createBindGroupLayout( { entries } );
  29420. }
  29421. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  29422. const { backend, bindGroupLayoutCache } = this;
  29423. const bindingsData = backend.get( bindGroup );
  29424. // setup (static) binding layout and (dynamic) binding group
  29425. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  29426. if ( bindLayoutGPU === undefined ) {
  29427. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  29428. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  29429. }
  29430. let bindGroupGPU;
  29431. if ( cacheIndex > 0 ) {
  29432. if ( bindingsData.groups === undefined ) {
  29433. bindingsData.groups = [];
  29434. bindingsData.versions = [];
  29435. }
  29436. if ( bindingsData.versions[ cacheIndex ] === version ) {
  29437. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  29438. }
  29439. }
  29440. if ( bindGroupGPU === undefined ) {
  29441. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  29442. if ( cacheIndex > 0 ) {
  29443. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  29444. bindingsData.versions[ cacheIndex ] = version;
  29445. }
  29446. }
  29447. bindingsData.group = bindGroupGPU;
  29448. bindingsData.layout = bindLayoutGPU;
  29449. }
  29450. updateBinding( binding ) {
  29451. const backend = this.backend;
  29452. const device = backend.device;
  29453. const buffer = binding.buffer;
  29454. const bufferGPU = backend.get( binding ).buffer;
  29455. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  29456. }
  29457. createBindGroup( bindGroup, layoutGPU ) {
  29458. const backend = this.backend;
  29459. const device = backend.device;
  29460. let bindingPoint = 0;
  29461. const entriesGPU = [];
  29462. for ( const binding of bindGroup.bindings ) {
  29463. if ( binding.isUniformBuffer ) {
  29464. const bindingData = backend.get( binding );
  29465. if ( bindingData.buffer === undefined ) {
  29466. const byteLength = binding.byteLength;
  29467. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  29468. const bufferGPU = device.createBuffer( {
  29469. label: 'bindingBuffer_' + binding.name,
  29470. size: byteLength,
  29471. usage: usage
  29472. } );
  29473. bindingData.buffer = bufferGPU;
  29474. }
  29475. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  29476. } else if ( binding.isStorageBuffer ) {
  29477. const bindingData = backend.get( binding );
  29478. if ( bindingData.buffer === undefined ) {
  29479. const attribute = binding.attribute;
  29480. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  29481. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  29482. bindingData.buffer = backend.get( attribute ).buffer;
  29483. }
  29484. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  29485. } else if ( binding.isSampler ) {
  29486. const textureGPU = backend.get( binding.texture );
  29487. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  29488. } else if ( binding.isSampledTexture ) {
  29489. const textureData = backend.get( binding.texture );
  29490. let resourceGPU;
  29491. if ( textureData.externalTexture !== undefined ) {
  29492. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  29493. } else {
  29494. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  29495. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  29496. resourceGPU = textureData[ propertyName ];
  29497. if ( resourceGPU === undefined ) {
  29498. const aspectGPU = GPUTextureAspect.All;
  29499. let dimensionViewGPU;
  29500. if ( binding.isSampledCubeTexture ) {
  29501. dimensionViewGPU = GPUTextureViewDimension.Cube;
  29502. } else if ( binding.isSampledTexture3D ) {
  29503. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  29504. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  29505. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  29506. } else {
  29507. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  29508. }
  29509. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  29510. }
  29511. }
  29512. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  29513. }
  29514. bindingPoint ++;
  29515. }
  29516. return device.createBindGroup( {
  29517. label: 'bindGroup_' + bindGroup.name,
  29518. layout: layoutGPU,
  29519. entries: entriesGPU
  29520. } );
  29521. }
  29522. }
  29523. class WebGPUPipelineUtils {
  29524. constructor( backend ) {
  29525. this.backend = backend;
  29526. }
  29527. _getSampleCount( renderObjectContext ) {
  29528. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  29529. }
  29530. createRenderPipeline( renderObject, promises ) {
  29531. const { object, material, geometry, pipeline } = renderObject;
  29532. const { vertexProgram, fragmentProgram } = pipeline;
  29533. const backend = this.backend;
  29534. const device = backend.device;
  29535. const utils = backend.utils;
  29536. const pipelineData = backend.get( pipeline );
  29537. // bind group layouts
  29538. const bindGroupLayouts = [];
  29539. for ( const bindGroup of renderObject.getBindings() ) {
  29540. const bindingsData = backend.get( bindGroup );
  29541. bindGroupLayouts.push( bindingsData.layout );
  29542. }
  29543. // vertex buffers
  29544. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  29545. // blending
  29546. let blending;
  29547. if ( material.transparent === true && material.blending !== NoBlending ) {
  29548. blending = this._getBlending( material );
  29549. }
  29550. // stencil
  29551. let stencilFront = {};
  29552. if ( material.stencilWrite === true ) {
  29553. stencilFront = {
  29554. compare: this._getStencilCompare( material ),
  29555. failOp: this._getStencilOperation( material.stencilFail ),
  29556. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  29557. passOp: this._getStencilOperation( material.stencilZPass )
  29558. };
  29559. }
  29560. const colorWriteMask = this._getColorWriteMask( material );
  29561. const targets = [];
  29562. if ( renderObject.context.textures !== null ) {
  29563. const textures = renderObject.context.textures;
  29564. for ( let i = 0; i < textures.length; i ++ ) {
  29565. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  29566. targets.push( {
  29567. format: colorFormat,
  29568. blend: blending,
  29569. writeMask: colorWriteMask
  29570. } );
  29571. }
  29572. } else {
  29573. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  29574. targets.push( {
  29575. format: colorFormat,
  29576. blend: blending,
  29577. writeMask: colorWriteMask
  29578. } );
  29579. }
  29580. const vertexModule = backend.get( vertexProgram ).module;
  29581. const fragmentModule = backend.get( fragmentProgram ).module;
  29582. const primitiveState = this._getPrimitiveState( object, geometry, material );
  29583. const depthCompare = this._getDepthCompare( material );
  29584. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  29585. const sampleCount = this._getSampleCount( renderObject.context );
  29586. const pipelineDescriptor = {
  29587. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  29588. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  29589. fragment: Object.assign( {}, fragmentModule, { targets } ),
  29590. primitive: primitiveState,
  29591. multisample: {
  29592. count: sampleCount,
  29593. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  29594. },
  29595. layout: device.createPipelineLayout( {
  29596. bindGroupLayouts
  29597. } )
  29598. };
  29599. const depthStencil = {};
  29600. const renderDepth = renderObject.context.depth;
  29601. const renderStencil = renderObject.context.stencil;
  29602. if ( renderDepth === true || renderStencil === true ) {
  29603. if ( renderDepth === true ) {
  29604. depthStencil.format = depthStencilFormat;
  29605. depthStencil.depthWriteEnabled = material.depthWrite;
  29606. depthStencil.depthCompare = depthCompare;
  29607. }
  29608. if ( renderStencil === true ) {
  29609. depthStencil.stencilFront = stencilFront;
  29610. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  29611. depthStencil.stencilReadMask = material.stencilFuncMask;
  29612. depthStencil.stencilWriteMask = material.stencilWriteMask;
  29613. }
  29614. pipelineDescriptor.depthStencil = depthStencil;
  29615. }
  29616. if ( promises === null ) {
  29617. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  29618. } else {
  29619. const p = new Promise( ( resolve /*, reject*/ ) => {
  29620. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  29621. pipelineData.pipeline = pipeline;
  29622. resolve();
  29623. } );
  29624. } );
  29625. promises.push( p );
  29626. }
  29627. }
  29628. createBundleEncoder( renderContext ) {
  29629. const backend = this.backend;
  29630. const { utils, device } = backend;
  29631. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  29632. const colorFormat = utils.getCurrentColorFormat( renderContext );
  29633. const sampleCount = this._getSampleCount( renderContext );
  29634. const descriptor = {
  29635. label: 'renderBundleEncoder',
  29636. colorFormats: [ colorFormat ],
  29637. depthStencilFormat,
  29638. sampleCount
  29639. };
  29640. return device.createRenderBundleEncoder( descriptor );
  29641. }
  29642. createComputePipeline( pipeline, bindings ) {
  29643. const backend = this.backend;
  29644. const device = backend.device;
  29645. const computeProgram = backend.get( pipeline.computeProgram ).module;
  29646. const pipelineGPU = backend.get( pipeline );
  29647. // bind group layouts
  29648. const bindGroupLayouts = [];
  29649. for ( const bindingsGroup of bindings ) {
  29650. const bindingsData = backend.get( bindingsGroup );
  29651. bindGroupLayouts.push( bindingsData.layout );
  29652. }
  29653. pipelineGPU.pipeline = device.createComputePipeline( {
  29654. compute: computeProgram,
  29655. layout: device.createPipelineLayout( {
  29656. bindGroupLayouts
  29657. } )
  29658. } );
  29659. }
  29660. _getBlending( material ) {
  29661. let color, alpha;
  29662. const blending = material.blending;
  29663. const blendSrc = material.blendSrc;
  29664. const blendDst = material.blendDst;
  29665. const blendEquation = material.blendEquation;
  29666. if ( blending === CustomBlending ) {
  29667. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  29668. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  29669. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  29670. color = {
  29671. srcFactor: this._getBlendFactor( blendSrc ),
  29672. dstFactor: this._getBlendFactor( blendDst ),
  29673. operation: this._getBlendOperation( blendEquation )
  29674. };
  29675. alpha = {
  29676. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  29677. dstFactor: this._getBlendFactor( blendDstAlpha ),
  29678. operation: this._getBlendOperation( blendEquationAlpha )
  29679. };
  29680. } else {
  29681. const premultipliedAlpha = material.premultipliedAlpha;
  29682. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  29683. color = {
  29684. srcFactor: srcRGB,
  29685. dstFactor: dstRGB,
  29686. operation: GPUBlendOperation.Add
  29687. };
  29688. alpha = {
  29689. srcFactor: srcAlpha,
  29690. dstFactor: dstAlpha,
  29691. operation: GPUBlendOperation.Add
  29692. };
  29693. };
  29694. if ( premultipliedAlpha ) {
  29695. switch ( blending ) {
  29696. case NormalBlending:
  29697. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  29698. break;
  29699. case AdditiveBlending:
  29700. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  29701. break;
  29702. case SubtractiveBlending:
  29703. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  29704. break;
  29705. case MultiplyBlending:
  29706. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  29707. break;
  29708. }
  29709. } else {
  29710. switch ( blending ) {
  29711. case NormalBlending:
  29712. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  29713. break;
  29714. case AdditiveBlending:
  29715. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  29716. break;
  29717. case SubtractiveBlending:
  29718. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  29719. break;
  29720. case MultiplyBlending:
  29721. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  29722. break;
  29723. }
  29724. }
  29725. }
  29726. if ( color !== undefined && alpha !== undefined ) {
  29727. return { color, alpha };
  29728. } else {
  29729. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  29730. }
  29731. }
  29732. _getBlendFactor( blend ) {
  29733. let blendFactor;
  29734. switch ( blend ) {
  29735. case ZeroFactor:
  29736. blendFactor = GPUBlendFactor.Zero;
  29737. break;
  29738. case OneFactor:
  29739. blendFactor = GPUBlendFactor.One;
  29740. break;
  29741. case SrcColorFactor:
  29742. blendFactor = GPUBlendFactor.Src;
  29743. break;
  29744. case OneMinusSrcColorFactor:
  29745. blendFactor = GPUBlendFactor.OneMinusSrc;
  29746. break;
  29747. case SrcAlphaFactor:
  29748. blendFactor = GPUBlendFactor.SrcAlpha;
  29749. break;
  29750. case OneMinusSrcAlphaFactor:
  29751. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  29752. break;
  29753. case DstColorFactor:
  29754. blendFactor = GPUBlendFactor.Dst;
  29755. break;
  29756. case OneMinusDstColorFactor:
  29757. blendFactor = GPUBlendFactor.OneMinusDstColor;
  29758. break;
  29759. case DstAlphaFactor:
  29760. blendFactor = GPUBlendFactor.DstAlpha;
  29761. break;
  29762. case OneMinusDstAlphaFactor:
  29763. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  29764. break;
  29765. case SrcAlphaSaturateFactor:
  29766. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  29767. break;
  29768. case BlendColorFactor:
  29769. blendFactor = GPUBlendFactor.Constant;
  29770. break;
  29771. case OneMinusBlendColorFactor:
  29772. blendFactor = GPUBlendFactor.OneMinusConstant;
  29773. break;
  29774. default:
  29775. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  29776. }
  29777. return blendFactor;
  29778. }
  29779. _getStencilCompare( material ) {
  29780. let stencilCompare;
  29781. const stencilFunc = material.stencilFunc;
  29782. switch ( stencilFunc ) {
  29783. case NeverStencilFunc:
  29784. stencilCompare = GPUCompareFunction.Never;
  29785. break;
  29786. case AlwaysStencilFunc:
  29787. stencilCompare = GPUCompareFunction.Always;
  29788. break;
  29789. case LessStencilFunc:
  29790. stencilCompare = GPUCompareFunction.Less;
  29791. break;
  29792. case LessEqualStencilFunc:
  29793. stencilCompare = GPUCompareFunction.LessEqual;
  29794. break;
  29795. case EqualStencilFunc:
  29796. stencilCompare = GPUCompareFunction.Equal;
  29797. break;
  29798. case GreaterEqualStencilFunc:
  29799. stencilCompare = GPUCompareFunction.GreaterEqual;
  29800. break;
  29801. case GreaterStencilFunc:
  29802. stencilCompare = GPUCompareFunction.Greater;
  29803. break;
  29804. case NotEqualStencilFunc:
  29805. stencilCompare = GPUCompareFunction.NotEqual;
  29806. break;
  29807. default:
  29808. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  29809. }
  29810. return stencilCompare;
  29811. }
  29812. _getStencilOperation( op ) {
  29813. let stencilOperation;
  29814. switch ( op ) {
  29815. case KeepStencilOp:
  29816. stencilOperation = GPUStencilOperation.Keep;
  29817. break;
  29818. case ZeroStencilOp:
  29819. stencilOperation = GPUStencilOperation.Zero;
  29820. break;
  29821. case ReplaceStencilOp:
  29822. stencilOperation = GPUStencilOperation.Replace;
  29823. break;
  29824. case InvertStencilOp:
  29825. stencilOperation = GPUStencilOperation.Invert;
  29826. break;
  29827. case IncrementStencilOp:
  29828. stencilOperation = GPUStencilOperation.IncrementClamp;
  29829. break;
  29830. case DecrementStencilOp:
  29831. stencilOperation = GPUStencilOperation.DecrementClamp;
  29832. break;
  29833. case IncrementWrapStencilOp:
  29834. stencilOperation = GPUStencilOperation.IncrementWrap;
  29835. break;
  29836. case DecrementWrapStencilOp:
  29837. stencilOperation = GPUStencilOperation.DecrementWrap;
  29838. break;
  29839. default:
  29840. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  29841. }
  29842. return stencilOperation;
  29843. }
  29844. _getBlendOperation( blendEquation ) {
  29845. let blendOperation;
  29846. switch ( blendEquation ) {
  29847. case AddEquation:
  29848. blendOperation = GPUBlendOperation.Add;
  29849. break;
  29850. case SubtractEquation:
  29851. blendOperation = GPUBlendOperation.Subtract;
  29852. break;
  29853. case ReverseSubtractEquation:
  29854. blendOperation = GPUBlendOperation.ReverseSubtract;
  29855. break;
  29856. case MinEquation:
  29857. blendOperation = GPUBlendOperation.Min;
  29858. break;
  29859. case MaxEquation:
  29860. blendOperation = GPUBlendOperation.Max;
  29861. break;
  29862. default:
  29863. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  29864. }
  29865. return blendOperation;
  29866. }
  29867. _getPrimitiveState( object, geometry, material ) {
  29868. const descriptor = {};
  29869. const utils = this.backend.utils;
  29870. descriptor.topology = utils.getPrimitiveTopology( object, material );
  29871. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  29872. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  29873. }
  29874. switch ( material.side ) {
  29875. case FrontSide:
  29876. descriptor.frontFace = GPUFrontFace.CCW;
  29877. descriptor.cullMode = GPUCullMode.Back;
  29878. break;
  29879. case BackSide:
  29880. descriptor.frontFace = GPUFrontFace.CCW;
  29881. descriptor.cullMode = GPUCullMode.Front;
  29882. break;
  29883. case DoubleSide:
  29884. descriptor.frontFace = GPUFrontFace.CCW;
  29885. descriptor.cullMode = GPUCullMode.None;
  29886. break;
  29887. default:
  29888. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  29889. break;
  29890. }
  29891. return descriptor;
  29892. }
  29893. _getColorWriteMask( material ) {
  29894. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  29895. }
  29896. _getDepthCompare( material ) {
  29897. let depthCompare;
  29898. if ( material.depthTest === false ) {
  29899. depthCompare = GPUCompareFunction.Always;
  29900. } else {
  29901. const depthFunc = material.depthFunc;
  29902. switch ( depthFunc ) {
  29903. case NeverDepth:
  29904. depthCompare = GPUCompareFunction.Never;
  29905. break;
  29906. case AlwaysDepth:
  29907. depthCompare = GPUCompareFunction.Always;
  29908. break;
  29909. case LessDepth:
  29910. depthCompare = GPUCompareFunction.Less;
  29911. break;
  29912. case LessEqualDepth:
  29913. depthCompare = GPUCompareFunction.LessEqual;
  29914. break;
  29915. case EqualDepth:
  29916. depthCompare = GPUCompareFunction.Equal;
  29917. break;
  29918. case GreaterEqualDepth:
  29919. depthCompare = GPUCompareFunction.GreaterEqual;
  29920. break;
  29921. case GreaterDepth:
  29922. depthCompare = GPUCompareFunction.Greater;
  29923. break;
  29924. case NotEqualDepth:
  29925. depthCompare = GPUCompareFunction.NotEqual;
  29926. break;
  29927. default:
  29928. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  29929. }
  29930. }
  29931. return depthCompare;
  29932. }
  29933. }
  29934. /*// debugger tools
  29935. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  29936. //*/
  29937. //
  29938. class WebGPUBackend extends Backend {
  29939. constructor( parameters = {} ) {
  29940. super( parameters );
  29941. this.isWebGPUBackend = true;
  29942. // some parameters require default values other than "undefined"
  29943. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  29944. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  29945. this.trackTimestamp = ( parameters.trackTimestamp === true );
  29946. this.device = null;
  29947. this.context = null;
  29948. this.colorBuffer = null;
  29949. this.defaultRenderPassdescriptor = null;
  29950. this.utils = new WebGPUUtils( this );
  29951. this.attributeUtils = new WebGPUAttributeUtils( this );
  29952. this.bindingUtils = new WebGPUBindingUtils( this );
  29953. this.pipelineUtils = new WebGPUPipelineUtils( this );
  29954. this.textureUtils = new WebGPUTextureUtils( this );
  29955. this.occludedResolveCache = new Map();
  29956. }
  29957. async init( renderer ) {
  29958. await super.init( renderer );
  29959. //
  29960. const parameters = this.parameters;
  29961. // create the device if it is not passed with parameters
  29962. let device;
  29963. if ( parameters.device === undefined ) {
  29964. const adapterOptions = {
  29965. powerPreference: parameters.powerPreference
  29966. };
  29967. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  29968. if ( adapter === null ) {
  29969. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  29970. }
  29971. // feature support
  29972. const features = Object.values( GPUFeatureName );
  29973. const supportedFeatures = [];
  29974. for ( const name of features ) {
  29975. if ( adapter.features.has( name ) ) {
  29976. supportedFeatures.push( name );
  29977. }
  29978. }
  29979. const deviceDescriptor = {
  29980. requiredFeatures: supportedFeatures,
  29981. requiredLimits: parameters.requiredLimits
  29982. };
  29983. device = await adapter.requestDevice( deviceDescriptor );
  29984. } else {
  29985. device = parameters.device;
  29986. }
  29987. device.lost.then( ( info ) => {
  29988. const deviceLossInfo = {
  29989. api: 'WebGPU',
  29990. message: info.message || 'Unknown reason',
  29991. reason: info.reason || null,
  29992. originalEvent: info
  29993. };
  29994. renderer.onDeviceLost( deviceLossInfo );
  29995. } );
  29996. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  29997. this.device = device;
  29998. this.context = context;
  29999. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  30000. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  30001. this.context.configure( {
  30002. device: this.device,
  30003. format: this.utils.getPreferredCanvasFormat(),
  30004. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  30005. alphaMode: alphaMode
  30006. } );
  30007. this.updateSize();
  30008. }
  30009. get coordinateSystem() {
  30010. return WebGPUCoordinateSystem;
  30011. }
  30012. async getArrayBufferAsync( attribute ) {
  30013. return await this.attributeUtils.getArrayBufferAsync( attribute );
  30014. }
  30015. getContext() {
  30016. return this.context;
  30017. }
  30018. _getDefaultRenderPassDescriptor() {
  30019. let descriptor = this.defaultRenderPassdescriptor;
  30020. if ( descriptor === null ) {
  30021. const renderer = this.renderer;
  30022. descriptor = {
  30023. colorAttachments: [ {
  30024. view: null
  30025. } ],
  30026. };
  30027. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  30028. descriptor.depthStencilAttachment = {
  30029. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  30030. };
  30031. }
  30032. const colorAttachment = descriptor.colorAttachments[ 0 ];
  30033. if ( this.renderer.samples > 0 ) {
  30034. colorAttachment.view = this.colorBuffer.createView();
  30035. } else {
  30036. colorAttachment.resolveTarget = undefined;
  30037. }
  30038. this.defaultRenderPassdescriptor = descriptor;
  30039. }
  30040. const colorAttachment = descriptor.colorAttachments[ 0 ];
  30041. if ( this.renderer.samples > 0 ) {
  30042. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  30043. } else {
  30044. colorAttachment.view = this.context.getCurrentTexture().createView();
  30045. }
  30046. return descriptor;
  30047. }
  30048. _getRenderPassDescriptor( renderContext ) {
  30049. const renderTarget = renderContext.renderTarget;
  30050. const renderTargetData = this.get( renderTarget );
  30051. let descriptors = renderTargetData.descriptors;
  30052. if ( descriptors === undefined ||
  30053. renderTargetData.width !== renderTarget.width ||
  30054. renderTargetData.height !== renderTarget.height ||
  30055. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  30056. renderTargetData.samples !== renderTarget.samples
  30057. ) {
  30058. descriptors = {};
  30059. renderTargetData.descriptors = descriptors;
  30060. // dispose
  30061. const onDispose = () => {
  30062. renderTarget.removeEventListener( 'dispose', onDispose );
  30063. this.delete( renderTarget );
  30064. };
  30065. renderTarget.addEventListener( 'dispose', onDispose );
  30066. }
  30067. const cacheKey = renderContext.getCacheKey();
  30068. let descriptor = descriptors[ cacheKey ];
  30069. if ( descriptor === undefined ) {
  30070. const textures = renderContext.textures;
  30071. const colorAttachments = [];
  30072. for ( let i = 0; i < textures.length; i ++ ) {
  30073. const textureData = this.get( textures[ i ] );
  30074. const textureView = textureData.texture.createView( {
  30075. baseMipLevel: renderContext.activeMipmapLevel,
  30076. mipLevelCount: 1,
  30077. baseArrayLayer: renderContext.activeCubeFace,
  30078. dimension: GPUTextureViewDimension.TwoD
  30079. } );
  30080. let view, resolveTarget;
  30081. if ( textureData.msaaTexture !== undefined ) {
  30082. view = textureData.msaaTexture.createView();
  30083. resolveTarget = textureView;
  30084. } else {
  30085. view = textureView;
  30086. resolveTarget = undefined;
  30087. }
  30088. colorAttachments.push( {
  30089. view,
  30090. resolveTarget,
  30091. loadOp: GPULoadOp.Load,
  30092. storeOp: GPUStoreOp.Store
  30093. } );
  30094. }
  30095. descriptor = {
  30096. colorAttachments,
  30097. };
  30098. if ( renderContext.depth ) {
  30099. const depthTextureData = this.get( renderContext.depthTexture );
  30100. const depthStencilAttachment = {
  30101. view: depthTextureData.texture.createView()
  30102. };
  30103. descriptor.depthStencilAttachment = depthStencilAttachment;
  30104. }
  30105. descriptors[ cacheKey ] = descriptor;
  30106. renderTargetData.width = renderTarget.width;
  30107. renderTargetData.height = renderTarget.height;
  30108. renderTargetData.samples = renderTarget.samples;
  30109. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  30110. }
  30111. return descriptor;
  30112. }
  30113. beginRender( renderContext ) {
  30114. const renderContextData = this.get( renderContext );
  30115. const device = this.device;
  30116. const occlusionQueryCount = renderContext.occlusionQueryCount;
  30117. let occlusionQuerySet;
  30118. if ( occlusionQueryCount > 0 ) {
  30119. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  30120. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  30121. // Get a reference to the array of objects with queries. The renderContextData property
  30122. // can be changed by another render pass before the buffer.mapAsyc() completes.
  30123. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  30124. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  30125. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  30126. //
  30127. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  30128. renderContextData.occlusionQuerySet = occlusionQuerySet;
  30129. renderContextData.occlusionQueryIndex = 0;
  30130. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  30131. renderContextData.lastOcclusionObject = null;
  30132. }
  30133. let descriptor;
  30134. if ( renderContext.textures === null ) {
  30135. descriptor = this._getDefaultRenderPassDescriptor();
  30136. } else {
  30137. descriptor = this._getRenderPassDescriptor( renderContext );
  30138. }
  30139. this.initTimestampQuery( renderContext, descriptor );
  30140. descriptor.occlusionQuerySet = occlusionQuerySet;
  30141. const depthStencilAttachment = descriptor.depthStencilAttachment;
  30142. if ( renderContext.textures !== null ) {
  30143. const colorAttachments = descriptor.colorAttachments;
  30144. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  30145. const colorAttachment = colorAttachments[ i ];
  30146. if ( renderContext.clearColor ) {
  30147. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  30148. colorAttachment.loadOp = GPULoadOp.Clear;
  30149. colorAttachment.storeOp = GPUStoreOp.Store;
  30150. } else {
  30151. colorAttachment.loadOp = GPULoadOp.Load;
  30152. colorAttachment.storeOp = GPUStoreOp.Store;
  30153. }
  30154. }
  30155. } else {
  30156. const colorAttachment = descriptor.colorAttachments[ 0 ];
  30157. if ( renderContext.clearColor ) {
  30158. colorAttachment.clearValue = renderContext.clearColorValue;
  30159. colorAttachment.loadOp = GPULoadOp.Clear;
  30160. colorAttachment.storeOp = GPUStoreOp.Store;
  30161. } else {
  30162. colorAttachment.loadOp = GPULoadOp.Load;
  30163. colorAttachment.storeOp = GPUStoreOp.Store;
  30164. }
  30165. }
  30166. //
  30167. if ( renderContext.depth ) {
  30168. if ( renderContext.clearDepth ) {
  30169. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  30170. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  30171. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  30172. } else {
  30173. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  30174. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  30175. }
  30176. }
  30177. if ( renderContext.stencil ) {
  30178. if ( renderContext.clearStencil ) {
  30179. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  30180. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  30181. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  30182. } else {
  30183. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  30184. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  30185. }
  30186. }
  30187. //
  30188. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  30189. const currentPass = encoder.beginRenderPass( descriptor );
  30190. //
  30191. renderContextData.descriptor = descriptor;
  30192. renderContextData.encoder = encoder;
  30193. renderContextData.currentPass = currentPass;
  30194. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  30195. renderContextData.renderBundles = [];
  30196. //
  30197. if ( renderContext.viewport ) {
  30198. this.updateViewport( renderContext );
  30199. }
  30200. if ( renderContext.scissor ) {
  30201. const { x, y, width, height } = renderContext.scissorValue;
  30202. currentPass.setScissorRect( x, y, width, height );
  30203. }
  30204. }
  30205. finishRender( renderContext ) {
  30206. const renderContextData = this.get( renderContext );
  30207. const occlusionQueryCount = renderContext.occlusionQueryCount;
  30208. if ( renderContextData.renderBundles.length > 0 ) {
  30209. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  30210. }
  30211. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  30212. renderContextData.currentPass.endOcclusionQuery();
  30213. }
  30214. renderContextData.currentPass.end();
  30215. if ( occlusionQueryCount > 0 ) {
  30216. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  30217. //
  30218. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  30219. if ( queryResolveBuffer === undefined ) {
  30220. queryResolveBuffer = this.device.createBuffer(
  30221. {
  30222. size: bufferSize,
  30223. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  30224. }
  30225. );
  30226. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  30227. }
  30228. //
  30229. const readBuffer = this.device.createBuffer(
  30230. {
  30231. size: bufferSize,
  30232. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  30233. }
  30234. );
  30235. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  30236. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  30237. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  30238. renderContextData.occlusionQueryBuffer = readBuffer;
  30239. //
  30240. this.resolveOccludedAsync( renderContext );
  30241. }
  30242. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  30243. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  30244. //
  30245. if ( renderContext.textures !== null ) {
  30246. const textures = renderContext.textures;
  30247. for ( let i = 0; i < textures.length; i ++ ) {
  30248. const texture = textures[ i ];
  30249. if ( texture.generateMipmaps === true ) {
  30250. this.textureUtils.generateMipmaps( texture );
  30251. }
  30252. }
  30253. }
  30254. }
  30255. isOccluded( renderContext, object ) {
  30256. const renderContextData = this.get( renderContext );
  30257. return renderContextData.occluded && renderContextData.occluded.has( object );
  30258. }
  30259. async resolveOccludedAsync( renderContext ) {
  30260. const renderContextData = this.get( renderContext );
  30261. // handle occlusion query results
  30262. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  30263. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  30264. const occluded = new WeakSet();
  30265. renderContextData.currentOcclusionQueryObjects = null;
  30266. renderContextData.currentOcclusionQueryBuffer = null;
  30267. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  30268. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  30269. const results = new BigUint64Array( buffer );
  30270. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  30271. if ( results[ i ] !== BigInt( 0 ) ) {
  30272. occluded.add( currentOcclusionQueryObjects[ i ] );
  30273. }
  30274. }
  30275. currentOcclusionQueryBuffer.destroy();
  30276. renderContextData.occluded = occluded;
  30277. }
  30278. }
  30279. updateViewport( renderContext ) {
  30280. const { currentPass } = this.get( renderContext );
  30281. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  30282. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  30283. }
  30284. clear( color, depth, stencil, renderTargetData = null ) {
  30285. const device = this.device;
  30286. const renderer = this.renderer;
  30287. let colorAttachments = [];
  30288. let depthStencilAttachment;
  30289. let clearValue;
  30290. let supportsDepth;
  30291. let supportsStencil;
  30292. if ( color ) {
  30293. const clearColor = this.getClearColor();
  30294. if ( this.renderer.alpha === true ) {
  30295. // premultiply alpha
  30296. const a = clearColor.a;
  30297. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  30298. } else {
  30299. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  30300. }
  30301. }
  30302. if ( renderTargetData === null ) {
  30303. supportsDepth = renderer.depth;
  30304. supportsStencil = renderer.stencil;
  30305. const descriptor = this._getDefaultRenderPassDescriptor();
  30306. if ( color ) {
  30307. colorAttachments = descriptor.colorAttachments;
  30308. const colorAttachment = colorAttachments[ 0 ];
  30309. colorAttachment.clearValue = clearValue;
  30310. colorAttachment.loadOp = GPULoadOp.Clear;
  30311. colorAttachment.storeOp = GPUStoreOp.Store;
  30312. }
  30313. if ( supportsDepth || supportsStencil ) {
  30314. depthStencilAttachment = descriptor.depthStencilAttachment;
  30315. }
  30316. } else {
  30317. supportsDepth = renderTargetData.depth;
  30318. supportsStencil = renderTargetData.stencil;
  30319. if ( color ) {
  30320. for ( const texture of renderTargetData.textures ) {
  30321. const textureData = this.get( texture );
  30322. const textureView = textureData.texture.createView();
  30323. let view, resolveTarget;
  30324. if ( textureData.msaaTexture !== undefined ) {
  30325. view = textureData.msaaTexture.createView();
  30326. resolveTarget = textureView;
  30327. } else {
  30328. view = textureView;
  30329. resolveTarget = undefined;
  30330. }
  30331. colorAttachments.push( {
  30332. view,
  30333. resolveTarget,
  30334. clearValue,
  30335. loadOp: GPULoadOp.Clear,
  30336. storeOp: GPUStoreOp.Store
  30337. } );
  30338. }
  30339. }
  30340. if ( supportsDepth || supportsStencil ) {
  30341. const depthTextureData = this.get( renderTargetData.depthTexture );
  30342. depthStencilAttachment = {
  30343. view: depthTextureData.texture.createView()
  30344. };
  30345. }
  30346. }
  30347. //
  30348. if ( supportsDepth ) {
  30349. if ( depth ) {
  30350. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  30351. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  30352. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  30353. } else {
  30354. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  30355. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  30356. }
  30357. }
  30358. //
  30359. if ( supportsStencil ) {
  30360. if ( stencil ) {
  30361. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  30362. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  30363. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  30364. } else {
  30365. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  30366. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  30367. }
  30368. }
  30369. //
  30370. const encoder = device.createCommandEncoder( {} );
  30371. const currentPass = encoder.beginRenderPass( {
  30372. colorAttachments,
  30373. depthStencilAttachment
  30374. } );
  30375. currentPass.end();
  30376. device.queue.submit( [ encoder.finish() ] );
  30377. }
  30378. // compute
  30379. beginCompute( computeGroup ) {
  30380. const groupGPU = this.get( computeGroup );
  30381. const descriptor = {};
  30382. this.initTimestampQuery( computeGroup, descriptor );
  30383. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  30384. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  30385. }
  30386. compute( computeGroup, computeNode, bindings, pipeline ) {
  30387. const { passEncoderGPU } = this.get( computeGroup );
  30388. // pipeline
  30389. const pipelineGPU = this.get( pipeline ).pipeline;
  30390. passEncoderGPU.setPipeline( pipelineGPU );
  30391. // bind groups
  30392. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  30393. const bindGroup = bindings[ i ];
  30394. const bindingsData = this.get( bindGroup );
  30395. passEncoderGPU.setBindGroup( i, bindingsData.group );
  30396. }
  30397. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  30398. const computeNodeData = this.get( computeNode );
  30399. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  30400. const { dispatchSize } = computeNodeData;
  30401. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  30402. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  30403. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  30404. } else {
  30405. dispatchSize.x = computeNode.dispatchCount;
  30406. }
  30407. passEncoderGPU.dispatchWorkgroups(
  30408. dispatchSize.x,
  30409. dispatchSize.y,
  30410. dispatchSize.z
  30411. );
  30412. }
  30413. finishCompute( computeGroup ) {
  30414. const groupData = this.get( computeGroup );
  30415. groupData.passEncoderGPU.end();
  30416. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  30417. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  30418. }
  30419. async waitForGPU() {
  30420. await this.device.queue.onSubmittedWorkDone();
  30421. }
  30422. // render object
  30423. draw( renderObject, info ) {
  30424. const { object, context, pipeline } = renderObject;
  30425. const bindings = renderObject.getBindings();
  30426. const renderContextData = this.get( context );
  30427. const pipelineGPU = this.get( pipeline ).pipeline;
  30428. const currentSets = renderContextData.currentSets;
  30429. const passEncoderGPU = renderContextData.currentPass;
  30430. const drawParams = renderObject.getDrawParameters();
  30431. if ( drawParams === null ) return;
  30432. // pipeline
  30433. if ( currentSets.pipeline !== pipelineGPU ) {
  30434. passEncoderGPU.setPipeline( pipelineGPU );
  30435. currentSets.pipeline = pipelineGPU;
  30436. }
  30437. // bind groups
  30438. const currentBindingGroups = currentSets.bindingGroups;
  30439. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  30440. const bindGroup = bindings[ i ];
  30441. const bindingsData = this.get( bindGroup );
  30442. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  30443. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  30444. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  30445. }
  30446. }
  30447. // attributes
  30448. const index = renderObject.getIndex();
  30449. const hasIndex = ( index !== null );
  30450. // index
  30451. if ( hasIndex === true ) {
  30452. if ( currentSets.index !== index ) {
  30453. const buffer = this.get( index ).buffer;
  30454. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  30455. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  30456. currentSets.index = index;
  30457. }
  30458. }
  30459. // vertex buffers
  30460. const vertexBuffers = renderObject.getVertexBuffers();
  30461. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  30462. const vertexBuffer = vertexBuffers[ i ];
  30463. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  30464. const buffer = this.get( vertexBuffer ).buffer;
  30465. passEncoderGPU.setVertexBuffer( i, buffer );
  30466. currentSets.attributes[ i ] = vertexBuffer;
  30467. }
  30468. }
  30469. // occlusion queries - handle multiple consecutive draw calls for an object
  30470. if ( renderContextData.occlusionQuerySet !== undefined ) {
  30471. const lastObject = renderContextData.lastOcclusionObject;
  30472. if ( lastObject !== object ) {
  30473. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  30474. passEncoderGPU.endOcclusionQuery();
  30475. renderContextData.occlusionQueryIndex ++;
  30476. }
  30477. if ( object.occlusionTest === true ) {
  30478. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  30479. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  30480. }
  30481. renderContextData.lastOcclusionObject = object;
  30482. }
  30483. }
  30484. // draw
  30485. if ( object.isBatchedMesh === true ) {
  30486. const starts = object._multiDrawStarts;
  30487. const counts = object._multiDrawCounts;
  30488. const drawCount = object._multiDrawCount;
  30489. const drawInstances = object._multiDrawInstances;
  30490. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  30491. for ( let i = 0; i < drawCount; i ++ ) {
  30492. const count = drawInstances ? drawInstances[ i ] : 1;
  30493. const firstInstance = count > 1 ? 0 : i;
  30494. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  30495. }
  30496. } else if ( hasIndex === true ) {
  30497. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  30498. const indirect = renderObject.getIndirect();
  30499. if ( indirect !== null ) {
  30500. const buffer = this.get( indirect ).buffer;
  30501. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  30502. } else {
  30503. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  30504. }
  30505. info.update( object, indexCount, instanceCount );
  30506. } else {
  30507. const { vertexCount, instanceCount, firstVertex } = drawParams;
  30508. const indirect = renderObject.getIndirect();
  30509. if ( indirect !== null ) {
  30510. const buffer = this.get( indirect ).buffer;
  30511. passEncoderGPU.drawIndirect( buffer, 0 );
  30512. } else {
  30513. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  30514. }
  30515. info.update( object, vertexCount, instanceCount );
  30516. }
  30517. }
  30518. // cache key
  30519. needsRenderUpdate( renderObject ) {
  30520. const data = this.get( renderObject );
  30521. const { object, material } = renderObject;
  30522. const utils = this.utils;
  30523. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  30524. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  30525. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  30526. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  30527. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  30528. let needsUpdate = false;
  30529. if ( data.material !== material || data.materialVersion !== material.version ||
  30530. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  30531. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  30532. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  30533. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  30534. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  30535. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  30536. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  30537. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  30538. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  30539. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  30540. data.primitiveTopology !== primitiveTopology ||
  30541. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  30542. ) {
  30543. data.material = material; data.materialVersion = material.version;
  30544. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  30545. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  30546. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  30547. data.colorWrite = material.colorWrite;
  30548. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  30549. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  30550. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  30551. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  30552. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  30553. data.sampleCount = sampleCount;
  30554. data.colorSpace = colorSpace;
  30555. data.colorFormat = colorFormat;
  30556. data.depthStencilFormat = depthStencilFormat;
  30557. data.primitiveTopology = primitiveTopology;
  30558. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  30559. needsUpdate = true;
  30560. }
  30561. return needsUpdate;
  30562. }
  30563. getRenderCacheKey( renderObject ) {
  30564. const { object, material } = renderObject;
  30565. const utils = this.utils;
  30566. const renderContext = renderObject.context;
  30567. return [
  30568. material.transparent, material.blending, material.premultipliedAlpha,
  30569. material.blendSrc, material.blendDst, material.blendEquation,
  30570. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  30571. material.colorWrite,
  30572. material.depthWrite, material.depthTest, material.depthFunc,
  30573. material.stencilWrite, material.stencilFunc,
  30574. material.stencilFail, material.stencilZFail, material.stencilZPass,
  30575. material.stencilFuncMask, material.stencilWriteMask,
  30576. material.side,
  30577. utils.getSampleCountRenderContext( renderContext ),
  30578. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  30579. utils.getPrimitiveTopology( object, material ),
  30580. renderObject.getGeometryCacheKey(),
  30581. renderObject.clippingContextCacheKey
  30582. ].join();
  30583. }
  30584. // textures
  30585. createSampler( texture ) {
  30586. this.textureUtils.createSampler( texture );
  30587. }
  30588. destroySampler( texture ) {
  30589. this.textureUtils.destroySampler( texture );
  30590. }
  30591. createDefaultTexture( texture ) {
  30592. this.textureUtils.createDefaultTexture( texture );
  30593. }
  30594. createTexture( texture, options ) {
  30595. this.textureUtils.createTexture( texture, options );
  30596. }
  30597. updateTexture( texture, options ) {
  30598. this.textureUtils.updateTexture( texture, options );
  30599. }
  30600. generateMipmaps( texture ) {
  30601. this.textureUtils.generateMipmaps( texture );
  30602. }
  30603. destroyTexture( texture ) {
  30604. this.textureUtils.destroyTexture( texture );
  30605. }
  30606. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  30607. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  30608. }
  30609. initTimestampQuery( renderContext, descriptor ) {
  30610. if ( ! this.trackTimestamp ) return;
  30611. const renderContextData = this.get( renderContext );
  30612. if ( ! renderContextData.timeStampQuerySet ) {
  30613. const type = renderContext.isComputeNode ? 'compute' : 'render';
  30614. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  30615. const timestampWrites = {
  30616. querySet: timeStampQuerySet,
  30617. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  30618. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  30619. };
  30620. Object.assign( descriptor, { timestampWrites } );
  30621. renderContextData.timeStampQuerySet = timeStampQuerySet;
  30622. }
  30623. }
  30624. // timestamp utils
  30625. prepareTimestampBuffer( renderContext, encoder ) {
  30626. if ( ! this.trackTimestamp ) return;
  30627. const renderContextData = this.get( renderContext );
  30628. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  30629. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  30630. renderContextData.currentTimestampQueryBuffers = {
  30631. resolveBuffer: this.device.createBuffer( {
  30632. label: 'timestamp resolve buffer',
  30633. size: size,
  30634. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  30635. } ),
  30636. resultBuffer: this.device.createBuffer( {
  30637. label: 'timestamp result buffer',
  30638. size: size,
  30639. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  30640. } )
  30641. };
  30642. }
  30643. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  30644. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  30645. if ( resultBuffer.mapState === 'unmapped' ) {
  30646. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  30647. }
  30648. }
  30649. async resolveTimestampAsync( renderContext, type = 'render' ) {
  30650. if ( ! this.trackTimestamp ) return;
  30651. const renderContextData = this.get( renderContext );
  30652. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  30653. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  30654. if ( resultBuffer.mapState === 'unmapped' ) {
  30655. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  30656. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  30657. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  30658. this.renderer.info.updateTimestamp( type, duration );
  30659. resultBuffer.unmap();
  30660. } );
  30661. }
  30662. }
  30663. // node builder
  30664. createNodeBuilder( object, renderer ) {
  30665. return new WGSLNodeBuilder( object, renderer );
  30666. }
  30667. // program
  30668. createProgram( program ) {
  30669. const programGPU = this.get( program );
  30670. programGPU.module = {
  30671. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  30672. entryPoint: 'main'
  30673. };
  30674. }
  30675. destroyProgram( program ) {
  30676. this.delete( program );
  30677. }
  30678. // pipelines
  30679. createRenderPipeline( renderObject, promises ) {
  30680. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  30681. }
  30682. createComputePipeline( computePipeline, bindings ) {
  30683. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  30684. }
  30685. beginBundle( renderContext ) {
  30686. const renderContextData = this.get( renderContext );
  30687. renderContextData._currentPass = renderContextData.currentPass;
  30688. renderContextData._currentSets = renderContextData.currentSets;
  30689. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  30690. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  30691. }
  30692. finishBundle( renderContext, bundle ) {
  30693. const renderContextData = this.get( renderContext );
  30694. const bundleEncoder = renderContextData.currentPass;
  30695. const bundleGPU = bundleEncoder.finish();
  30696. this.get( bundle ).bundleGPU = bundleGPU;
  30697. // restore render pass state
  30698. renderContextData.currentSets = renderContextData._currentSets;
  30699. renderContextData.currentPass = renderContextData._currentPass;
  30700. }
  30701. addBundle( renderContext, bundle ) {
  30702. const renderContextData = this.get( renderContext );
  30703. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  30704. }
  30705. // bindings
  30706. createBindings( bindGroup, bindings, cacheIndex, version ) {
  30707. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  30708. }
  30709. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  30710. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  30711. }
  30712. updateBinding( binding ) {
  30713. this.bindingUtils.updateBinding( binding );
  30714. }
  30715. // attributes
  30716. createIndexAttribute( attribute ) {
  30717. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  30718. }
  30719. createAttribute( attribute ) {
  30720. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  30721. }
  30722. createStorageAttribute( attribute ) {
  30723. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  30724. }
  30725. createIndirectStorageAttribute( attribute ) {
  30726. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  30727. }
  30728. updateAttribute( attribute ) {
  30729. this.attributeUtils.updateAttribute( attribute );
  30730. }
  30731. destroyAttribute( attribute ) {
  30732. this.attributeUtils.destroyAttribute( attribute );
  30733. }
  30734. // canvas
  30735. updateSize() {
  30736. this.colorBuffer = this.textureUtils.getColorBuffer();
  30737. this.defaultRenderPassdescriptor = null;
  30738. }
  30739. // utils public
  30740. getMaxAnisotropy() {
  30741. return 16;
  30742. }
  30743. hasFeature( name ) {
  30744. return this.device.features.has( name );
  30745. }
  30746. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  30747. let dstX = 0;
  30748. let dstY = 0;
  30749. let dstLayer = 0;
  30750. let srcX = 0;
  30751. let srcY = 0;
  30752. let srcLayer = 0;
  30753. let srcWidth = srcTexture.image.width;
  30754. let srcHeight = srcTexture.image.height;
  30755. if ( srcRegion !== null ) {
  30756. srcX = srcRegion.x;
  30757. srcY = srcRegion.y;
  30758. srcLayer = srcRegion.z || 0;
  30759. srcWidth = srcRegion.width;
  30760. srcHeight = srcRegion.height;
  30761. }
  30762. if ( dstPosition !== null ) {
  30763. dstX = dstPosition.x;
  30764. dstY = dstPosition.y;
  30765. dstLayer = dstPosition.z || 0;
  30766. }
  30767. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  30768. const sourceGPU = this.get( srcTexture ).texture;
  30769. const destinationGPU = this.get( dstTexture ).texture;
  30770. encoder.copyTextureToTexture(
  30771. {
  30772. texture: sourceGPU,
  30773. mipLevel: level,
  30774. origin: { x: srcX, y: srcY, z: srcLayer }
  30775. },
  30776. {
  30777. texture: destinationGPU,
  30778. mipLevel: level,
  30779. origin: { x: dstX, y: dstY, z: dstLayer }
  30780. },
  30781. [
  30782. srcWidth,
  30783. srcHeight,
  30784. 1
  30785. ]
  30786. );
  30787. this.device.queue.submit( [ encoder.finish() ] );
  30788. }
  30789. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  30790. const renderContextData = this.get( renderContext );
  30791. let sourceGPU = null;
  30792. if ( renderContext.renderTarget ) {
  30793. if ( texture.isDepthTexture ) {
  30794. sourceGPU = this.get( renderContext.depthTexture ).texture;
  30795. } else {
  30796. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  30797. }
  30798. } else {
  30799. if ( texture.isDepthTexture ) {
  30800. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  30801. } else {
  30802. sourceGPU = this.context.getCurrentTexture();
  30803. }
  30804. }
  30805. const destinationGPU = this.get( texture ).texture;
  30806. if ( sourceGPU.format !== destinationGPU.format ) {
  30807. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  30808. return;
  30809. }
  30810. let encoder;
  30811. if ( renderContextData.currentPass ) {
  30812. renderContextData.currentPass.end();
  30813. encoder = renderContextData.encoder;
  30814. } else {
  30815. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  30816. }
  30817. encoder.copyTextureToTexture(
  30818. {
  30819. texture: sourceGPU,
  30820. origin: [ rectangle.x, rectangle.y, 0 ],
  30821. },
  30822. {
  30823. texture: destinationGPU
  30824. },
  30825. [
  30826. rectangle.z,
  30827. rectangle.w
  30828. ]
  30829. );
  30830. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  30831. if ( renderContextData.currentPass ) {
  30832. const { descriptor } = renderContextData;
  30833. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  30834. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  30835. }
  30836. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  30837. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  30838. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  30839. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  30840. if ( renderContext.viewport ) {
  30841. this.updateViewport( renderContext );
  30842. }
  30843. if ( renderContext.scissor ) {
  30844. const { x, y, width, height } = renderContext.scissorValue;
  30845. renderContextData.currentPass.setScissorRect( x, y, width, height );
  30846. }
  30847. } else {
  30848. this.device.queue.submit( [ encoder.finish() ] );
  30849. }
  30850. }
  30851. }
  30852. class IESSpotLight extends SpotLight {
  30853. constructor( color, intensity, distance, angle, penumbra, decay ) {
  30854. super( color, intensity, distance, angle, penumbra, decay );
  30855. this.iesMap = null;
  30856. }
  30857. copy( source, recursive ) {
  30858. super.copy( source, recursive );
  30859. this.iesMap = source.iesMap;
  30860. return this;
  30861. }
  30862. }
  30863. class BasicNodeLibrary extends NodeLibrary {
  30864. constructor() {
  30865. super();
  30866. this.addLight( PointLightNode, PointLight );
  30867. this.addLight( DirectionalLightNode, DirectionalLight );
  30868. this.addLight( RectAreaLightNode, RectAreaLight );
  30869. this.addLight( SpotLightNode, SpotLight );
  30870. this.addLight( AmbientLightNode, AmbientLight );
  30871. this.addLight( HemisphereLightNode, HemisphereLight );
  30872. this.addLight( LightProbeNode, LightProbe );
  30873. this.addLight( IESSpotLightNode, IESSpotLight );
  30874. this.addToneMapping( linearToneMapping, LinearToneMapping );
  30875. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  30876. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  30877. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  30878. this.addToneMapping( agxToneMapping, AgXToneMapping );
  30879. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  30880. }
  30881. }
  30882. class WebGPURenderer extends Renderer {
  30883. constructor( parameters = {} ) {
  30884. let BackendClass;
  30885. if ( parameters.forceWebGL ) {
  30886. BackendClass = WebGLBackend;
  30887. } else {
  30888. BackendClass = WebGPUBackend;
  30889. parameters.getFallback = () => {
  30890. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  30891. return new WebGLBackend( parameters );
  30892. };
  30893. }
  30894. const backend = new BackendClass( parameters );
  30895. super( backend, parameters );
  30896. this.library = new BasicNodeLibrary();
  30897. this.isWebGPURenderer = true;
  30898. }
  30899. }
  30900. class BundleGroup extends Group {
  30901. constructor() {
  30902. super();
  30903. this.isBundleGroup = true;
  30904. this.type = 'BundleGroup';
  30905. this.static = true;
  30906. this.version = 0;
  30907. }
  30908. set needsUpdate( value ) {
  30909. if ( value === true ) this.version ++;
  30910. }
  30911. }
  30912. const _material = /*@__PURE__*/ new NodeMaterial();
  30913. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  30914. class PostProcessing {
  30915. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  30916. this.renderer = renderer;
  30917. this.outputNode = outputNode;
  30918. this.outputColorTransform = true;
  30919. this.needsUpdate = true;
  30920. _material.name = 'PostProcessing';
  30921. }
  30922. render() {
  30923. this.update();
  30924. const renderer = this.renderer;
  30925. const toneMapping = renderer.toneMapping;
  30926. const outputColorSpace = renderer.outputColorSpace;
  30927. renderer.toneMapping = NoToneMapping;
  30928. renderer.outputColorSpace = LinearSRGBColorSpace;
  30929. //
  30930. _quadMesh.render( renderer );
  30931. //
  30932. renderer.toneMapping = toneMapping;
  30933. renderer.outputColorSpace = outputColorSpace;
  30934. }
  30935. update() {
  30936. if ( this.needsUpdate === true ) {
  30937. const renderer = this.renderer;
  30938. const toneMapping = renderer.toneMapping;
  30939. const outputColorSpace = renderer.outputColorSpace;
  30940. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  30941. _quadMesh.material.needsUpdate = true;
  30942. this.needsUpdate = false;
  30943. }
  30944. }
  30945. async renderAsync() {
  30946. this.update();
  30947. const renderer = this.renderer;
  30948. const toneMapping = renderer.toneMapping;
  30949. const outputColorSpace = renderer.outputColorSpace;
  30950. renderer.toneMapping = NoToneMapping;
  30951. renderer.outputColorSpace = LinearSRGBColorSpace;
  30952. //
  30953. await _quadMesh.renderAsync( renderer );
  30954. //
  30955. renderer.toneMapping = toneMapping;
  30956. renderer.outputColorSpace = outputColorSpace;
  30957. }
  30958. }
  30959. // renderer state
  30960. function saveRendererState( renderer, state = {} ) {
  30961. state.toneMapping = renderer.toneMapping;
  30962. state.toneMappingExposure = renderer.toneMappingExposure;
  30963. state.outputColorSpace = renderer.outputColorSpace;
  30964. state.renderTarget = renderer.getRenderTarget();
  30965. state.activeCubeFace = renderer.getActiveCubeFace();
  30966. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30967. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30968. state.pixelRatio = renderer.getPixelRatio();
  30969. state.mrt = renderer.getMRT();
  30970. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30971. state.clearAlpha = renderer.getClearAlpha();
  30972. state.autoClear = renderer.autoClear;
  30973. state.scissorTest = renderer.getScissorTest();
  30974. return state;
  30975. }
  30976. function resetRendererState( renderer, state ) {
  30977. state = saveRendererState( renderer, state );
  30978. renderer.setMRT( null );
  30979. renderer.setRenderObjectFunction( null );
  30980. renderer.setClearColor( 0x000000, 1 );
  30981. renderer.autoClear = true;
  30982. return state;
  30983. }
  30984. function restoreRendererState( renderer, state ) {
  30985. renderer.toneMapping = state.toneMapping;
  30986. renderer.toneMappingExposure = state.toneMappingExposure;
  30987. renderer.outputColorSpace = state.outputColorSpace;
  30988. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30989. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30990. renderer.setPixelRatio( state.pixelRatio );
  30991. renderer.setMRT( state.mrt );
  30992. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30993. renderer.autoClear = state.autoClear;
  30994. renderer.setScissorTest( state.scissorTest );
  30995. }
  30996. // renderer and scene state
  30997. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30998. state = saveRendererState( renderer, state );
  30999. state.background = scene.background;
  31000. state.backgroundNode = scene.backgroundNode;
  31001. state.overrideMaterial = scene.overrideMaterial;
  31002. return state;
  31003. }
  31004. function resetRendererAndSceneState( renderer, scene, state ) {
  31005. state = saveRendererAndSceneState( renderer, scene, state );
  31006. scene.background = null;
  31007. scene.backgroundNode = null;
  31008. scene.overrideMaterial = null;
  31009. return state;
  31010. }
  31011. function restoreRendererAndSceneState( renderer, scene, state ) {
  31012. restoreRendererState( renderer, state );
  31013. scene.background = state.background;
  31014. scene.backgroundNode = state.backgroundNode;
  31015. scene.overrideMaterial = state.overrideMaterial;
  31016. }
  31017. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  31018. __proto__: null,
  31019. resetRendererAndSceneState: resetRendererAndSceneState,
  31020. resetRendererState: resetRendererState,
  31021. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31022. restoreRendererState: restoreRendererState,
  31023. saveRendererAndSceneState: saveRendererAndSceneState,
  31024. saveRendererState: saveRendererState
  31025. });
  31026. class StorageTexture extends Texture {
  31027. constructor( width = 1, height = 1 ) {
  31028. super();
  31029. this.image = { width, height };
  31030. this.magFilter = LinearFilter;
  31031. this.minFilter = LinearFilter;
  31032. this.isStorageTexture = true;
  31033. }
  31034. }
  31035. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  31036. constructor( array, itemSize ) {
  31037. super( array, itemSize, Uint32Array );
  31038. this.isIndirectStorageBufferAttribute = true;
  31039. }
  31040. }
  31041. class NodeLoader extends Loader {
  31042. constructor( manager ) {
  31043. super( manager );
  31044. this.textures = {};
  31045. this.nodes = {};
  31046. }
  31047. load( url, onLoad, onProgress, onError ) {
  31048. const loader = new FileLoader( this.manager );
  31049. loader.setPath( this.path );
  31050. loader.setRequestHeader( this.requestHeader );
  31051. loader.setWithCredentials( this.withCredentials );
  31052. loader.load( url, ( text ) => {
  31053. try {
  31054. onLoad( this.parse( JSON.parse( text ) ) );
  31055. } catch ( e ) {
  31056. if ( onError ) {
  31057. onError( e );
  31058. } else {
  31059. console.error( e );
  31060. }
  31061. this.manager.itemError( url );
  31062. }
  31063. }, onProgress, onError );
  31064. }
  31065. parseNodes( json ) {
  31066. const nodes = {};
  31067. if ( json !== undefined ) {
  31068. for ( const nodeJSON of json ) {
  31069. const { uuid, type } = nodeJSON;
  31070. nodes[ uuid ] = this.createNodeFromType( type );
  31071. nodes[ uuid ].uuid = uuid;
  31072. }
  31073. const meta = { nodes, textures: this.textures };
  31074. for ( const nodeJSON of json ) {
  31075. nodeJSON.meta = meta;
  31076. const node = nodes[ nodeJSON.uuid ];
  31077. node.deserialize( nodeJSON );
  31078. delete nodeJSON.meta;
  31079. }
  31080. }
  31081. return nodes;
  31082. }
  31083. parse( json ) {
  31084. const node = this.createNodeFromType( json.type );
  31085. node.uuid = json.uuid;
  31086. const nodes = this.parseNodes( json.nodes );
  31087. const meta = { nodes, textures: this.textures };
  31088. json.meta = meta;
  31089. node.deserialize( json );
  31090. delete json.meta;
  31091. return node;
  31092. }
  31093. setTextures( value ) {
  31094. this.textures = value;
  31095. return this;
  31096. }
  31097. setNodes( value ) {
  31098. this.nodes = value;
  31099. return this;
  31100. }
  31101. createNodeFromType( type ) {
  31102. if ( this.nodes[ type ] === undefined ) {
  31103. console.error( 'THREE.NodeLoader: Node type not found:', type );
  31104. return float();
  31105. }
  31106. return nodeObject( new this.nodes[ type ]() );
  31107. }
  31108. }
  31109. class NodeMaterialLoader extends MaterialLoader {
  31110. constructor( manager ) {
  31111. super( manager );
  31112. this.nodes = {};
  31113. this.nodeMaterials = {};
  31114. }
  31115. parse( json ) {
  31116. const material = super.parse( json );
  31117. const nodes = this.nodes;
  31118. const inputNodes = json.inputNodes;
  31119. for ( const property in inputNodes ) {
  31120. const uuid = inputNodes[ property ];
  31121. material[ property ] = nodes[ uuid ];
  31122. }
  31123. return material;
  31124. }
  31125. setNodes( value ) {
  31126. this.nodes = value;
  31127. return this;
  31128. }
  31129. setNodeMaterials( value ) {
  31130. this.nodeMaterials = value;
  31131. return this;
  31132. }
  31133. createMaterialFromType( type ) {
  31134. const materialClass = this.nodeMaterials[ type ];
  31135. if ( materialClass !== undefined ) {
  31136. return new materialClass();
  31137. }
  31138. return super.createMaterialFromType( type );
  31139. }
  31140. }
  31141. class NodeObjectLoader extends ObjectLoader {
  31142. constructor( manager ) {
  31143. super( manager );
  31144. this.nodes = {};
  31145. this.nodeMaterials = {};
  31146. this._nodesJSON = null;
  31147. }
  31148. setNodes( value ) {
  31149. this.nodes = value;
  31150. return this;
  31151. }
  31152. setNodeMaterials( value ) {
  31153. this.nodeMaterials = value;
  31154. return this;
  31155. }
  31156. parse( json, onLoad ) {
  31157. this._nodesJSON = json.nodes;
  31158. const data = super.parse( json, onLoad );
  31159. this._nodesJSON = null; // dispose
  31160. return data;
  31161. }
  31162. parseNodes( json, textures ) {
  31163. if ( json !== undefined ) {
  31164. const loader = new NodeLoader();
  31165. loader.setNodes( this.nodes );
  31166. loader.setTextures( textures );
  31167. return loader.parseNodes( json );
  31168. }
  31169. return {};
  31170. }
  31171. parseMaterials( json, textures ) {
  31172. const materials = {};
  31173. if ( json !== undefined ) {
  31174. const nodes = this.parseNodes( this._nodesJSON, textures );
  31175. const loader = new NodeMaterialLoader();
  31176. loader.setTextures( textures );
  31177. loader.setNodes( nodes );
  31178. loader.setNodeMaterials( this.nodeMaterials );
  31179. for ( let i = 0, l = json.length; i < l; i ++ ) {
  31180. const data = json[ i ];
  31181. materials[ data.uuid ] = loader.parse( data );
  31182. }
  31183. }
  31184. return materials;
  31185. }
  31186. }
  31187. class ClippingGroup extends Group {
  31188. constructor() {
  31189. super();
  31190. this.isClippingGroup = true;
  31191. this.clippingPlanes = [];
  31192. this.enabled = true;
  31193. this.clipIntersection = false;
  31194. this.clipShadows = false;
  31195. }
  31196. }
  31197. 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, FogExp2Node, FogNode, FogRangeNode, 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, ModelViewProjectionNode, 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, PostProcessingUtils, 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, 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号