three.webgpu.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530
  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 StandardNodeLibrary extends NodeLibrary {
  30864. constructor() {
  30865. super();
  30866. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  30867. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  30868. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  30869. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  30870. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  30871. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  30872. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  30873. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  30874. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  30875. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  30876. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  30877. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  30878. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  30879. this.addLight( PointLightNode, PointLight );
  30880. this.addLight( DirectionalLightNode, DirectionalLight );
  30881. this.addLight( RectAreaLightNode, RectAreaLight );
  30882. this.addLight( SpotLightNode, SpotLight );
  30883. this.addLight( AmbientLightNode, AmbientLight );
  30884. this.addLight( HemisphereLightNode, HemisphereLight );
  30885. this.addLight( LightProbeNode, LightProbe );
  30886. this.addLight( IESSpotLightNode, IESSpotLight );
  30887. this.addToneMapping( linearToneMapping, LinearToneMapping );
  30888. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  30889. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  30890. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  30891. this.addToneMapping( agxToneMapping, AgXToneMapping );
  30892. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  30893. }
  30894. }
  30895. /*
  30896. const debugHandler = {
  30897. get: function ( target, name ) {
  30898. // Add |update
  30899. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  30900. return target[ name ];
  30901. }
  30902. };
  30903. */
  30904. class WebGPURenderer extends Renderer {
  30905. constructor( parameters = {} ) {
  30906. let BackendClass;
  30907. if ( parameters.forceWebGL ) {
  30908. BackendClass = WebGLBackend;
  30909. } else {
  30910. BackendClass = WebGPUBackend;
  30911. parameters.getFallback = () => {
  30912. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  30913. return new WebGLBackend( parameters );
  30914. };
  30915. }
  30916. const backend = new BackendClass( parameters );
  30917. //super( new Proxy( backend, debugHandler ) );
  30918. super( backend, parameters );
  30919. this.library = new StandardNodeLibrary();
  30920. this.isWebGPURenderer = true;
  30921. }
  30922. }
  30923. class BundleGroup extends Group {
  30924. constructor() {
  30925. super();
  30926. this.isBundleGroup = true;
  30927. this.type = 'BundleGroup';
  30928. this.static = true;
  30929. this.version = 0;
  30930. }
  30931. set needsUpdate( value ) {
  30932. if ( value === true ) this.version ++;
  30933. }
  30934. }
  30935. const _material = /*@__PURE__*/ new NodeMaterial();
  30936. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  30937. class PostProcessing {
  30938. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  30939. this.renderer = renderer;
  30940. this.outputNode = outputNode;
  30941. this.outputColorTransform = true;
  30942. this.needsUpdate = true;
  30943. _material.name = 'PostProcessing';
  30944. }
  30945. render() {
  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. _quadMesh.render( renderer );
  30954. //
  30955. renderer.toneMapping = toneMapping;
  30956. renderer.outputColorSpace = outputColorSpace;
  30957. }
  30958. update() {
  30959. if ( this.needsUpdate === true ) {
  30960. const renderer = this.renderer;
  30961. const toneMapping = renderer.toneMapping;
  30962. const outputColorSpace = renderer.outputColorSpace;
  30963. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  30964. _quadMesh.material.needsUpdate = true;
  30965. this.needsUpdate = false;
  30966. }
  30967. }
  30968. async renderAsync() {
  30969. this.update();
  30970. const renderer = this.renderer;
  30971. const toneMapping = renderer.toneMapping;
  30972. const outputColorSpace = renderer.outputColorSpace;
  30973. renderer.toneMapping = NoToneMapping;
  30974. renderer.outputColorSpace = LinearSRGBColorSpace;
  30975. //
  30976. await _quadMesh.renderAsync( renderer );
  30977. //
  30978. renderer.toneMapping = toneMapping;
  30979. renderer.outputColorSpace = outputColorSpace;
  30980. }
  30981. }
  30982. // renderer state
  30983. function saveRendererState( renderer, state = {} ) {
  30984. state.toneMapping = renderer.toneMapping;
  30985. state.toneMappingExposure = renderer.toneMappingExposure;
  30986. state.outputColorSpace = renderer.outputColorSpace;
  30987. state.renderTarget = renderer.getRenderTarget();
  30988. state.activeCubeFace = renderer.getActiveCubeFace();
  30989. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30990. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30991. state.pixelRatio = renderer.getPixelRatio();
  30992. state.mrt = renderer.getMRT();
  30993. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30994. state.clearAlpha = renderer.getClearAlpha();
  30995. state.autoClear = renderer.autoClear;
  30996. state.scissorTest = renderer.getScissorTest();
  30997. return state;
  30998. }
  30999. function resetRendererState( renderer, state ) {
  31000. state = saveRendererState( renderer, state );
  31001. renderer.setMRT( null );
  31002. renderer.setRenderObjectFunction( null );
  31003. renderer.setClearColor( 0x000000, 1 );
  31004. renderer.autoClear = true;
  31005. return state;
  31006. }
  31007. function restoreRendererState( renderer, state ) {
  31008. renderer.toneMapping = state.toneMapping;
  31009. renderer.toneMappingExposure = state.toneMappingExposure;
  31010. renderer.outputColorSpace = state.outputColorSpace;
  31011. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  31012. renderer.setRenderObjectFunction( state.renderObjectFunction );
  31013. renderer.setPixelRatio( state.pixelRatio );
  31014. renderer.setMRT( state.mrt );
  31015. renderer.setClearColor( state.clearColor, state.clearAlpha );
  31016. renderer.autoClear = state.autoClear;
  31017. renderer.setScissorTest( state.scissorTest );
  31018. }
  31019. // renderer and scene state
  31020. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  31021. state = saveRendererState( renderer, state );
  31022. state.background = scene.background;
  31023. state.backgroundNode = scene.backgroundNode;
  31024. state.overrideMaterial = scene.overrideMaterial;
  31025. return state;
  31026. }
  31027. function resetRendererAndSceneState( renderer, scene, state ) {
  31028. state = saveRendererAndSceneState( renderer, scene, state );
  31029. scene.background = null;
  31030. scene.backgroundNode = null;
  31031. scene.overrideMaterial = null;
  31032. return state;
  31033. }
  31034. function restoreRendererAndSceneState( renderer, scene, state ) {
  31035. restoreRendererState( renderer, state );
  31036. scene.background = state.background;
  31037. scene.backgroundNode = state.backgroundNode;
  31038. scene.overrideMaterial = state.overrideMaterial;
  31039. }
  31040. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  31041. __proto__: null,
  31042. resetRendererAndSceneState: resetRendererAndSceneState,
  31043. resetRendererState: resetRendererState,
  31044. restoreRendererAndSceneState: restoreRendererAndSceneState,
  31045. restoreRendererState: restoreRendererState,
  31046. saveRendererAndSceneState: saveRendererAndSceneState,
  31047. saveRendererState: saveRendererState
  31048. });
  31049. class StorageTexture extends Texture {
  31050. constructor( width = 1, height = 1 ) {
  31051. super();
  31052. this.image = { width, height };
  31053. this.magFilter = LinearFilter;
  31054. this.minFilter = LinearFilter;
  31055. this.isStorageTexture = true;
  31056. }
  31057. }
  31058. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  31059. constructor( array, itemSize ) {
  31060. super( array, itemSize, Uint32Array );
  31061. this.isIndirectStorageBufferAttribute = true;
  31062. }
  31063. }
  31064. class NodeLoader extends Loader {
  31065. constructor( manager ) {
  31066. super( manager );
  31067. this.textures = {};
  31068. this.nodes = {};
  31069. }
  31070. load( url, onLoad, onProgress, onError ) {
  31071. const loader = new FileLoader( this.manager );
  31072. loader.setPath( this.path );
  31073. loader.setRequestHeader( this.requestHeader );
  31074. loader.setWithCredentials( this.withCredentials );
  31075. loader.load( url, ( text ) => {
  31076. try {
  31077. onLoad( this.parse( JSON.parse( text ) ) );
  31078. } catch ( e ) {
  31079. if ( onError ) {
  31080. onError( e );
  31081. } else {
  31082. console.error( e );
  31083. }
  31084. this.manager.itemError( url );
  31085. }
  31086. }, onProgress, onError );
  31087. }
  31088. parseNodes( json ) {
  31089. const nodes = {};
  31090. if ( json !== undefined ) {
  31091. for ( const nodeJSON of json ) {
  31092. const { uuid, type } = nodeJSON;
  31093. nodes[ uuid ] = this.createNodeFromType( type );
  31094. nodes[ uuid ].uuid = uuid;
  31095. }
  31096. const meta = { nodes, textures: this.textures };
  31097. for ( const nodeJSON of json ) {
  31098. nodeJSON.meta = meta;
  31099. const node = nodes[ nodeJSON.uuid ];
  31100. node.deserialize( nodeJSON );
  31101. delete nodeJSON.meta;
  31102. }
  31103. }
  31104. return nodes;
  31105. }
  31106. parse( json ) {
  31107. const node = this.createNodeFromType( json.type );
  31108. node.uuid = json.uuid;
  31109. const nodes = this.parseNodes( json.nodes );
  31110. const meta = { nodes, textures: this.textures };
  31111. json.meta = meta;
  31112. node.deserialize( json );
  31113. delete json.meta;
  31114. return node;
  31115. }
  31116. setTextures( value ) {
  31117. this.textures = value;
  31118. return this;
  31119. }
  31120. setNodes( value ) {
  31121. this.nodes = value;
  31122. return this;
  31123. }
  31124. createNodeFromType( type ) {
  31125. if ( this.nodes[ type ] === undefined ) {
  31126. console.error( 'THREE.NodeLoader: Node type not found:', type );
  31127. return float();
  31128. }
  31129. return nodeObject( new this.nodes[ type ]() );
  31130. }
  31131. }
  31132. class NodeMaterialLoader extends MaterialLoader {
  31133. constructor( manager ) {
  31134. super( manager );
  31135. this.nodes = {};
  31136. this.nodeMaterials = {};
  31137. }
  31138. parse( json ) {
  31139. const material = super.parse( json );
  31140. const nodes = this.nodes;
  31141. const inputNodes = json.inputNodes;
  31142. for ( const property in inputNodes ) {
  31143. const uuid = inputNodes[ property ];
  31144. material[ property ] = nodes[ uuid ];
  31145. }
  31146. return material;
  31147. }
  31148. setNodes( value ) {
  31149. this.nodes = value;
  31150. return this;
  31151. }
  31152. setNodeMaterials( value ) {
  31153. this.nodeMaterials = value;
  31154. return this;
  31155. }
  31156. createMaterialFromType( type ) {
  31157. const materialClass = this.nodeMaterials[ type ];
  31158. if ( materialClass !== undefined ) {
  31159. return new materialClass();
  31160. }
  31161. return super.createMaterialFromType( type );
  31162. }
  31163. }
  31164. class NodeObjectLoader extends ObjectLoader {
  31165. constructor( manager ) {
  31166. super( manager );
  31167. this.nodes = {};
  31168. this.nodeMaterials = {};
  31169. this._nodesJSON = null;
  31170. }
  31171. setNodes( value ) {
  31172. this.nodes = value;
  31173. return this;
  31174. }
  31175. setNodeMaterials( value ) {
  31176. this.nodeMaterials = value;
  31177. return this;
  31178. }
  31179. parse( json, onLoad ) {
  31180. this._nodesJSON = json.nodes;
  31181. const data = super.parse( json, onLoad );
  31182. this._nodesJSON = null; // dispose
  31183. return data;
  31184. }
  31185. parseNodes( json, textures ) {
  31186. if ( json !== undefined ) {
  31187. const loader = new NodeLoader();
  31188. loader.setNodes( this.nodes );
  31189. loader.setTextures( textures );
  31190. return loader.parseNodes( json );
  31191. }
  31192. return {};
  31193. }
  31194. parseMaterials( json, textures ) {
  31195. const materials = {};
  31196. if ( json !== undefined ) {
  31197. const nodes = this.parseNodes( this._nodesJSON, textures );
  31198. const loader = new NodeMaterialLoader();
  31199. loader.setTextures( textures );
  31200. loader.setNodes( nodes );
  31201. loader.setNodeMaterials( this.nodeMaterials );
  31202. for ( let i = 0, l = json.length; i < l; i ++ ) {
  31203. const data = json[ i ];
  31204. materials[ data.uuid ] = loader.parse( data );
  31205. }
  31206. }
  31207. return materials;
  31208. }
  31209. }
  31210. class ClippingGroup extends Group {
  31211. constructor() {
  31212. super();
  31213. this.isClippingGroup = true;
  31214. this.clippingPlanes = [];
  31215. this.enabled = true;
  31216. this.clipIntersection = false;
  31217. this.clipShadows = false;
  31218. }
  31219. }
  31220. 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号