three.webgpu.js 944 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615
  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, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, NoBlending, 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, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, BufferAttribute, 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, WebGLMultipleRenderTargets, 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. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  259. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  260. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  261. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  262. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  263. function cyrb53( value, seed = 0 ) {
  264. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  265. if ( value instanceof Array ) {
  266. for ( let i = 0, val; i < value.length; i ++ ) {
  267. val = value[ i ];
  268. h1 = Math.imul( h1 ^ val, 2654435761 );
  269. h2 = Math.imul( h2 ^ val, 1597334677 );
  270. }
  271. } else {
  272. for ( let i = 0, ch; i < value.length; i ++ ) {
  273. ch = value.charCodeAt( i );
  274. h1 = Math.imul( h1 ^ ch, 2654435761 );
  275. h2 = Math.imul( h2 ^ ch, 1597334677 );
  276. }
  277. }
  278. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  279. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  280. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  281. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  282. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  283. }
  284. const hashString = ( str ) => cyrb53( str );
  285. const hashArray = ( array ) => cyrb53( array );
  286. const hash$1 = ( ...params ) => cyrb53( params );
  287. function getCacheKey$1( object, force = false ) {
  288. const values = [];
  289. if ( object.isNode === true ) {
  290. values.push( object.id );
  291. object = object.getSelf();
  292. }
  293. for ( const { property, childNode } of getNodeChildren( object ) ) {
  294. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  295. }
  296. return cyrb53( values );
  297. }
  298. function* getNodeChildren( node, toJSON = false ) {
  299. for ( const property in node ) {
  300. // Ignore private properties.
  301. if ( property.startsWith( '_' ) === true ) continue;
  302. const object = node[ property ];
  303. if ( Array.isArray( object ) === true ) {
  304. for ( let i = 0; i < object.length; i ++ ) {
  305. const child = object[ i ];
  306. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  307. yield { property, index: i, childNode: child };
  308. }
  309. }
  310. } else if ( object && object.isNode === true ) {
  311. yield { property, childNode: object };
  312. } else if ( typeof object === 'object' ) {
  313. for ( const subProperty in object ) {
  314. const child = object[ subProperty ];
  315. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  316. yield { property, index: subProperty, childNode: child };
  317. }
  318. }
  319. }
  320. }
  321. }
  322. function getValueType( value ) {
  323. if ( value === undefined || value === null ) return null;
  324. const typeOf = typeof value;
  325. if ( value.isNode === true ) {
  326. return 'node';
  327. } else if ( typeOf === 'number' ) {
  328. return 'float';
  329. } else if ( typeOf === 'boolean' ) {
  330. return 'bool';
  331. } else if ( typeOf === 'string' ) {
  332. return 'string';
  333. } else if ( typeOf === 'function' ) {
  334. return 'shader';
  335. } else if ( value.isVector2 === true ) {
  336. return 'vec2';
  337. } else if ( value.isVector3 === true ) {
  338. return 'vec3';
  339. } else if ( value.isVector4 === true ) {
  340. return 'vec4';
  341. } else if ( value.isMatrix3 === true ) {
  342. return 'mat3';
  343. } else if ( value.isMatrix4 === true ) {
  344. return 'mat4';
  345. } else if ( value.isColor === true ) {
  346. return 'color';
  347. } else if ( value instanceof ArrayBuffer ) {
  348. return 'ArrayBuffer';
  349. }
  350. return null;
  351. }
  352. function getValueFromType( type, ...params ) {
  353. const last4 = type ? type.slice( - 4 ) : undefined;
  354. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  355. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  356. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  357. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  358. }
  359. if ( type === 'color' ) {
  360. return new Color( ...params );
  361. } else if ( last4 === 'vec2' ) {
  362. return new Vector2( ...params );
  363. } else if ( last4 === 'vec3' ) {
  364. return new Vector3( ...params );
  365. } else if ( last4 === 'vec4' ) {
  366. return new Vector4( ...params );
  367. } else if ( last4 === 'mat3' ) {
  368. return new Matrix3( ...params );
  369. } else if ( last4 === 'mat4' ) {
  370. return new Matrix4( ...params );
  371. } else if ( type === 'bool' ) {
  372. return params[ 0 ] || false;
  373. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  374. return params[ 0 ] || 0;
  375. } else if ( type === 'string' ) {
  376. return params[ 0 ] || '';
  377. } else if ( type === 'ArrayBuffer' ) {
  378. return base64ToArrayBuffer( params[ 0 ] );
  379. }
  380. return null;
  381. }
  382. function arrayBufferToBase64( arrayBuffer ) {
  383. let chars = '';
  384. const array = new Uint8Array( arrayBuffer );
  385. for ( let i = 0; i < array.length; i ++ ) {
  386. chars += String.fromCharCode( array[ i ] );
  387. }
  388. return btoa( chars );
  389. }
  390. function base64ToArrayBuffer( base64 ) {
  391. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  392. }
  393. var NodeUtils = /*#__PURE__*/Object.freeze({
  394. __proto__: null,
  395. arrayBufferToBase64: arrayBufferToBase64,
  396. base64ToArrayBuffer: base64ToArrayBuffer,
  397. getCacheKey: getCacheKey$1,
  398. getNodeChildren: getNodeChildren,
  399. getValueFromType: getValueFromType,
  400. getValueType: getValueType,
  401. hash: hash$1,
  402. hashArray: hashArray,
  403. hashString: hashString
  404. });
  405. const NodeShaderStage = {
  406. VERTEX: 'vertex',
  407. FRAGMENT: 'fragment'
  408. };
  409. const NodeUpdateType = {
  410. NONE: 'none',
  411. FRAME: 'frame',
  412. RENDER: 'render',
  413. OBJECT: 'object'
  414. };
  415. const NodeType = {
  416. BOOLEAN: 'bool',
  417. INTEGER: 'int',
  418. FLOAT: 'float',
  419. VECTOR2: 'vec2',
  420. VECTOR3: 'vec3',
  421. VECTOR4: 'vec4',
  422. MATRIX2: 'mat2',
  423. MATRIX3: 'mat3',
  424. MATRIX4: 'mat4'
  425. };
  426. const defaultShaderStages = [ 'fragment', 'vertex' ];
  427. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  428. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  429. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  430. let _nodeId = 0;
  431. class Node extends EventDispatcher {
  432. static get type() {
  433. return 'Node';
  434. }
  435. constructor( nodeType = null ) {
  436. super();
  437. this.nodeType = nodeType;
  438. this.updateType = NodeUpdateType.NONE;
  439. this.updateBeforeType = NodeUpdateType.NONE;
  440. this.updateAfterType = NodeUpdateType.NONE;
  441. this.uuid = MathUtils.generateUUID();
  442. this.version = 0;
  443. this._cacheKey = null;
  444. this._cacheKeyVersion = 0;
  445. this.global = false;
  446. this.isNode = true;
  447. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  448. }
  449. set needsUpdate( value ) {
  450. if ( value === true ) {
  451. this.version ++;
  452. }
  453. }
  454. get type() {
  455. return this.constructor.type;
  456. }
  457. onUpdate( callback, updateType ) {
  458. this.updateType = updateType;
  459. this.update = callback.bind( this.getSelf() );
  460. return this;
  461. }
  462. onFrameUpdate( callback ) {
  463. return this.onUpdate( callback, NodeUpdateType.FRAME );
  464. }
  465. onRenderUpdate( callback ) {
  466. return this.onUpdate( callback, NodeUpdateType.RENDER );
  467. }
  468. onObjectUpdate( callback ) {
  469. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  470. }
  471. onReference( callback ) {
  472. this.updateReference = callback.bind( this.getSelf() );
  473. return this;
  474. }
  475. getSelf() {
  476. // Returns non-node object.
  477. return this.self || this;
  478. }
  479. updateReference( /*state*/ ) {
  480. return this;
  481. }
  482. isGlobal( /*builder*/ ) {
  483. return this.global;
  484. }
  485. * getChildren() {
  486. for ( const { childNode } of getNodeChildren( this ) ) {
  487. yield childNode;
  488. }
  489. }
  490. dispose() {
  491. this.dispatchEvent( { type: 'dispose' } );
  492. }
  493. traverse( callback ) {
  494. callback( this );
  495. for ( const childNode of this.getChildren() ) {
  496. childNode.traverse( callback );
  497. }
  498. }
  499. getCacheKey( force = false ) {
  500. force = force || this.version !== this._cacheKeyVersion;
  501. if ( force === true || this._cacheKey === null ) {
  502. this._cacheKey = getCacheKey$1( this, force );
  503. this._cacheKeyVersion = this.version;
  504. }
  505. return this._cacheKey;
  506. }
  507. getScope() {
  508. return this;
  509. }
  510. getHash( /*builder*/ ) {
  511. return this.uuid;
  512. }
  513. getUpdateType() {
  514. return this.updateType;
  515. }
  516. getUpdateBeforeType() {
  517. return this.updateBeforeType;
  518. }
  519. getUpdateAfterType() {
  520. return this.updateAfterType;
  521. }
  522. getElementType( builder ) {
  523. const type = this.getNodeType( builder );
  524. const elementType = builder.getElementType( type );
  525. return elementType;
  526. }
  527. getNodeType( builder ) {
  528. const nodeProperties = builder.getNodeProperties( this );
  529. if ( nodeProperties.outputNode ) {
  530. return nodeProperties.outputNode.getNodeType( builder );
  531. }
  532. return this.nodeType;
  533. }
  534. getShared( builder ) {
  535. const hash = this.getHash( builder );
  536. const nodeFromHash = builder.getNodeFromHash( hash );
  537. return nodeFromHash || this;
  538. }
  539. setup( builder ) {
  540. const nodeProperties = builder.getNodeProperties( this );
  541. let index = 0;
  542. for ( const childNode of this.getChildren() ) {
  543. nodeProperties[ 'node' + index ++ ] = childNode;
  544. }
  545. // return a outputNode if exists
  546. return null;
  547. }
  548. analyze( builder ) {
  549. const usageCount = builder.increaseUsage( this );
  550. if ( usageCount === 1 ) {
  551. // node flow children
  552. const nodeProperties = builder.getNodeProperties( this );
  553. for ( const childNode of Object.values( nodeProperties ) ) {
  554. if ( childNode && childNode.isNode === true ) {
  555. childNode.build( builder );
  556. }
  557. }
  558. }
  559. }
  560. generate( builder, output ) {
  561. const { outputNode } = builder.getNodeProperties( this );
  562. if ( outputNode && outputNode.isNode === true ) {
  563. return outputNode.build( builder, output );
  564. }
  565. }
  566. updateBefore( /*frame*/ ) {
  567. console.warn( 'Abstract function.' );
  568. }
  569. updateAfter( /*frame*/ ) {
  570. console.warn( 'Abstract function.' );
  571. }
  572. update( /*frame*/ ) {
  573. console.warn( 'Abstract function.' );
  574. }
  575. build( builder, output = null ) {
  576. const refNode = this.getShared( builder );
  577. if ( this !== refNode ) {
  578. return refNode.build( builder, output );
  579. }
  580. builder.addNode( this );
  581. builder.addChain( this );
  582. /* Build stages expected results:
  583. - "setup" -> Node
  584. - "analyze" -> null
  585. - "generate" -> String
  586. */
  587. let result = null;
  588. const buildStage = builder.getBuildStage();
  589. if ( buildStage === 'setup' ) {
  590. this.updateReference( builder );
  591. const properties = builder.getNodeProperties( this );
  592. if ( properties.initialized !== true ) {
  593. const stackNodesBeforeSetup = builder.stack.nodes.length;
  594. properties.initialized = true;
  595. properties.outputNode = this.setup( builder );
  596. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  597. for ( const childNode of Object.values( properties ) ) {
  598. if ( childNode && childNode.isNode === true ) {
  599. childNode.build( builder );
  600. }
  601. }
  602. }
  603. } else if ( buildStage === 'analyze' ) {
  604. this.analyze( builder );
  605. } else if ( buildStage === 'generate' ) {
  606. const isGenerateOnce = this.generate.length === 1;
  607. if ( isGenerateOnce ) {
  608. const type = this.getNodeType( builder );
  609. const nodeData = builder.getDataFromNode( this );
  610. result = nodeData.snippet;
  611. if ( result === undefined ) {
  612. result = this.generate( builder ) || '';
  613. nodeData.snippet = result;
  614. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  615. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  616. }
  617. result = builder.format( result, type, output );
  618. } else {
  619. result = this.generate( builder, output ) || '';
  620. }
  621. }
  622. builder.removeChain( this );
  623. builder.addSequentialNode( this );
  624. return result;
  625. }
  626. getSerializeChildren() {
  627. return getNodeChildren( this );
  628. }
  629. serialize( json ) {
  630. const nodeChildren = this.getSerializeChildren();
  631. const inputNodes = {};
  632. for ( const { property, index, childNode } of nodeChildren ) {
  633. if ( index !== undefined ) {
  634. if ( inputNodes[ property ] === undefined ) {
  635. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  636. }
  637. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  638. } else {
  639. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  640. }
  641. }
  642. if ( Object.keys( inputNodes ).length > 0 ) {
  643. json.inputNodes = inputNodes;
  644. }
  645. }
  646. deserialize( json ) {
  647. if ( json.inputNodes !== undefined ) {
  648. const nodes = json.meta.nodes;
  649. for ( const property in json.inputNodes ) {
  650. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  651. const inputArray = [];
  652. for ( const uuid of json.inputNodes[ property ] ) {
  653. inputArray.push( nodes[ uuid ] );
  654. }
  655. this[ property ] = inputArray;
  656. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  657. const inputObject = {};
  658. for ( const subProperty in json.inputNodes[ property ] ) {
  659. const uuid = json.inputNodes[ property ][ subProperty ];
  660. inputObject[ subProperty ] = nodes[ uuid ];
  661. }
  662. this[ property ] = inputObject;
  663. } else {
  664. const uuid = json.inputNodes[ property ];
  665. this[ property ] = nodes[ uuid ];
  666. }
  667. }
  668. }
  669. }
  670. toJSON( meta ) {
  671. const { uuid, type } = this;
  672. const isRoot = ( meta === undefined || typeof meta === 'string' );
  673. if ( isRoot ) {
  674. meta = {
  675. textures: {},
  676. images: {},
  677. nodes: {}
  678. };
  679. }
  680. // serialize
  681. let data = meta.nodes[ uuid ];
  682. if ( data === undefined ) {
  683. data = {
  684. uuid,
  685. type,
  686. meta,
  687. metadata: {
  688. version: 4.6,
  689. type: 'Node',
  690. generator: 'Node.toJSON'
  691. }
  692. };
  693. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  694. this.serialize( data );
  695. delete data.meta;
  696. }
  697. // TODO: Copied from Object3D.toJSON
  698. function extractFromCache( cache ) {
  699. const values = [];
  700. for ( const key in cache ) {
  701. const data = cache[ key ];
  702. delete data.metadata;
  703. values.push( data );
  704. }
  705. return values;
  706. }
  707. if ( isRoot ) {
  708. const textures = extractFromCache( meta.textures );
  709. const images = extractFromCache( meta.images );
  710. const nodes = extractFromCache( meta.nodes );
  711. if ( textures.length > 0 ) data.textures = textures;
  712. if ( images.length > 0 ) data.images = images;
  713. if ( nodes.length > 0 ) data.nodes = nodes;
  714. }
  715. return data;
  716. }
  717. }
  718. class ArrayElementNode extends Node {
  719. static get type() {
  720. return 'ArrayElementNode';
  721. } // @TODO: If extending from TempNode it breaks webgpu_compute
  722. constructor( node, indexNode ) {
  723. super();
  724. this.node = node;
  725. this.indexNode = indexNode;
  726. this.isArrayElementNode = true;
  727. }
  728. getNodeType( builder ) {
  729. return this.node.getElementType( builder );
  730. }
  731. generate( builder ) {
  732. const nodeSnippet = this.node.build( builder );
  733. const indexSnippet = this.indexNode.build( builder, 'uint' );
  734. return `${nodeSnippet}[ ${indexSnippet} ]`;
  735. }
  736. }
  737. class ConvertNode extends Node {
  738. static get type() {
  739. return 'ConvertNode';
  740. }
  741. constructor( node, convertTo ) {
  742. super();
  743. this.node = node;
  744. this.convertTo = convertTo;
  745. }
  746. getNodeType( builder ) {
  747. const requestType = this.node.getNodeType( builder );
  748. let convertTo = null;
  749. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  750. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  751. convertTo = overloadingType;
  752. }
  753. }
  754. return convertTo;
  755. }
  756. serialize( data ) {
  757. super.serialize( data );
  758. data.convertTo = this.convertTo;
  759. }
  760. deserialize( data ) {
  761. super.deserialize( data );
  762. this.convertTo = data.convertTo;
  763. }
  764. generate( builder, output ) {
  765. const node = this.node;
  766. const type = this.getNodeType( builder );
  767. const snippet = node.build( builder, type );
  768. return builder.format( snippet, type, output );
  769. }
  770. }
  771. class TempNode extends Node {
  772. static get type() {
  773. return 'TempNode';
  774. }
  775. constructor( type ) {
  776. super( type );
  777. this.isTempNode = true;
  778. }
  779. hasDependencies( builder ) {
  780. return builder.getDataFromNode( this ).usageCount > 1;
  781. }
  782. build( builder, output ) {
  783. const buildStage = builder.getBuildStage();
  784. if ( buildStage === 'generate' ) {
  785. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  786. const nodeData = builder.getDataFromNode( this );
  787. if ( nodeData.propertyName !== undefined ) {
  788. return builder.format( nodeData.propertyName, type, output );
  789. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  790. const snippet = super.build( builder, type );
  791. const nodeVar = builder.getVarFromNode( this, null, type );
  792. const propertyName = builder.getPropertyName( nodeVar );
  793. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  794. nodeData.snippet = snippet;
  795. nodeData.propertyName = propertyName;
  796. return builder.format( nodeData.propertyName, type, output );
  797. }
  798. }
  799. return super.build( builder, output );
  800. }
  801. }
  802. class JoinNode extends TempNode {
  803. static get type() {
  804. return 'JoinNode';
  805. }
  806. constructor( nodes = [], nodeType = null ) {
  807. super( nodeType );
  808. this.nodes = nodes;
  809. }
  810. getNodeType( builder ) {
  811. if ( this.nodeType !== null ) {
  812. return builder.getVectorType( this.nodeType );
  813. }
  814. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  815. }
  816. generate( builder, output ) {
  817. const type = this.getNodeType( builder );
  818. const nodes = this.nodes;
  819. const primitiveType = builder.getComponentType( type );
  820. const snippetValues = [];
  821. for ( const input of nodes ) {
  822. let inputSnippet = input.build( builder );
  823. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  824. if ( inputPrimitiveType !== primitiveType ) {
  825. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  826. }
  827. snippetValues.push( inputSnippet );
  828. }
  829. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  830. return builder.format( snippet, type, output );
  831. }
  832. }
  833. const stringVectorComponents = vectorComponents.join( '' );
  834. class SplitNode extends Node {
  835. static get type() {
  836. return 'SplitNode';
  837. }
  838. constructor( node, components = 'x' ) {
  839. super();
  840. this.node = node;
  841. this.components = components;
  842. this.isSplitNode = true;
  843. }
  844. getVectorLength() {
  845. let vectorLength = this.components.length;
  846. for ( const c of this.components ) {
  847. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  848. }
  849. return vectorLength;
  850. }
  851. getComponentType( builder ) {
  852. return builder.getComponentType( this.node.getNodeType( builder ) );
  853. }
  854. getNodeType( builder ) {
  855. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  856. }
  857. generate( builder, output ) {
  858. const node = this.node;
  859. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  860. let snippet = null;
  861. if ( nodeTypeLength > 1 ) {
  862. let type = null;
  863. const componentsLength = this.getVectorLength();
  864. if ( componentsLength >= nodeTypeLength ) {
  865. // needed expand the input node
  866. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  867. }
  868. const nodeSnippet = node.build( builder, type );
  869. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  870. // unnecessary swizzle
  871. snippet = builder.format( nodeSnippet, type, output );
  872. } else {
  873. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  874. }
  875. } else {
  876. // ignore .components if .node returns float/integer
  877. snippet = node.build( builder, output );
  878. }
  879. return snippet;
  880. }
  881. serialize( data ) {
  882. super.serialize( data );
  883. data.components = this.components;
  884. }
  885. deserialize( data ) {
  886. super.deserialize( data );
  887. this.components = data.components;
  888. }
  889. }
  890. class SetNode extends TempNode {
  891. static get type() {
  892. return 'SetNode';
  893. }
  894. constructor( sourceNode, components, targetNode ) {
  895. super();
  896. this.sourceNode = sourceNode;
  897. this.components = components;
  898. this.targetNode = targetNode;
  899. }
  900. getNodeType( builder ) {
  901. return this.sourceNode.getNodeType( builder );
  902. }
  903. generate( builder ) {
  904. const { sourceNode, components, targetNode } = this;
  905. const sourceType = this.getNodeType( builder );
  906. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  907. const targetSnippet = targetNode.build( builder, targetType );
  908. const sourceSnippet = sourceNode.build( builder, sourceType );
  909. const length = builder.getTypeLength( sourceType );
  910. const snippetValues = [];
  911. for ( let i = 0; i < length; i ++ ) {
  912. const component = vectorComponents[ i ];
  913. if ( component === components[ 0 ] ) {
  914. snippetValues.push( targetSnippet );
  915. i += components.length - 1;
  916. } else {
  917. snippetValues.push( sourceSnippet + '.' + component );
  918. }
  919. }
  920. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  921. }
  922. }
  923. class FlipNode extends TempNode {
  924. static get type() {
  925. return 'FlipNode';
  926. }
  927. constructor( sourceNode, components ) {
  928. super();
  929. this.sourceNode = sourceNode;
  930. this.components = components;
  931. }
  932. getNodeType( builder ) {
  933. return this.sourceNode.getNodeType( builder );
  934. }
  935. generate( builder ) {
  936. const { components, sourceNode } = this;
  937. const sourceType = this.getNodeType( builder );
  938. const sourceSnippet = sourceNode.build( builder );
  939. const sourceCache = builder.getVarFromNode( this );
  940. const sourceProperty = builder.getPropertyName( sourceCache );
  941. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  942. const length = builder.getTypeLength( sourceType );
  943. const snippetValues = [];
  944. let componentIndex = 0;
  945. for ( let i = 0; i < length; i ++ ) {
  946. const component = vectorComponents[ i ];
  947. if ( component === components[ componentIndex ] ) {
  948. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  949. componentIndex ++;
  950. } else {
  951. snippetValues.push( sourceProperty + '.' + component );
  952. }
  953. }
  954. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  955. }
  956. }
  957. class InputNode extends Node {
  958. static get type() {
  959. return 'InputNode';
  960. }
  961. constructor( value, nodeType = null ) {
  962. super( nodeType );
  963. this.isInputNode = true;
  964. this.value = value;
  965. this.precision = null;
  966. }
  967. getNodeType( /*builder*/ ) {
  968. if ( this.nodeType === null ) {
  969. return getValueType( this.value );
  970. }
  971. return this.nodeType;
  972. }
  973. getInputType( builder ) {
  974. return this.getNodeType( builder );
  975. }
  976. setPrecision( precision ) {
  977. this.precision = precision;
  978. return this;
  979. }
  980. serialize( data ) {
  981. super.serialize( data );
  982. data.value = this.value;
  983. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  984. data.valueType = getValueType( this.value );
  985. data.nodeType = this.nodeType;
  986. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  987. data.precision = this.precision;
  988. }
  989. deserialize( data ) {
  990. super.deserialize( data );
  991. this.nodeType = data.nodeType;
  992. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  993. this.precision = data.precision || null;
  994. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  995. }
  996. generate( /*builder, output*/ ) {
  997. console.warn( 'Abstract function.' );
  998. }
  999. }
  1000. class ConstNode extends InputNode {
  1001. static get type() {
  1002. return 'ConstNode';
  1003. }
  1004. constructor( value, nodeType = null ) {
  1005. super( value, nodeType );
  1006. this.isConstNode = true;
  1007. }
  1008. generateConst( builder ) {
  1009. return builder.generateConst( this.getNodeType( builder ), this.value );
  1010. }
  1011. generate( builder, output ) {
  1012. const type = this.getNodeType( builder );
  1013. return builder.format( this.generateConst( builder ), type, output );
  1014. }
  1015. }
  1016. //
  1017. let currentStack = null;
  1018. const NodeElements = new Map();
  1019. function addMethodChaining( name, nodeElement ) {
  1020. if ( NodeElements.has( name ) ) {
  1021. console.warn( `Redefinition of method chaining ${ name }` );
  1022. return;
  1023. }
  1024. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1025. NodeElements.set( name, nodeElement );
  1026. }
  1027. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1028. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1029. const shaderNodeHandler = {
  1030. setup( NodeClosure, params ) {
  1031. const inputs = params.shift();
  1032. return NodeClosure( nodeObjects( inputs ), ...params );
  1033. },
  1034. get( node, prop, nodeObj ) {
  1035. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1036. if ( node.isStackNode !== true && prop === 'assign' ) {
  1037. return ( ...params ) => {
  1038. currentStack.assign( nodeObj, ...params );
  1039. return nodeObj;
  1040. };
  1041. } else if ( NodeElements.has( prop ) ) {
  1042. const nodeElement = NodeElements.get( prop );
  1043. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1044. } else if ( prop === 'self' ) {
  1045. return node;
  1046. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1047. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1048. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1049. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1050. // accessing properties ( swizzle )
  1051. prop = parseSwizzle( prop );
  1052. return nodeObject( new SplitNode( nodeObj, prop ) );
  1053. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1054. // set properties ( swizzle ) and sort to xyzw sequence
  1055. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1056. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1057. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1058. // set properties ( swizzle ) and sort to xyzw sequence
  1059. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1060. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1061. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1062. // accessing property
  1063. if ( prop === 'width' ) prop = 'x';
  1064. else if ( prop === 'height' ) prop = 'y';
  1065. else if ( prop === 'depth' ) prop = 'z';
  1066. return nodeObject( new SplitNode( node, prop ) );
  1067. } else if ( /^\d+$/.test( prop ) === true ) {
  1068. // accessing array
  1069. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1070. }
  1071. }
  1072. return Reflect.get( node, prop, nodeObj );
  1073. },
  1074. set( node, prop, value, nodeObj ) {
  1075. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1076. // setting properties
  1077. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1078. nodeObj[ prop ].assign( value );
  1079. return true;
  1080. }
  1081. }
  1082. return Reflect.set( node, prop, value, nodeObj );
  1083. }
  1084. };
  1085. const nodeObjectsCacheMap = new WeakMap();
  1086. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1087. const ShaderNodeObject = function ( obj, altType = null ) {
  1088. const type = getValueType( obj );
  1089. if ( type === 'node' ) {
  1090. let nodeObject = nodeObjectsCacheMap.get( obj );
  1091. if ( nodeObject === undefined ) {
  1092. nodeObject = new Proxy( obj, shaderNodeHandler );
  1093. nodeObjectsCacheMap.set( obj, nodeObject );
  1094. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1095. }
  1096. return nodeObject;
  1097. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1098. return nodeObject( getConstNode( obj, altType ) );
  1099. } else if ( type === 'shader' ) {
  1100. return Fn( obj );
  1101. }
  1102. return obj;
  1103. };
  1104. const ShaderNodeObjects = function ( objects, altType = null ) {
  1105. for ( const name in objects ) {
  1106. objects[ name ] = nodeObject( objects[ name ], altType );
  1107. }
  1108. return objects;
  1109. };
  1110. const ShaderNodeArray = function ( array, altType = null ) {
  1111. const len = array.length;
  1112. for ( let i = 0; i < len; i ++ ) {
  1113. array[ i ] = nodeObject( array[ i ], altType );
  1114. }
  1115. return array;
  1116. };
  1117. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1118. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1119. if ( scope === null ) {
  1120. return ( ...params ) => {
  1121. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1122. };
  1123. } else if ( factor !== null ) {
  1124. factor = nodeObject( factor );
  1125. return ( ...params ) => {
  1126. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1127. };
  1128. } else {
  1129. return ( ...params ) => {
  1130. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1131. };
  1132. }
  1133. };
  1134. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1135. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1136. };
  1137. class ShaderCallNodeInternal extends Node {
  1138. constructor( shaderNode, inputNodes ) {
  1139. super();
  1140. this.shaderNode = shaderNode;
  1141. this.inputNodes = inputNodes;
  1142. }
  1143. getNodeType( builder ) {
  1144. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1145. }
  1146. call( builder ) {
  1147. const { shaderNode, inputNodes } = this;
  1148. const properties = builder.getNodeProperties( shaderNode );
  1149. if ( properties.onceOutput ) return properties.onceOutput;
  1150. //
  1151. let result = null;
  1152. if ( shaderNode.layout ) {
  1153. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1154. if ( functionNodesCacheMap === undefined ) {
  1155. functionNodesCacheMap = new WeakMap();
  1156. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1157. }
  1158. let functionNode = functionNodesCacheMap.get( shaderNode );
  1159. if ( functionNode === undefined ) {
  1160. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1161. functionNodesCacheMap.set( shaderNode, functionNode );
  1162. }
  1163. if ( builder.currentFunctionNode !== null ) {
  1164. builder.currentFunctionNode.includes.push( functionNode );
  1165. }
  1166. result = nodeObject( functionNode.call( inputNodes ) );
  1167. } else {
  1168. const jsFunc = shaderNode.jsFunc;
  1169. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1170. result = nodeObject( outputNode );
  1171. }
  1172. if ( shaderNode.once ) {
  1173. properties.onceOutput = result;
  1174. }
  1175. return result;
  1176. }
  1177. getOutputNode( builder ) {
  1178. const properties = builder.getNodeProperties( this );
  1179. if ( properties.outputNode === null ) {
  1180. properties.outputNode = this.setupOutput( builder );
  1181. }
  1182. return properties.outputNode;
  1183. }
  1184. setup( builder ) {
  1185. return this.getOutputNode( builder );
  1186. }
  1187. setupOutput( builder ) {
  1188. builder.addStack();
  1189. builder.stack.outputNode = this.call( builder );
  1190. return builder.removeStack();
  1191. }
  1192. generate( builder, output ) {
  1193. const outputNode = this.getOutputNode( builder );
  1194. return outputNode.build( builder, output );
  1195. }
  1196. }
  1197. class ShaderNodeInternal extends Node {
  1198. constructor( jsFunc, nodeType ) {
  1199. super( nodeType );
  1200. this.jsFunc = jsFunc;
  1201. this.layout = null;
  1202. this.global = true;
  1203. this.once = false;
  1204. }
  1205. setLayout( layout ) {
  1206. this.layout = layout;
  1207. return this;
  1208. }
  1209. call( inputs = null ) {
  1210. nodeObjects( inputs );
  1211. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1212. }
  1213. setup() {
  1214. return this.call();
  1215. }
  1216. }
  1217. const bools = [ false, true ];
  1218. const uints = [ 0, 1, 2, 3 ];
  1219. const ints = [ - 1, - 2 ];
  1220. 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 ];
  1221. const boolsCacheMap = new Map();
  1222. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1223. const uintsCacheMap = new Map();
  1224. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1225. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1226. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1227. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1228. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1229. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1230. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1231. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1232. const getConstNode = ( value, type ) => {
  1233. if ( constNodesCacheMap.has( value ) ) {
  1234. return constNodesCacheMap.get( value );
  1235. } else if ( value.isNode === true ) {
  1236. return value;
  1237. } else {
  1238. return new ConstNode( value, type );
  1239. }
  1240. };
  1241. const safeGetNodeType = ( node ) => {
  1242. try {
  1243. return node.getNodeType();
  1244. } catch ( _ ) {
  1245. return undefined;
  1246. }
  1247. };
  1248. const ConvertType = function ( type, cacheMap = null ) {
  1249. return ( ...params ) => {
  1250. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1251. params = [ getValueFromType( type, ...params ) ];
  1252. }
  1253. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1254. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1255. }
  1256. if ( params.length === 1 ) {
  1257. const node = getConstNode( params[ 0 ], type );
  1258. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1259. return nodeObject( new ConvertNode( node, type ) );
  1260. }
  1261. const nodes = params.map( param => getConstNode( param ) );
  1262. return nodeObject( new JoinNode( nodes, type ) );
  1263. };
  1264. };
  1265. // exports
  1266. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1267. // utils
  1268. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1269. // shader node base
  1270. function ShaderNode( jsFunc, nodeType ) {
  1271. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1272. }
  1273. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1274. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1275. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1276. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1277. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1278. const Fn = ( jsFunc, nodeType ) => {
  1279. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1280. const fn = ( ...params ) => {
  1281. let inputs;
  1282. nodeObjects( params );
  1283. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1284. inputs = [ ...params ];
  1285. } else {
  1286. inputs = params[ 0 ];
  1287. }
  1288. return shaderNode.call( inputs );
  1289. };
  1290. fn.shaderNode = shaderNode;
  1291. fn.setLayout = ( layout ) => {
  1292. shaderNode.setLayout( layout );
  1293. return fn;
  1294. };
  1295. fn.once = () => {
  1296. shaderNode.once = true;
  1297. return fn;
  1298. };
  1299. return fn;
  1300. };
  1301. const tslFn = ( ...params ) => { // @deprecated, r168
  1302. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1303. return Fn( ...params );
  1304. };
  1305. //
  1306. addMethodChaining( 'toGlobal', ( node ) => {
  1307. node.global = true;
  1308. return node;
  1309. } );
  1310. //
  1311. const setCurrentStack = ( stack ) => {
  1312. currentStack = stack;
  1313. };
  1314. const getCurrentStack = () => currentStack;
  1315. const If = ( ...params ) => currentStack.If( ...params );
  1316. function append( node ) {
  1317. if ( currentStack ) currentStack.add( node );
  1318. return node;
  1319. }
  1320. addMethodChaining( 'append', append );
  1321. // types
  1322. const color = new ConvertType( 'color' );
  1323. const float = new ConvertType( 'float', cacheMaps.float );
  1324. const int = new ConvertType( 'int', cacheMaps.ints );
  1325. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1326. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1327. const vec2 = new ConvertType( 'vec2' );
  1328. const ivec2 = new ConvertType( 'ivec2' );
  1329. const uvec2 = new ConvertType( 'uvec2' );
  1330. const bvec2 = new ConvertType( 'bvec2' );
  1331. const vec3 = new ConvertType( 'vec3' );
  1332. const ivec3 = new ConvertType( 'ivec3' );
  1333. const uvec3 = new ConvertType( 'uvec3' );
  1334. const bvec3 = new ConvertType( 'bvec3' );
  1335. const vec4 = new ConvertType( 'vec4' );
  1336. const ivec4 = new ConvertType( 'ivec4' );
  1337. const uvec4 = new ConvertType( 'uvec4' );
  1338. const bvec4 = new ConvertType( 'bvec4' );
  1339. const mat2 = new ConvertType( 'mat2' );
  1340. const mat3 = new ConvertType( 'mat3' );
  1341. const mat4 = new ConvertType( 'mat4' );
  1342. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1343. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1344. addMethodChaining( 'toColor', color );
  1345. addMethodChaining( 'toFloat', float );
  1346. addMethodChaining( 'toInt', int );
  1347. addMethodChaining( 'toUint', uint );
  1348. addMethodChaining( 'toBool', bool );
  1349. addMethodChaining( 'toVec2', vec2 );
  1350. addMethodChaining( 'toIVec2', ivec2 );
  1351. addMethodChaining( 'toUVec2', uvec2 );
  1352. addMethodChaining( 'toBVec2', bvec2 );
  1353. addMethodChaining( 'toVec3', vec3 );
  1354. addMethodChaining( 'toIVec3', ivec3 );
  1355. addMethodChaining( 'toUVec3', uvec3 );
  1356. addMethodChaining( 'toBVec3', bvec3 );
  1357. addMethodChaining( 'toVec4', vec4 );
  1358. addMethodChaining( 'toIVec4', ivec4 );
  1359. addMethodChaining( 'toUVec4', uvec4 );
  1360. addMethodChaining( 'toBVec4', bvec4 );
  1361. addMethodChaining( 'toMat2', mat2 );
  1362. addMethodChaining( 'toMat3', mat3 );
  1363. addMethodChaining( 'toMat4', mat4 );
  1364. // basic nodes
  1365. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1366. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1367. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1368. addMethodChaining( 'element', element );
  1369. addMethodChaining( 'convert', convert );
  1370. class UniformGroupNode extends Node {
  1371. static get type() {
  1372. return 'UniformGroupNode';
  1373. }
  1374. constructor( name, shared = false, order = 1 ) {
  1375. super( 'string' );
  1376. this.name = name;
  1377. this.version = 0;
  1378. this.shared = shared;
  1379. this.order = order;
  1380. this.isUniformGroup = true;
  1381. }
  1382. set needsUpdate( value ) {
  1383. if ( value === true ) this.version ++;
  1384. }
  1385. serialize( data ) {
  1386. super.serialize( data );
  1387. data.name = this.name;
  1388. data.version = this.version;
  1389. data.shared = this.shared;
  1390. }
  1391. deserialize( data ) {
  1392. super.deserialize( data );
  1393. this.name = data.name;
  1394. this.version = data.version;
  1395. this.shared = data.shared;
  1396. }
  1397. }
  1398. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1399. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1400. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1401. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1402. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1403. class UniformNode extends InputNode {
  1404. static get type() {
  1405. return 'UniformNode';
  1406. }
  1407. constructor( value, nodeType = null ) {
  1408. super( value, nodeType );
  1409. this.isUniformNode = true;
  1410. this.name = '';
  1411. this.groupNode = objectGroup;
  1412. }
  1413. label( name ) {
  1414. this.name = name;
  1415. return this;
  1416. }
  1417. setGroup( group ) {
  1418. this.groupNode = group;
  1419. return this;
  1420. }
  1421. getGroup() {
  1422. return this.groupNode;
  1423. }
  1424. getUniformHash( builder ) {
  1425. return this.getHash( builder );
  1426. }
  1427. onUpdate( callback, updateType ) {
  1428. const self = this.getSelf();
  1429. callback = callback.bind( self );
  1430. return super.onUpdate( ( frame ) => {
  1431. const value = callback( frame, self );
  1432. if ( value !== undefined ) {
  1433. this.value = value;
  1434. }
  1435. }, updateType );
  1436. }
  1437. generate( builder, output ) {
  1438. const type = this.getNodeType( builder );
  1439. const hash = this.getUniformHash( builder );
  1440. let sharedNode = builder.getNodeFromHash( hash );
  1441. if ( sharedNode === undefined ) {
  1442. builder.setHashNode( this, hash );
  1443. sharedNode = this;
  1444. }
  1445. const sharedNodeType = sharedNode.getInputType( builder );
  1446. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  1447. const propertyName = builder.getPropertyName( nodeUniform );
  1448. if ( builder.context.label !== undefined ) delete builder.context.label;
  1449. return builder.format( propertyName, type, output );
  1450. }
  1451. }
  1452. const uniform = ( arg1, arg2 ) => {
  1453. const nodeType = getConstNodeType( arg2 || arg1 );
  1454. // @TODO: get ConstNode from .traverse() in the future
  1455. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  1456. return nodeObject( new UniformNode( value, nodeType ) );
  1457. };
  1458. class PropertyNode extends Node {
  1459. static get type() {
  1460. return 'PropertyNode';
  1461. }
  1462. constructor( nodeType, name = null, varying = false ) {
  1463. super( nodeType );
  1464. this.name = name;
  1465. this.varying = varying;
  1466. this.isPropertyNode = true;
  1467. }
  1468. getHash( builder ) {
  1469. return this.name || super.getHash( builder );
  1470. }
  1471. isGlobal( /*builder*/ ) {
  1472. return true;
  1473. }
  1474. generate( builder ) {
  1475. let nodeVar;
  1476. if ( this.varying === true ) {
  1477. nodeVar = builder.getVaryingFromNode( this, this.name );
  1478. nodeVar.needsInterpolation = true;
  1479. } else {
  1480. nodeVar = builder.getVarFromNode( this, this.name );
  1481. }
  1482. return builder.getPropertyName( nodeVar );
  1483. }
  1484. }
  1485. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  1486. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  1487. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  1488. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  1489. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  1490. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  1491. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  1492. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  1493. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  1494. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  1495. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  1496. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  1497. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  1498. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  1499. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  1500. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  1501. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  1502. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  1503. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  1504. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  1505. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  1506. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  1507. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  1508. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  1509. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  1510. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  1511. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  1512. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  1513. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  1514. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  1515. class AssignNode extends TempNode {
  1516. static get type() {
  1517. return 'AssignNode';
  1518. }
  1519. constructor( targetNode, sourceNode ) {
  1520. super();
  1521. this.targetNode = targetNode;
  1522. this.sourceNode = sourceNode;
  1523. }
  1524. hasDependencies() {
  1525. return false;
  1526. }
  1527. getNodeType( builder, output ) {
  1528. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  1529. }
  1530. needsSplitAssign( builder ) {
  1531. const { targetNode } = this;
  1532. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  1533. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  1534. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  1535. return assignDiferentVector;
  1536. }
  1537. return false;
  1538. }
  1539. generate( builder, output ) {
  1540. const { targetNode, sourceNode } = this;
  1541. const needsSplitAssign = this.needsSplitAssign( builder );
  1542. const targetType = targetNode.getNodeType( builder );
  1543. const target = targetNode.context( { assign: true } ).build( builder );
  1544. const source = sourceNode.build( builder, targetType );
  1545. const sourceType = sourceNode.getNodeType( builder );
  1546. const nodeData = builder.getDataFromNode( this );
  1547. //
  1548. let snippet;
  1549. if ( nodeData.initialized === true ) {
  1550. if ( output !== 'void' ) {
  1551. snippet = target;
  1552. }
  1553. } else if ( needsSplitAssign ) {
  1554. const sourceVar = builder.getVarFromNode( this, null, targetType );
  1555. const sourceProperty = builder.getPropertyName( sourceVar );
  1556. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  1557. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  1558. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  1559. const component = targetNode.components[ i ];
  1560. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  1561. }
  1562. if ( output !== 'void' ) {
  1563. snippet = target;
  1564. }
  1565. } else {
  1566. snippet = `${ target } = ${ source }`;
  1567. if ( output === 'void' || sourceType === 'void' ) {
  1568. builder.addLineFlowCode( snippet, this );
  1569. if ( output !== 'void' ) {
  1570. snippet = target;
  1571. }
  1572. }
  1573. }
  1574. nodeData.initialized = true;
  1575. return builder.format( snippet, targetType, output );
  1576. }
  1577. }
  1578. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  1579. addMethodChaining( 'assign', assign );
  1580. class FunctionCallNode extends TempNode {
  1581. static get type() {
  1582. return 'FunctionCallNode';
  1583. }
  1584. constructor( functionNode = null, parameters = {} ) {
  1585. super();
  1586. this.functionNode = functionNode;
  1587. this.parameters = parameters;
  1588. }
  1589. setParameters( parameters ) {
  1590. this.parameters = parameters;
  1591. return this;
  1592. }
  1593. getParameters() {
  1594. return this.parameters;
  1595. }
  1596. getNodeType( builder ) {
  1597. return this.functionNode.getNodeType( builder );
  1598. }
  1599. generate( builder ) {
  1600. const params = [];
  1601. const functionNode = this.functionNode;
  1602. const inputs = functionNode.getInputs( builder );
  1603. const parameters = this.parameters;
  1604. const generateInput = ( node, inputNode ) => {
  1605. const type = inputNode.type;
  1606. const pointer = type === 'pointer';
  1607. let output;
  1608. if ( pointer ) output = '&' + node.build( builder );
  1609. else output = node.build( builder, type );
  1610. return output;
  1611. };
  1612. if ( Array.isArray( parameters ) ) {
  1613. for ( let i = 0; i < parameters.length; i ++ ) {
  1614. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  1615. }
  1616. } else {
  1617. for ( const inputNode of inputs ) {
  1618. const node = parameters[ inputNode.name ];
  1619. if ( node !== undefined ) {
  1620. params.push( generateInput( node, inputNode ) );
  1621. } else {
  1622. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  1623. }
  1624. }
  1625. }
  1626. const functionName = functionNode.build( builder, 'property' );
  1627. return `${functionName}( ${params.join( ', ' )} )`;
  1628. }
  1629. }
  1630. const call = ( func, ...params ) => {
  1631. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  1632. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  1633. };
  1634. addMethodChaining( 'call', call );
  1635. class OperatorNode extends TempNode {
  1636. static get type() {
  1637. return 'OperatorNode';
  1638. }
  1639. constructor( op, aNode, bNode, ...params ) {
  1640. super();
  1641. if ( params.length > 0 ) {
  1642. let finalOp = new OperatorNode( op, aNode, bNode );
  1643. for ( let i = 0; i < params.length - 1; i ++ ) {
  1644. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  1645. }
  1646. aNode = finalOp;
  1647. bNode = params[ params.length - 1 ];
  1648. }
  1649. this.op = op;
  1650. this.aNode = aNode;
  1651. this.bNode = bNode;
  1652. }
  1653. getNodeType( builder, output ) {
  1654. const op = this.op;
  1655. const aNode = this.aNode;
  1656. const bNode = this.bNode;
  1657. const typeA = aNode.getNodeType( builder );
  1658. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1659. if ( typeA === 'void' || typeB === 'void' ) {
  1660. return 'void';
  1661. } else if ( op === '%' ) {
  1662. return typeA;
  1663. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  1664. return builder.getIntegerType( typeA );
  1665. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  1666. return 'bool';
  1667. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  1668. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  1669. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  1670. } else {
  1671. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  1672. return typeB;
  1673. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1674. // matrix x vector
  1675. return builder.getVectorFromMatrix( typeA );
  1676. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1677. // vector x matrix
  1678. return builder.getVectorFromMatrix( typeB );
  1679. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  1680. // anytype x anytype: use the greater length vector
  1681. return typeB;
  1682. }
  1683. return typeA;
  1684. }
  1685. }
  1686. generate( builder, output ) {
  1687. const op = this.op;
  1688. const aNode = this.aNode;
  1689. const bNode = this.bNode;
  1690. const type = this.getNodeType( builder, output );
  1691. let typeA = null;
  1692. let typeB = null;
  1693. if ( type !== 'void' ) {
  1694. typeA = aNode.getNodeType( builder );
  1695. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1696. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  1697. if ( builder.isVector( typeA ) ) {
  1698. typeB = typeA;
  1699. } else if ( typeA !== typeB ) {
  1700. typeA = typeB = 'float';
  1701. }
  1702. } else if ( op === '>>' || op === '<<' ) {
  1703. typeA = type;
  1704. typeB = builder.changeComponentType( typeB, 'uint' );
  1705. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1706. // matrix x vector
  1707. typeB = builder.getVectorFromMatrix( typeA );
  1708. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1709. // vector x matrix
  1710. typeA = builder.getVectorFromMatrix( typeB );
  1711. } else {
  1712. // anytype x anytype
  1713. typeA = typeB = type;
  1714. }
  1715. } else {
  1716. typeA = typeB = type;
  1717. }
  1718. const a = aNode.build( builder, typeA );
  1719. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  1720. const outputLength = builder.getTypeLength( output );
  1721. const fnOpSnippet = builder.getFunctionOperator( op );
  1722. if ( output !== 'void' ) {
  1723. if ( op === '<' && outputLength > 1 ) {
  1724. if ( builder.useComparisonMethod ) {
  1725. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  1726. } else {
  1727. return builder.format( `( ${ a } < ${ b } )`, type, output );
  1728. }
  1729. } else if ( op === '<=' && outputLength > 1 ) {
  1730. if ( builder.useComparisonMethod ) {
  1731. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1732. } else {
  1733. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  1734. }
  1735. } else if ( op === '>' && outputLength > 1 ) {
  1736. if ( builder.useComparisonMethod ) {
  1737. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  1738. } else {
  1739. return builder.format( `( ${ a } > ${ b } )`, type, output );
  1740. }
  1741. } else if ( op === '>=' && outputLength > 1 ) {
  1742. if ( builder.useComparisonMethod ) {
  1743. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1744. } else {
  1745. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  1746. }
  1747. } else if ( op === '!' || op === '~' ) {
  1748. return builder.format( `(${op}${a})`, typeA, output );
  1749. } else if ( fnOpSnippet ) {
  1750. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1751. } else {
  1752. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  1753. }
  1754. } else if ( typeA !== 'void' ) {
  1755. if ( fnOpSnippet ) {
  1756. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1757. } else {
  1758. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  1759. }
  1760. }
  1761. }
  1762. serialize( data ) {
  1763. super.serialize( data );
  1764. data.op = this.op;
  1765. }
  1766. deserialize( data ) {
  1767. super.deserialize( data );
  1768. this.op = data.op;
  1769. }
  1770. }
  1771. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  1772. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  1773. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  1774. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  1775. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  1776. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  1777. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  1778. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  1779. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  1780. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  1781. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  1782. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  1783. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  1784. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  1785. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  1786. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  1787. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  1788. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  1789. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  1790. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  1791. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  1792. addMethodChaining( 'add', add );
  1793. addMethodChaining( 'sub', sub );
  1794. addMethodChaining( 'mul', mul );
  1795. addMethodChaining( 'div', div );
  1796. addMethodChaining( 'modInt', modInt );
  1797. addMethodChaining( 'equal', equal );
  1798. addMethodChaining( 'notEqual', notEqual );
  1799. addMethodChaining( 'lessThan', lessThan );
  1800. addMethodChaining( 'greaterThan', greaterThan );
  1801. addMethodChaining( 'lessThanEqual', lessThanEqual );
  1802. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  1803. addMethodChaining( 'and', and );
  1804. addMethodChaining( 'or', or );
  1805. addMethodChaining( 'not', not );
  1806. addMethodChaining( 'xor', xor );
  1807. addMethodChaining( 'bitAnd', bitAnd );
  1808. addMethodChaining( 'bitNot', bitNot );
  1809. addMethodChaining( 'bitOr', bitOr );
  1810. addMethodChaining( 'bitXor', bitXor );
  1811. addMethodChaining( 'shiftLeft', shiftLeft );
  1812. addMethodChaining( 'shiftRight', shiftRight );
  1813. const remainder = ( ...params ) => { // @deprecated, r168
  1814. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  1815. return modInt( ...params );
  1816. };
  1817. addMethodChaining( 'remainder', remainder );
  1818. class MathNode extends TempNode {
  1819. static get type() {
  1820. return 'MathNode';
  1821. }
  1822. constructor( method, aNode, bNode = null, cNode = null ) {
  1823. super();
  1824. this.method = method;
  1825. this.aNode = aNode;
  1826. this.bNode = bNode;
  1827. this.cNode = cNode;
  1828. }
  1829. getInputType( builder ) {
  1830. const aType = this.aNode.getNodeType( builder );
  1831. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  1832. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  1833. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  1834. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  1835. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  1836. if ( aLen > bLen && aLen > cLen ) {
  1837. return aType;
  1838. } else if ( bLen > cLen ) {
  1839. return bType;
  1840. } else if ( cLen > aLen ) {
  1841. return cType;
  1842. }
  1843. return aType;
  1844. }
  1845. getNodeType( builder ) {
  1846. const method = this.method;
  1847. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  1848. return 'float';
  1849. } else if ( method === MathNode.CROSS ) {
  1850. return 'vec3';
  1851. } else if ( method === MathNode.ALL ) {
  1852. return 'bool';
  1853. } else if ( method === MathNode.EQUALS ) {
  1854. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  1855. } else if ( method === MathNode.MOD ) {
  1856. return this.aNode.getNodeType( builder );
  1857. } else {
  1858. return this.getInputType( builder );
  1859. }
  1860. }
  1861. generate( builder, output ) {
  1862. const method = this.method;
  1863. const type = this.getNodeType( builder );
  1864. const inputType = this.getInputType( builder );
  1865. const a = this.aNode;
  1866. const b = this.bNode;
  1867. const c = this.cNode;
  1868. const isWebGL = builder.renderer.isWebGLRenderer === true;
  1869. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  1870. // dir can be either a direction vector or a normal vector
  1871. // upper-left 3x3 of matrix is assumed to be orthogonal
  1872. let tA = a;
  1873. let tB = b;
  1874. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  1875. tB = vec4( vec3( tB ), 0.0 );
  1876. } else {
  1877. tA = vec4( vec3( tA ), 0.0 );
  1878. }
  1879. const mulNode = mul( tA, tB ).xyz;
  1880. return normalize( mulNode ).build( builder, output );
  1881. } else if ( method === MathNode.NEGATE ) {
  1882. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  1883. } else if ( method === MathNode.ONE_MINUS ) {
  1884. return sub( 1.0, a ).build( builder, output );
  1885. } else if ( method === MathNode.RECIPROCAL ) {
  1886. return div( 1.0, a ).build( builder, output );
  1887. } else if ( method === MathNode.DIFFERENCE ) {
  1888. return abs( sub( a, b ) ).build( builder, output );
  1889. } else {
  1890. const params = [];
  1891. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  1892. params.push(
  1893. a.build( builder, type ),
  1894. b.build( builder, type )
  1895. );
  1896. } else if ( isWebGL && method === MathNode.STEP ) {
  1897. params.push(
  1898. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  1899. b.build( builder, inputType )
  1900. );
  1901. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  1902. params.push(
  1903. a.build( builder, inputType ),
  1904. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1905. );
  1906. } else if ( method === MathNode.REFRACT ) {
  1907. params.push(
  1908. a.build( builder, inputType ),
  1909. b.build( builder, inputType ),
  1910. c.build( builder, 'float' )
  1911. );
  1912. } else if ( method === MathNode.MIX ) {
  1913. params.push(
  1914. a.build( builder, inputType ),
  1915. b.build( builder, inputType ),
  1916. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1917. );
  1918. } else {
  1919. params.push( a.build( builder, inputType ) );
  1920. if ( b !== null ) params.push( b.build( builder, inputType ) );
  1921. if ( c !== null ) params.push( c.build( builder, inputType ) );
  1922. }
  1923. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  1924. }
  1925. }
  1926. serialize( data ) {
  1927. super.serialize( data );
  1928. data.method = this.method;
  1929. }
  1930. deserialize( data ) {
  1931. super.deserialize( data );
  1932. this.method = data.method;
  1933. }
  1934. }
  1935. // 1 input
  1936. MathNode.ALL = 'all';
  1937. MathNode.ANY = 'any';
  1938. MathNode.EQUALS = 'equals';
  1939. MathNode.RADIANS = 'radians';
  1940. MathNode.DEGREES = 'degrees';
  1941. MathNode.EXP = 'exp';
  1942. MathNode.EXP2 = 'exp2';
  1943. MathNode.LOG = 'log';
  1944. MathNode.LOG2 = 'log2';
  1945. MathNode.SQRT = 'sqrt';
  1946. MathNode.INVERSE_SQRT = 'inversesqrt';
  1947. MathNode.FLOOR = 'floor';
  1948. MathNode.CEIL = 'ceil';
  1949. MathNode.NORMALIZE = 'normalize';
  1950. MathNode.FRACT = 'fract';
  1951. MathNode.SIN = 'sin';
  1952. MathNode.COS = 'cos';
  1953. MathNode.TAN = 'tan';
  1954. MathNode.ASIN = 'asin';
  1955. MathNode.ACOS = 'acos';
  1956. MathNode.ATAN = 'atan';
  1957. MathNode.ABS = 'abs';
  1958. MathNode.SIGN = 'sign';
  1959. MathNode.LENGTH = 'length';
  1960. MathNode.NEGATE = 'negate';
  1961. MathNode.ONE_MINUS = 'oneMinus';
  1962. MathNode.DFDX = 'dFdx';
  1963. MathNode.DFDY = 'dFdy';
  1964. MathNode.ROUND = 'round';
  1965. MathNode.RECIPROCAL = 'reciprocal';
  1966. MathNode.TRUNC = 'trunc';
  1967. MathNode.FWIDTH = 'fwidth';
  1968. MathNode.BITCAST = 'bitcast';
  1969. MathNode.TRANSPOSE = 'transpose';
  1970. // 2 inputs
  1971. MathNode.ATAN2 = 'atan2';
  1972. MathNode.MIN = 'min';
  1973. MathNode.MAX = 'max';
  1974. MathNode.MOD = 'mod';
  1975. MathNode.STEP = 'step';
  1976. MathNode.REFLECT = 'reflect';
  1977. MathNode.DISTANCE = 'distance';
  1978. MathNode.DIFFERENCE = 'difference';
  1979. MathNode.DOT = 'dot';
  1980. MathNode.CROSS = 'cross';
  1981. MathNode.POW = 'pow';
  1982. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  1983. // 3 inputs
  1984. MathNode.MIX = 'mix';
  1985. MathNode.CLAMP = 'clamp';
  1986. MathNode.REFRACT = 'refract';
  1987. MathNode.SMOOTHSTEP = 'smoothstep';
  1988. MathNode.FACEFORWARD = 'faceforward';
  1989. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  1990. const INFINITY = /*@__PURE__*/ float( 1e6 );
  1991. const PI = /*@__PURE__*/ float( Math.PI );
  1992. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  1993. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  1994. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  1995. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  1996. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  1997. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  1998. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  1999. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2000. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2001. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2002. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2003. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2004. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2005. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2006. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2007. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2008. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2009. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2010. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2011. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2012. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2013. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2014. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2015. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2016. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2017. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2018. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2019. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2020. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2021. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2022. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2023. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2024. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2025. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2026. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2027. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2028. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2029. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2030. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2031. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2032. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2033. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2034. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2035. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2036. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2037. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2038. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2039. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2040. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2041. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2042. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2043. const lengthSq = ( a ) => dot( a, a );
  2044. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2045. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2046. const saturate = ( value ) => clamp( value );
  2047. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2048. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2049. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2050. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2051. const a = 12.9898, b = 78.233, c = 43758.5453;
  2052. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2053. return fract( sin( sn ).mul( c ) );
  2054. } );
  2055. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2056. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2057. addMethodChaining( 'all', all );
  2058. addMethodChaining( 'any', any );
  2059. addMethodChaining( 'equals', equals );
  2060. addMethodChaining( 'radians', radians );
  2061. addMethodChaining( 'degrees', degrees );
  2062. addMethodChaining( 'exp', exp );
  2063. addMethodChaining( 'exp2', exp2 );
  2064. addMethodChaining( 'log', log );
  2065. addMethodChaining( 'log2', log2 );
  2066. addMethodChaining( 'sqrt', sqrt );
  2067. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2068. addMethodChaining( 'floor', floor );
  2069. addMethodChaining( 'ceil', ceil );
  2070. addMethodChaining( 'normalize', normalize );
  2071. addMethodChaining( 'fract', fract );
  2072. addMethodChaining( 'sin', sin );
  2073. addMethodChaining( 'cos', cos );
  2074. addMethodChaining( 'tan', tan );
  2075. addMethodChaining( 'asin', asin );
  2076. addMethodChaining( 'acos', acos );
  2077. addMethodChaining( 'atan', atan );
  2078. addMethodChaining( 'abs', abs );
  2079. addMethodChaining( 'sign', sign );
  2080. addMethodChaining( 'length', length );
  2081. addMethodChaining( 'lengthSq', lengthSq );
  2082. addMethodChaining( 'negate', negate );
  2083. addMethodChaining( 'oneMinus', oneMinus );
  2084. addMethodChaining( 'dFdx', dFdx );
  2085. addMethodChaining( 'dFdy', dFdy );
  2086. addMethodChaining( 'round', round );
  2087. addMethodChaining( 'reciprocal', reciprocal );
  2088. addMethodChaining( 'trunc', trunc );
  2089. addMethodChaining( 'fwidth', fwidth );
  2090. addMethodChaining( 'atan2', atan2 );
  2091. addMethodChaining( 'min', min$1 );
  2092. addMethodChaining( 'max', max$1 );
  2093. addMethodChaining( 'mod', mod );
  2094. addMethodChaining( 'step', step );
  2095. addMethodChaining( 'reflect', reflect );
  2096. addMethodChaining( 'distance', distance );
  2097. addMethodChaining( 'dot', dot );
  2098. addMethodChaining( 'cross', cross );
  2099. addMethodChaining( 'pow', pow );
  2100. addMethodChaining( 'pow2', pow2 );
  2101. addMethodChaining( 'pow3', pow3 );
  2102. addMethodChaining( 'pow4', pow4 );
  2103. addMethodChaining( 'transformDirection', transformDirection );
  2104. addMethodChaining( 'mix', mixElement );
  2105. addMethodChaining( 'clamp', clamp );
  2106. addMethodChaining( 'refract', refract );
  2107. addMethodChaining( 'smoothstep', smoothstepElement );
  2108. addMethodChaining( 'faceForward', faceForward );
  2109. addMethodChaining( 'difference', difference );
  2110. addMethodChaining( 'saturate', saturate );
  2111. addMethodChaining( 'cbrt', cbrt );
  2112. addMethodChaining( 'transpose', transpose );
  2113. addMethodChaining( 'rand', rand );
  2114. class ConditionalNode extends Node {
  2115. static get type() {
  2116. return 'ConditionalNode';
  2117. }
  2118. constructor( condNode, ifNode, elseNode = null ) {
  2119. super();
  2120. this.condNode = condNode;
  2121. this.ifNode = ifNode;
  2122. this.elseNode = elseNode;
  2123. }
  2124. getNodeType( builder ) {
  2125. const ifType = this.ifNode.getNodeType( builder );
  2126. if ( this.elseNode !== null ) {
  2127. const elseType = this.elseNode.getNodeType( builder );
  2128. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2129. return elseType;
  2130. }
  2131. }
  2132. return ifType;
  2133. }
  2134. setup( builder ) {
  2135. const condNode = this.condNode.cache();
  2136. const ifNode = this.ifNode.cache();
  2137. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2138. //
  2139. const currentNodeBlock = builder.context.nodeBlock;
  2140. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2141. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2142. //
  2143. const properties = builder.getNodeProperties( this );
  2144. properties.condNode = condNode;
  2145. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2146. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2147. }
  2148. generate( builder, output ) {
  2149. const type = this.getNodeType( builder );
  2150. const nodeData = builder.getDataFromNode( this );
  2151. if ( nodeData.nodeProperty !== undefined ) {
  2152. return nodeData.nodeProperty;
  2153. }
  2154. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2155. const needsOutput = output !== 'void';
  2156. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2157. nodeData.nodeProperty = nodeProperty;
  2158. const nodeSnippet = condNode.build( builder, 'bool' );
  2159. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2160. let ifSnippet = ifNode.build( builder, type );
  2161. if ( ifSnippet ) {
  2162. if ( needsOutput ) {
  2163. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2164. } else {
  2165. ifSnippet = 'return ' + ifSnippet + ';';
  2166. }
  2167. }
  2168. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2169. if ( elseNode !== null ) {
  2170. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2171. let elseSnippet = elseNode.build( builder, type );
  2172. if ( elseSnippet ) {
  2173. if ( needsOutput ) {
  2174. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2175. } else {
  2176. elseSnippet = 'return ' + elseSnippet + ';';
  2177. }
  2178. }
  2179. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2180. } else {
  2181. builder.addFlowCode( '\n\n' );
  2182. }
  2183. return builder.format( nodeProperty, type, output );
  2184. }
  2185. }
  2186. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2187. addMethodChaining( 'select', select );
  2188. //
  2189. const cond = ( ...params ) => { // @deprecated, r168
  2190. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2191. return select( ...params );
  2192. };
  2193. addMethodChaining( 'cond', cond );
  2194. class ContextNode extends Node {
  2195. static get type() {
  2196. return 'ContextNode';
  2197. }
  2198. constructor( node, value = {} ) {
  2199. super();
  2200. this.isContextNode = true;
  2201. this.node = node;
  2202. this.value = value;
  2203. }
  2204. getScope() {
  2205. return this.node.getScope();
  2206. }
  2207. getNodeType( builder ) {
  2208. return this.node.getNodeType( builder );
  2209. }
  2210. analyze( builder ) {
  2211. this.node.build( builder );
  2212. }
  2213. setup( builder ) {
  2214. const previousContext = builder.getContext();
  2215. builder.setContext( { ...builder.context, ...this.value } );
  2216. const node = this.node.build( builder );
  2217. builder.setContext( previousContext );
  2218. return node;
  2219. }
  2220. generate( builder, output ) {
  2221. const previousContext = builder.getContext();
  2222. builder.setContext( { ...builder.context, ...this.value } );
  2223. const snippet = this.node.build( builder, output );
  2224. builder.setContext( previousContext );
  2225. return snippet;
  2226. }
  2227. }
  2228. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2229. const label = ( node, name ) => context( node, { label: name } );
  2230. addMethodChaining( 'context', context );
  2231. addMethodChaining( 'label', label );
  2232. class VarNode extends Node {
  2233. static get type() {
  2234. return 'VarNode';
  2235. }
  2236. constructor( node, name = null ) {
  2237. super();
  2238. this.node = node;
  2239. this.name = name;
  2240. this.global = true;
  2241. this.isVarNode = true;
  2242. }
  2243. getHash( builder ) {
  2244. return this.name || super.getHash( builder );
  2245. }
  2246. getNodeType( builder ) {
  2247. return this.node.getNodeType( builder );
  2248. }
  2249. generate( builder ) {
  2250. const { node, name } = this;
  2251. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  2252. const propertyName = builder.getPropertyName( nodeVar );
  2253. const snippet = node.build( builder, nodeVar.type );
  2254. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  2255. return propertyName;
  2256. }
  2257. }
  2258. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  2259. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  2260. // Deprecated
  2261. const temp = ( node ) => { // @deprecated, r170
  2262. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  2263. return createVar( node );
  2264. };
  2265. addMethodChaining( 'temp', temp );
  2266. class VaryingNode extends Node {
  2267. static get type() {
  2268. return 'VaryingNode';
  2269. }
  2270. constructor( node, name = null ) {
  2271. super();
  2272. this.node = node;
  2273. this.name = name;
  2274. this.isVaryingNode = true;
  2275. }
  2276. isGlobal() {
  2277. return true;
  2278. }
  2279. getHash( builder ) {
  2280. return this.name || super.getHash( builder );
  2281. }
  2282. getNodeType( builder ) {
  2283. // VaryingNode is auto type
  2284. return this.node.getNodeType( builder );
  2285. }
  2286. setupVarying( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. let varying = properties.varying;
  2289. if ( varying === undefined ) {
  2290. const name = this.name;
  2291. const type = this.getNodeType( builder );
  2292. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  2293. properties.node = this.node;
  2294. }
  2295. // this property can be used to check if the varying can be optimized for a variable
  2296. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  2297. return varying;
  2298. }
  2299. setup( builder ) {
  2300. this.setupVarying( builder );
  2301. }
  2302. analyze( builder ) {
  2303. this.setupVarying( builder );
  2304. return this.node.analyze( builder );
  2305. }
  2306. generate( builder ) {
  2307. const properties = builder.getNodeProperties( this );
  2308. const varying = this.setupVarying( builder );
  2309. if ( properties.propertyName === undefined ) {
  2310. const type = this.getNodeType( builder );
  2311. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  2312. // force node run in vertex stage
  2313. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  2314. properties.propertyName = propertyName;
  2315. }
  2316. return builder.getPropertyName( varying );
  2317. }
  2318. }
  2319. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  2320. addMethodChaining( 'varying', varying );
  2321. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2322. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  2323. const b = color.mul( 0.0773993808 );
  2324. const factor = color.lessThanEqual( 0.04045 );
  2325. const rgbResult = mix( a, b, factor );
  2326. return rgbResult;
  2327. } ).setLayout( {
  2328. name: 'sRGBTransferEOTF',
  2329. type: 'vec3',
  2330. inputs: [
  2331. { name: 'color', type: 'vec3' }
  2332. ]
  2333. } );
  2334. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2335. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  2336. const b = color.mul( 12.92 );
  2337. const factor = color.lessThanEqual( 0.0031308 );
  2338. const rgbResult = mix( a, b, factor );
  2339. return rgbResult;
  2340. } ).setLayout( {
  2341. name: 'sRGBTransferOETF',
  2342. type: 'vec3',
  2343. inputs: [
  2344. { name: 'color', type: 'vec3' }
  2345. ]
  2346. } );
  2347. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  2348. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  2349. class ColorSpaceNode extends TempNode {
  2350. static get type() {
  2351. return 'ColorSpaceNode';
  2352. }
  2353. constructor( colorNode, source, target ) {
  2354. super( 'vec4' );
  2355. this.colorNode = colorNode;
  2356. this.source = source;
  2357. this.target = target;
  2358. }
  2359. resolveColorSpace( builder, colorSpace ) {
  2360. if ( colorSpace === WORKING_COLOR_SPACE ) {
  2361. return ColorManagement.workingColorSpace;
  2362. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  2363. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  2364. }
  2365. return colorSpace;
  2366. }
  2367. setup( builder ) {
  2368. const { colorNode } = this;
  2369. const source = this.resolveColorSpace( builder, this.source );
  2370. const target = this.resolveColorSpace( builder, this.target );
  2371. let outputNode = colorNode;
  2372. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  2373. return outputNode;
  2374. }
  2375. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  2376. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  2377. }
  2378. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  2379. outputNode = vec4(
  2380. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  2381. outputNode.a
  2382. );
  2383. }
  2384. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  2385. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  2386. }
  2387. return outputNode;
  2388. }
  2389. }
  2390. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  2391. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  2392. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  2393. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  2394. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  2395. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  2396. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  2397. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  2398. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  2399. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  2400. static get type() {
  2401. return 'ReferenceElementNode';
  2402. }
  2403. constructor( referenceNode, indexNode ) {
  2404. super( referenceNode, indexNode );
  2405. this.referenceNode = referenceNode;
  2406. this.isReferenceElementNode = true;
  2407. }
  2408. getNodeType() {
  2409. return this.referenceNode.uniformType;
  2410. }
  2411. generate( builder ) {
  2412. const snippet = super.generate( builder );
  2413. const arrayType = this.referenceNode.getNodeType();
  2414. const elementType = this.getNodeType();
  2415. return builder.format( snippet, arrayType, elementType );
  2416. }
  2417. };
  2418. class ReferenceBaseNode extends Node {
  2419. static get type() {
  2420. return 'ReferenceBaseNode';
  2421. }
  2422. constructor( property, uniformType, object = null, count = null ) {
  2423. super();
  2424. this.property = property;
  2425. this.uniformType = uniformType;
  2426. this.object = object;
  2427. this.count = count;
  2428. this.properties = property.split( '.' );
  2429. this.reference = object;
  2430. this.node = null;
  2431. this.group = null;
  2432. this.updateType = NodeUpdateType.OBJECT;
  2433. }
  2434. setGroup( group ) {
  2435. this.group = group;
  2436. return this;
  2437. }
  2438. element( indexNode ) {
  2439. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  2440. }
  2441. setNodeType( uniformType ) {
  2442. const node = uniform( null, uniformType ).getSelf();
  2443. if ( this.group !== null ) {
  2444. node.setGroup( this.group );
  2445. }
  2446. this.node = node;
  2447. }
  2448. getNodeType( builder ) {
  2449. if ( this.node === null ) {
  2450. this.updateReference( builder );
  2451. this.updateValue();
  2452. }
  2453. return this.node.getNodeType( builder );
  2454. }
  2455. getValueFromReference( object = this.reference ) {
  2456. const { properties } = this;
  2457. let value = object[ properties[ 0 ] ];
  2458. for ( let i = 1; i < properties.length; i ++ ) {
  2459. value = value[ properties[ i ] ];
  2460. }
  2461. return value;
  2462. }
  2463. updateReference( state ) {
  2464. this.reference = this.object !== null ? this.object : state.object;
  2465. return this.reference;
  2466. }
  2467. setup() {
  2468. this.updateValue();
  2469. return this.node;
  2470. }
  2471. update( /*frame*/ ) {
  2472. this.updateValue();
  2473. }
  2474. updateValue() {
  2475. if ( this.node === null ) this.setNodeType( this.uniformType );
  2476. const value = this.getValueFromReference();
  2477. if ( Array.isArray( value ) ) {
  2478. this.node.array = value;
  2479. } else {
  2480. this.node.value = value;
  2481. }
  2482. }
  2483. }
  2484. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  2485. class RendererReferenceNode extends ReferenceBaseNode {
  2486. static get type() {
  2487. return 'RendererReferenceNode';
  2488. }
  2489. constructor( property, inputType, renderer = null ) {
  2490. super( property, inputType, renderer );
  2491. this.renderer = renderer;
  2492. this.setGroup( renderGroup );
  2493. }
  2494. updateReference( state ) {
  2495. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  2496. return this.reference;
  2497. }
  2498. }
  2499. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  2500. class ToneMappingNode extends TempNode {
  2501. static get type() {
  2502. return 'ToneMappingNode';
  2503. }
  2504. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  2505. super( 'vec3' );
  2506. this.toneMapping = toneMapping;
  2507. this.exposureNode = exposureNode;
  2508. this.colorNode = colorNode;
  2509. }
  2510. getCacheKey() {
  2511. return hash$1( super.getCacheKey(), this.toneMapping );
  2512. }
  2513. setup( builder ) {
  2514. const colorNode = this.colorNode || builder.context.color;
  2515. const toneMapping = this.toneMapping;
  2516. if ( toneMapping === NoToneMapping ) return colorNode;
  2517. let outputNode = null;
  2518. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  2519. if ( toneMappingFn !== null ) {
  2520. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  2521. } else {
  2522. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  2523. outputNode = colorNode;
  2524. }
  2525. return outputNode;
  2526. }
  2527. }
  2528. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  2529. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  2530. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  2531. class BufferAttributeNode extends InputNode {
  2532. static get type() {
  2533. return 'BufferAttributeNode';
  2534. }
  2535. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  2536. super( value, bufferType );
  2537. this.isBufferNode = true;
  2538. this.bufferType = bufferType;
  2539. this.bufferStride = bufferStride;
  2540. this.bufferOffset = bufferOffset;
  2541. this.usage = StaticDrawUsage;
  2542. this.instanced = false;
  2543. this.attribute = null;
  2544. this.global = true;
  2545. if ( value && value.isBufferAttribute === true ) {
  2546. this.attribute = value;
  2547. this.usage = value.usage;
  2548. this.instanced = value.isInstancedBufferAttribute;
  2549. }
  2550. }
  2551. getHash( builder ) {
  2552. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  2553. let bufferData = builder.globalCache.getData( this.value );
  2554. if ( bufferData === undefined ) {
  2555. bufferData = {
  2556. node: this
  2557. };
  2558. builder.globalCache.setData( this.value, bufferData );
  2559. }
  2560. return bufferData.node.uuid;
  2561. }
  2562. return this.uuid;
  2563. }
  2564. getNodeType( builder ) {
  2565. if ( this.bufferType === null ) {
  2566. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  2567. }
  2568. return this.bufferType;
  2569. }
  2570. setup( builder ) {
  2571. if ( this.attribute !== null ) return;
  2572. const type = this.getNodeType( builder );
  2573. const array = this.value;
  2574. const itemSize = builder.getTypeLength( type );
  2575. const stride = this.bufferStride || itemSize;
  2576. const offset = this.bufferOffset;
  2577. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  2578. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  2579. buffer.setUsage( this.usage );
  2580. this.attribute = bufferAttribute;
  2581. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  2582. }
  2583. generate( builder ) {
  2584. const nodeType = this.getNodeType( builder );
  2585. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  2586. const propertyName = builder.getPropertyName( nodeAttribute );
  2587. let output = null;
  2588. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  2589. this.name = propertyName;
  2590. output = propertyName;
  2591. } else {
  2592. const nodeVarying = varying( this );
  2593. output = nodeVarying.build( builder, nodeType );
  2594. }
  2595. return output;
  2596. }
  2597. getInputType( /*builder*/ ) {
  2598. return 'bufferAttribute';
  2599. }
  2600. setUsage( value ) {
  2601. this.usage = value;
  2602. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  2603. this.attribute.usage = value;
  2604. }
  2605. return this;
  2606. }
  2607. setInstanced( value ) {
  2608. this.instanced = value;
  2609. return this;
  2610. }
  2611. }
  2612. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  2613. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  2614. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  2615. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  2616. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  2617. class ComputeNode extends Node {
  2618. static get type() {
  2619. return 'ComputeNode';
  2620. }
  2621. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  2622. super( 'void' );
  2623. this.isComputeNode = true;
  2624. this.computeNode = computeNode;
  2625. this.count = count;
  2626. this.workgroupSize = workgroupSize;
  2627. this.dispatchCount = 0;
  2628. this.version = 1;
  2629. this.updateBeforeType = NodeUpdateType.OBJECT;
  2630. this.onInitFunction = null;
  2631. this.updateDispatchCount();
  2632. }
  2633. dispose() {
  2634. this.dispatchEvent( { type: 'dispose' } );
  2635. }
  2636. set needsUpdate( value ) {
  2637. if ( value === true ) this.version ++;
  2638. }
  2639. updateDispatchCount() {
  2640. const { count, workgroupSize } = this;
  2641. let size = workgroupSize[ 0 ];
  2642. for ( let i = 1; i < workgroupSize.length; i ++ )
  2643. size *= workgroupSize[ i ];
  2644. this.dispatchCount = Math.ceil( count / size );
  2645. }
  2646. onInit( callback ) {
  2647. this.onInitFunction = callback;
  2648. return this;
  2649. }
  2650. updateBefore( { renderer } ) {
  2651. renderer.compute( this );
  2652. }
  2653. generate( builder ) {
  2654. const { shaderStage } = builder;
  2655. if ( shaderStage === 'compute' ) {
  2656. const snippet = this.computeNode.build( builder, 'void' );
  2657. if ( snippet !== '' ) {
  2658. builder.addLineFlowCode( snippet, this );
  2659. }
  2660. }
  2661. }
  2662. }
  2663. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  2664. addMethodChaining( 'compute', compute );
  2665. class CacheNode extends Node {
  2666. static get type() {
  2667. return 'CacheNode';
  2668. }
  2669. constructor( node, parent = true ) {
  2670. super();
  2671. this.node = node;
  2672. this.parent = parent;
  2673. this.isCacheNode = true;
  2674. }
  2675. getNodeType( builder ) {
  2676. return this.node.getNodeType( builder );
  2677. }
  2678. build( builder, ...params ) {
  2679. const previousCache = builder.getCache();
  2680. const cache = builder.getCacheFromNode( this, this.parent );
  2681. builder.setCache( cache );
  2682. const data = this.node.build( builder, ...params );
  2683. builder.setCache( previousCache );
  2684. return data;
  2685. }
  2686. }
  2687. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  2688. addMethodChaining( 'cache', cache );
  2689. class BypassNode extends Node {
  2690. static get type() {
  2691. return 'BypassNode';
  2692. }
  2693. constructor( returnNode, callNode ) {
  2694. super();
  2695. this.isBypassNode = true;
  2696. this.outputNode = returnNode;
  2697. this.callNode = callNode;
  2698. }
  2699. getNodeType( builder ) {
  2700. return this.outputNode.getNodeType( builder );
  2701. }
  2702. generate( builder ) {
  2703. const snippet = this.callNode.build( builder, 'void' );
  2704. if ( snippet !== '' ) {
  2705. builder.addLineFlowCode( snippet, this );
  2706. }
  2707. return this.outputNode.build( builder );
  2708. }
  2709. }
  2710. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  2711. addMethodChaining( 'bypass', bypass );
  2712. class RemapNode extends Node {
  2713. static get type() {
  2714. return 'RemapNode';
  2715. }
  2716. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  2717. super();
  2718. this.node = node;
  2719. this.inLowNode = inLowNode;
  2720. this.inHighNode = inHighNode;
  2721. this.outLowNode = outLowNode;
  2722. this.outHighNode = outHighNode;
  2723. this.doClamp = true;
  2724. }
  2725. setup() {
  2726. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  2727. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  2728. if ( doClamp === true ) t = t.clamp();
  2729. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  2730. }
  2731. }
  2732. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  2733. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  2734. addMethodChaining( 'remap', remap );
  2735. addMethodChaining( 'remapClamp', remapClamp );
  2736. class ExpressionNode extends Node {
  2737. static get type() {
  2738. return 'ExpressionNode';
  2739. }
  2740. constructor( snippet = '', nodeType = 'void' ) {
  2741. super( nodeType );
  2742. this.snippet = snippet;
  2743. }
  2744. generate( builder, output ) {
  2745. const type = this.getNodeType( builder );
  2746. const snippet = this.snippet;
  2747. if ( type === 'void' ) {
  2748. builder.addLineFlowCode( snippet, this );
  2749. } else {
  2750. return builder.format( `( ${ snippet } )`, type, output );
  2751. }
  2752. }
  2753. }
  2754. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  2755. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  2756. const Return = () => expression( 'return' ).append();
  2757. addMethodChaining( 'discard', Discard );
  2758. class RenderOutputNode extends TempNode {
  2759. static get type() {
  2760. return 'RenderOutputNode';
  2761. }
  2762. constructor( colorNode, toneMapping, outputColorSpace ) {
  2763. super( 'vec4' );
  2764. this.colorNode = colorNode;
  2765. this.toneMapping = toneMapping;
  2766. this.outputColorSpace = outputColorSpace;
  2767. this.isRenderOutput = true;
  2768. }
  2769. setup( { context } ) {
  2770. let outputNode = this.colorNode || context.color;
  2771. // tone mapping
  2772. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  2773. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  2774. if ( toneMapping !== NoToneMapping ) {
  2775. outputNode = outputNode.toneMapping( toneMapping );
  2776. }
  2777. // working to output color space
  2778. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  2779. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  2780. }
  2781. return outputNode;
  2782. }
  2783. }
  2784. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  2785. addMethodChaining( 'renderOutput', renderOutput );
  2786. // Non-PURE exports list, side-effects are required here.
  2787. // TSL Base Syntax
  2788. function addNodeElement( name/*, nodeElement*/ ) {
  2789. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  2790. }
  2791. class AttributeNode extends Node {
  2792. static get type() {
  2793. return 'AttributeNode';
  2794. }
  2795. constructor( attributeName, nodeType = null ) {
  2796. super( nodeType );
  2797. this.global = true;
  2798. this._attributeName = attributeName;
  2799. }
  2800. getHash( builder ) {
  2801. return this.getAttributeName( builder );
  2802. }
  2803. getNodeType( builder ) {
  2804. let nodeType = this.nodeType;
  2805. if ( nodeType === null ) {
  2806. const attributeName = this.getAttributeName( builder );
  2807. if ( builder.hasGeometryAttribute( attributeName ) ) {
  2808. const attribute = builder.geometry.getAttribute( attributeName );
  2809. nodeType = builder.getTypeFromAttribute( attribute );
  2810. } else {
  2811. nodeType = 'float';
  2812. }
  2813. }
  2814. return nodeType;
  2815. }
  2816. setAttributeName( attributeName ) {
  2817. this._attributeName = attributeName;
  2818. return this;
  2819. }
  2820. getAttributeName( /*builder*/ ) {
  2821. return this._attributeName;
  2822. }
  2823. generate( builder ) {
  2824. const attributeName = this.getAttributeName( builder );
  2825. const nodeType = this.getNodeType( builder );
  2826. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  2827. if ( geometryAttribute === true ) {
  2828. const attribute = builder.geometry.getAttribute( attributeName );
  2829. const attributeType = builder.getTypeFromAttribute( attribute );
  2830. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  2831. if ( builder.shaderStage === 'vertex' ) {
  2832. return builder.format( nodeAttribute.name, attributeType, nodeType );
  2833. } else {
  2834. const nodeVarying = varying( this );
  2835. return nodeVarying.build( builder, nodeType );
  2836. }
  2837. } else {
  2838. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  2839. return builder.generateConst( nodeType );
  2840. }
  2841. }
  2842. serialize( data ) {
  2843. super.serialize( data );
  2844. data.global = this.global;
  2845. data._attributeName = this._attributeName;
  2846. }
  2847. deserialize( data ) {
  2848. super.deserialize( data );
  2849. this.global = data.global;
  2850. this._attributeName = data._attributeName;
  2851. }
  2852. }
  2853. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  2854. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  2855. class TextureSizeNode extends Node {
  2856. static get type() {
  2857. return 'TextureSizeNode';
  2858. }
  2859. constructor( textureNode, levelNode = null ) {
  2860. super( 'uvec2' );
  2861. this.isTextureSizeNode = true;
  2862. this.textureNode = textureNode;
  2863. this.levelNode = levelNode;
  2864. }
  2865. generate( builder, output ) {
  2866. const textureProperty = this.textureNode.build( builder, 'property' );
  2867. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  2868. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  2869. }
  2870. }
  2871. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  2872. class MaxMipLevelNode extends UniformNode {
  2873. static get type() {
  2874. return 'MaxMipLevelNode';
  2875. }
  2876. constructor( textureNode ) {
  2877. super( 0 );
  2878. this._textureNode = textureNode;
  2879. this.updateType = NodeUpdateType.FRAME;
  2880. }
  2881. get textureNode() {
  2882. return this._textureNode;
  2883. }
  2884. get texture() {
  2885. return this._textureNode.value;
  2886. }
  2887. update() {
  2888. const texture = this.texture;
  2889. const images = texture.images;
  2890. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  2891. if ( image && image.width !== undefined ) {
  2892. const { width, height } = image;
  2893. this.value = Math.log2( Math.max( width, height ) );
  2894. }
  2895. }
  2896. }
  2897. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  2898. class TextureNode extends UniformNode {
  2899. static get type() {
  2900. return 'TextureNode';
  2901. }
  2902. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  2903. super( value );
  2904. this.isTextureNode = true;
  2905. this.uvNode = uvNode;
  2906. this.levelNode = levelNode;
  2907. this.biasNode = biasNode;
  2908. this.compareNode = null;
  2909. this.depthNode = null;
  2910. this.gradNode = null;
  2911. this.sampler = true;
  2912. this.updateMatrix = false;
  2913. this.updateType = NodeUpdateType.NONE;
  2914. this.referenceNode = null;
  2915. this._value = value;
  2916. this._matrixUniform = null;
  2917. this.setUpdateMatrix( uvNode === null );
  2918. }
  2919. set value( value ) {
  2920. if ( this.referenceNode ) {
  2921. this.referenceNode.value = value;
  2922. } else {
  2923. this._value = value;
  2924. }
  2925. }
  2926. get value() {
  2927. return this.referenceNode ? this.referenceNode.value : this._value;
  2928. }
  2929. getUniformHash( /*builder*/ ) {
  2930. return this.value.uuid;
  2931. }
  2932. getNodeType( /*builder*/ ) {
  2933. if ( this.value.isDepthTexture === true ) return 'float';
  2934. if ( this.value.type === UnsignedIntType ) {
  2935. return 'uvec4';
  2936. } else if ( this.value.type === IntType ) {
  2937. return 'ivec4';
  2938. }
  2939. return 'vec4';
  2940. }
  2941. getInputType( /*builder*/ ) {
  2942. return 'texture';
  2943. }
  2944. getDefaultUV() {
  2945. return uv( this.value.channel );
  2946. }
  2947. updateReference( /*state*/ ) {
  2948. return this.value;
  2949. }
  2950. getTransformedUV( uvNode ) {
  2951. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  2952. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  2953. }
  2954. setUpdateMatrix( value ) {
  2955. this.updateMatrix = value;
  2956. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  2957. return this;
  2958. }
  2959. setupUV( builder, uvNode ) {
  2960. const texture = this.value;
  2961. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  2962. if ( this.sampler ) {
  2963. uvNode = uvNode.flipY();
  2964. } else {
  2965. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  2966. }
  2967. }
  2968. return uvNode;
  2969. }
  2970. setup( builder ) {
  2971. const properties = builder.getNodeProperties( this );
  2972. properties.referenceNode = this.referenceNode;
  2973. //
  2974. let uvNode = this.uvNode;
  2975. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  2976. uvNode = builder.context.getUV( this );
  2977. }
  2978. if ( ! uvNode ) uvNode = this.getDefaultUV();
  2979. if ( this.updateMatrix === true ) {
  2980. uvNode = this.getTransformedUV( uvNode );
  2981. }
  2982. uvNode = this.setupUV( builder, uvNode );
  2983. //
  2984. let levelNode = this.levelNode;
  2985. if ( levelNode === null && builder.context.getTextureLevel ) {
  2986. levelNode = builder.context.getTextureLevel( this );
  2987. }
  2988. //
  2989. properties.uvNode = uvNode;
  2990. properties.levelNode = levelNode;
  2991. properties.biasNode = this.biasNode;
  2992. properties.compareNode = this.compareNode;
  2993. properties.gradNode = this.gradNode;
  2994. properties.depthNode = this.depthNode;
  2995. }
  2996. generateUV( builder, uvNode ) {
  2997. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  2998. }
  2999. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3000. const texture = this.value;
  3001. let snippet;
  3002. if ( levelSnippet ) {
  3003. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3004. } else if ( biasSnippet ) {
  3005. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3006. } else if ( gradSnippet ) {
  3007. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3008. } else if ( compareSnippet ) {
  3009. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3010. } else if ( this.sampler === false ) {
  3011. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3012. } else {
  3013. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3014. }
  3015. return snippet;
  3016. }
  3017. generate( builder, output ) {
  3018. const properties = builder.getNodeProperties( this );
  3019. const texture = this.value;
  3020. if ( ! texture || texture.isTexture !== true ) {
  3021. throw new Error( 'TextureNode: Need a three.js texture.' );
  3022. }
  3023. const textureProperty = super.generate( builder, 'property' );
  3024. if ( output === 'sampler' ) {
  3025. return textureProperty + '_sampler';
  3026. } else if ( builder.isReference( output ) ) {
  3027. return textureProperty;
  3028. } else {
  3029. const nodeData = builder.getDataFromNode( this );
  3030. let propertyName = nodeData.propertyName;
  3031. if ( propertyName === undefined ) {
  3032. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3033. const uvSnippet = this.generateUV( builder, uvNode );
  3034. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3035. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3036. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3037. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3038. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3039. const nodeVar = builder.getVarFromNode( this );
  3040. propertyName = builder.getPropertyName( nodeVar );
  3041. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3042. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3043. nodeData.snippet = snippet;
  3044. nodeData.propertyName = propertyName;
  3045. }
  3046. let snippet = propertyName;
  3047. const nodeType = this.getNodeType( builder );
  3048. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3049. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3050. }
  3051. return builder.format( snippet, nodeType, output );
  3052. }
  3053. }
  3054. setSampler( value ) {
  3055. this.sampler = value;
  3056. return this;
  3057. }
  3058. getSampler() {
  3059. return this.sampler;
  3060. }
  3061. // @TODO: Move to TSL
  3062. uv( uvNode ) {
  3063. const textureNode = this.clone();
  3064. textureNode.uvNode = nodeObject( uvNode );
  3065. textureNode.referenceNode = this.getSelf();
  3066. return nodeObject( textureNode );
  3067. }
  3068. blur( amountNode ) {
  3069. const textureNode = this.clone();
  3070. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  3071. textureNode.referenceNode = this.getSelf();
  3072. return nodeObject( textureNode );
  3073. }
  3074. level( levelNode ) {
  3075. const textureNode = this.clone();
  3076. textureNode.levelNode = nodeObject( levelNode );
  3077. textureNode.referenceNode = this.getSelf();
  3078. return nodeObject( textureNode );
  3079. }
  3080. size( levelNode ) {
  3081. return textureSize( this, levelNode );
  3082. }
  3083. bias( biasNode ) {
  3084. const textureNode = this.clone();
  3085. textureNode.biasNode = nodeObject( biasNode );
  3086. textureNode.referenceNode = this.getSelf();
  3087. return nodeObject( textureNode );
  3088. }
  3089. compare( compareNode ) {
  3090. const textureNode = this.clone();
  3091. textureNode.compareNode = nodeObject( compareNode );
  3092. textureNode.referenceNode = this.getSelf();
  3093. return nodeObject( textureNode );
  3094. }
  3095. grad( gradNodeX, gradNodeY ) {
  3096. const textureNode = this.clone();
  3097. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  3098. textureNode.referenceNode = this.getSelf();
  3099. return nodeObject( textureNode );
  3100. }
  3101. depth( depthNode ) {
  3102. const textureNode = this.clone();
  3103. textureNode.depthNode = nodeObject( depthNode );
  3104. textureNode.referenceNode = this.getSelf();
  3105. return nodeObject( textureNode );
  3106. }
  3107. // --
  3108. serialize( data ) {
  3109. super.serialize( data );
  3110. data.value = this.value.toJSON( data.meta ).uuid;
  3111. data.sampler = this.sampler;
  3112. data.updateMatrix = this.updateMatrix;
  3113. data.updateType = this.updateType;
  3114. }
  3115. deserialize( data ) {
  3116. super.deserialize( data );
  3117. this.value = data.meta.textures[ data.value ];
  3118. this.sampler = data.sampler;
  3119. this.updateMatrix = data.updateMatrix;
  3120. this.updateType = data.updateType;
  3121. }
  3122. update() {
  3123. const texture = this.value;
  3124. const matrixUniform = this._matrixUniform;
  3125. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  3126. if ( texture.matrixAutoUpdate === true ) {
  3127. texture.updateMatrix();
  3128. }
  3129. }
  3130. clone() {
  3131. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  3132. newNode.sampler = this.sampler;
  3133. return newNode;
  3134. }
  3135. }
  3136. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  3137. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  3138. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  3139. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  3140. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  3141. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  3142. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  3143. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  3144. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  3145. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  3146. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  3147. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  3148. class Object3DNode extends Node {
  3149. static get type() {
  3150. return 'Object3DNode';
  3151. }
  3152. constructor( scope, object3d = null ) {
  3153. super();
  3154. this.scope = scope;
  3155. this.object3d = object3d;
  3156. this.updateType = NodeUpdateType.OBJECT;
  3157. this._uniformNode = new UniformNode( null );
  3158. }
  3159. getNodeType() {
  3160. const scope = this.scope;
  3161. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3162. return 'mat4';
  3163. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3164. return 'vec3';
  3165. }
  3166. }
  3167. update( frame ) {
  3168. const object = this.object3d;
  3169. const uniformNode = this._uniformNode;
  3170. const scope = this.scope;
  3171. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3172. uniformNode.value = object.matrixWorld;
  3173. } else if ( scope === Object3DNode.POSITION ) {
  3174. uniformNode.value = uniformNode.value || new Vector3();
  3175. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3176. } else if ( scope === Object3DNode.SCALE ) {
  3177. uniformNode.value = uniformNode.value || new Vector3();
  3178. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  3179. } else if ( scope === Object3DNode.DIRECTION ) {
  3180. uniformNode.value = uniformNode.value || new Vector3();
  3181. object.getWorldDirection( uniformNode.value );
  3182. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  3183. const camera = frame.camera;
  3184. uniformNode.value = uniformNode.value || new Vector3();
  3185. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3186. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  3187. }
  3188. }
  3189. generate( builder ) {
  3190. const scope = this.scope;
  3191. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3192. this._uniformNode.nodeType = 'mat4';
  3193. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3194. this._uniformNode.nodeType = 'vec3';
  3195. }
  3196. return this._uniformNode.build( builder );
  3197. }
  3198. serialize( data ) {
  3199. super.serialize( data );
  3200. data.scope = this.scope;
  3201. }
  3202. deserialize( data ) {
  3203. super.deserialize( data );
  3204. this.scope = data.scope;
  3205. }
  3206. }
  3207. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  3208. Object3DNode.POSITION = 'position';
  3209. Object3DNode.SCALE = 'scale';
  3210. Object3DNode.VIEW_POSITION = 'viewPosition';
  3211. Object3DNode.DIRECTION = 'direction';
  3212. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  3213. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  3214. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  3215. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  3216. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  3217. class ModelNode extends Object3DNode {
  3218. static get type() {
  3219. return 'ModelNode';
  3220. }
  3221. constructor( scope ) {
  3222. super( scope );
  3223. }
  3224. update( frame ) {
  3225. this.object3d = frame.object;
  3226. super.update( frame );
  3227. }
  3228. }
  3229. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  3230. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  3231. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  3232. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  3233. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  3234. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  3235. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  3236. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  3237. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3238. builder.context.isHighPrecisionModelViewMatrix = true;
  3239. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  3240. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3241. } );
  3242. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  3243. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3244. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  3245. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  3246. if ( isHighPrecisionModelViewMatrix !== true ) {
  3247. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3248. }
  3249. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  3250. } );
  3251. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  3252. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  3253. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  3254. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  3255. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  3256. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  3257. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  3258. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  3259. class FrontFacingNode extends Node {
  3260. static get type() {
  3261. return 'FrontFacingNode';
  3262. }
  3263. constructor() {
  3264. super( 'bool' );
  3265. this.isFrontFacingNode = true;
  3266. }
  3267. generate( builder ) {
  3268. const { renderer, material } = builder;
  3269. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  3270. if ( material.side === BackSide ) {
  3271. return 'false';
  3272. }
  3273. }
  3274. return builder.getFrontFacing();
  3275. }
  3276. }
  3277. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  3278. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  3279. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  3280. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  3281. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  3282. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  3283. return vec3( 0, 1, 0 );
  3284. }
  3285. return normalGeometry;
  3286. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  3287. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  3288. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3289. let node;
  3290. if ( builder.material.flatShading === true ) {
  3291. node = normalFlat;
  3292. } else {
  3293. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  3294. }
  3295. return node;
  3296. }, 'vec3' ).once() )().toVar( 'normalView' );
  3297. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  3298. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3299. return builder.context.setupNormal();
  3300. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  3301. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  3302. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3303. return builder.context.setupClearcoatNormal();
  3304. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  3305. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  3306. const m = mat3( matrix );
  3307. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  3308. return m.mul( transformedNormal ).xyz;
  3309. } );
  3310. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  3311. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  3312. if ( modelNormalViewMatrix !== null ) {
  3313. return modelNormalViewMatrix.transformDirection( normal );
  3314. }
  3315. //
  3316. const transformedNormal = modelNormalMatrix.mul( normal );
  3317. return cameraViewMatrix.transformDirection( transformedNormal );
  3318. } );
  3319. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  3320. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  3321. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  3322. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3323. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3324. class CubeTextureNode extends TextureNode {
  3325. static get type() {
  3326. return 'CubeTextureNode';
  3327. }
  3328. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3329. super( value, uvNode, levelNode, biasNode );
  3330. this.isCubeTextureNode = true;
  3331. }
  3332. getInputType( /*builder*/ ) {
  3333. return 'cubeTexture';
  3334. }
  3335. getDefaultUV() {
  3336. const texture = this.value;
  3337. if ( texture.mapping === CubeReflectionMapping ) {
  3338. return reflectVector;
  3339. } else if ( texture.mapping === CubeRefractionMapping ) {
  3340. return refractVector;
  3341. } else {
  3342. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  3343. return vec3( 0, 0, 0 );
  3344. }
  3345. }
  3346. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  3347. setupUV( builder, uvNode ) {
  3348. const texture = this.value;
  3349. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  3350. return vec3( uvNode.x.negate(), uvNode.yz );
  3351. } else {
  3352. return uvNode;
  3353. }
  3354. }
  3355. generateUV( builder, cubeUV ) {
  3356. return cubeUV.build( builder, 'vec3' );
  3357. }
  3358. }
  3359. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  3360. class BufferNode extends UniformNode {
  3361. static get type() {
  3362. return 'BufferNode';
  3363. }
  3364. constructor( value, bufferType, bufferCount = 0 ) {
  3365. super( value, bufferType );
  3366. this.isBufferNode = true;
  3367. this.bufferType = bufferType;
  3368. this.bufferCount = bufferCount;
  3369. }
  3370. getElementType( builder ) {
  3371. return this.getNodeType( builder );
  3372. }
  3373. getInputType( /*builder*/ ) {
  3374. return 'buffer';
  3375. }
  3376. }
  3377. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  3378. class UniformArrayElementNode extends ArrayElementNode {
  3379. static get type() {
  3380. return 'UniformArrayElementNode';
  3381. }
  3382. constructor( arrayBuffer, indexNode ) {
  3383. super( arrayBuffer, indexNode );
  3384. this.isArrayBufferElementNode = true;
  3385. }
  3386. generate( builder ) {
  3387. const snippet = super.generate( builder );
  3388. const type = this.getNodeType();
  3389. return builder.format( snippet, 'vec4', type );
  3390. }
  3391. }
  3392. class UniformArrayNode extends BufferNode {
  3393. static get type() {
  3394. return 'UniformArrayNode';
  3395. }
  3396. constructor( value, elementType = null ) {
  3397. super( null, 'vec4' );
  3398. this.array = value;
  3399. this.elementType = elementType;
  3400. this._elementType = null;
  3401. this._elementLength = 0;
  3402. this.updateType = NodeUpdateType.RENDER;
  3403. this.isArrayBufferNode = true;
  3404. }
  3405. getElementType() {
  3406. return this.elementType || this._elementType;
  3407. }
  3408. getElementLength() {
  3409. return this._elementLength;
  3410. }
  3411. update( /*frame*/ ) {
  3412. const { array, value } = this;
  3413. const elementLength = this.getElementLength();
  3414. const elementType = this.getElementType();
  3415. if ( elementLength === 1 ) {
  3416. for ( let i = 0; i < array.length; i ++ ) {
  3417. const index = i * 4;
  3418. value[ index ] = array[ i ];
  3419. }
  3420. } else if ( elementType === 'color' ) {
  3421. for ( let i = 0; i < array.length; i ++ ) {
  3422. const index = i * 4;
  3423. const vector = array[ i ];
  3424. value[ index ] = vector.r;
  3425. value[ index + 1 ] = vector.g;
  3426. value[ index + 2 ] = vector.b || 0;
  3427. //value[ index + 3 ] = vector.a || 0;
  3428. }
  3429. } else {
  3430. for ( let i = 0; i < array.length; i ++ ) {
  3431. const index = i * 4;
  3432. const vector = array[ i ];
  3433. value[ index ] = vector.x;
  3434. value[ index + 1 ] = vector.y;
  3435. value[ index + 2 ] = vector.z || 0;
  3436. value[ index + 3 ] = vector.w || 0;
  3437. }
  3438. }
  3439. }
  3440. setup( builder ) {
  3441. const length = this.array.length;
  3442. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  3443. this._elementLength = builder.getTypeLength( this._elementType );
  3444. let arrayType = Float32Array;
  3445. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  3446. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  3447. this.value = new arrayType( length * 4 );
  3448. this.bufferCount = length;
  3449. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  3450. return super.setup( builder );
  3451. }
  3452. element( indexNode ) {
  3453. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  3454. }
  3455. }
  3456. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  3457. //
  3458. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  3459. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  3460. return nodeObject( new UniformArrayNode( values, nodeType ) );
  3461. };
  3462. class ReferenceElementNode extends ArrayElementNode {
  3463. static get type() {
  3464. return 'ReferenceElementNode';
  3465. }
  3466. constructor( referenceNode, indexNode ) {
  3467. super( referenceNode, indexNode );
  3468. this.referenceNode = referenceNode;
  3469. this.isReferenceElementNode = true;
  3470. }
  3471. getNodeType() {
  3472. return this.referenceNode.uniformType;
  3473. }
  3474. generate( builder ) {
  3475. const snippet = super.generate( builder );
  3476. const arrayType = this.referenceNode.getNodeType();
  3477. const elementType = this.getNodeType();
  3478. return builder.format( snippet, arrayType, elementType );
  3479. }
  3480. }
  3481. // TODO: Extends this from ReferenceBaseNode
  3482. class ReferenceNode extends Node {
  3483. static get type() {
  3484. return 'ReferenceNode';
  3485. }
  3486. constructor( property, uniformType, object = null, count = null ) {
  3487. super();
  3488. this.property = property;
  3489. this.uniformType = uniformType;
  3490. this.object = object;
  3491. this.count = count;
  3492. this.properties = property.split( '.' );
  3493. this.reference = object;
  3494. this.node = null;
  3495. this.group = null;
  3496. this.name = null;
  3497. this.updateType = NodeUpdateType.OBJECT;
  3498. }
  3499. element( indexNode ) {
  3500. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  3501. }
  3502. setGroup( group ) {
  3503. this.group = group;
  3504. return this;
  3505. }
  3506. label( name ) {
  3507. this.name = name;
  3508. return this;
  3509. }
  3510. setNodeType( uniformType ) {
  3511. let node = null;
  3512. if ( this.count !== null ) {
  3513. node = buffer( null, uniformType, this.count );
  3514. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  3515. node = uniformArray( null, uniformType );
  3516. } else if ( uniformType === 'texture' ) {
  3517. node = texture( null );
  3518. } else if ( uniformType === 'cubeTexture' ) {
  3519. node = cubeTexture( null );
  3520. } else {
  3521. node = uniform( null, uniformType );
  3522. }
  3523. if ( this.group !== null ) {
  3524. node.setGroup( this.group );
  3525. }
  3526. if ( this.name !== null ) node.label( this.name );
  3527. this.node = node.getSelf();
  3528. }
  3529. getNodeType( builder ) {
  3530. if ( this.node === null ) {
  3531. this.updateReference( builder );
  3532. this.updateValue();
  3533. }
  3534. return this.node.getNodeType( builder );
  3535. }
  3536. getValueFromReference( object = this.reference ) {
  3537. const { properties } = this;
  3538. let value = object[ properties[ 0 ] ];
  3539. for ( let i = 1; i < properties.length; i ++ ) {
  3540. value = value[ properties[ i ] ];
  3541. }
  3542. return value;
  3543. }
  3544. updateReference( state ) {
  3545. this.reference = this.object !== null ? this.object : state.object;
  3546. return this.reference;
  3547. }
  3548. setup() {
  3549. this.updateValue();
  3550. return this.node;
  3551. }
  3552. update( /*frame*/ ) {
  3553. this.updateValue();
  3554. }
  3555. updateValue() {
  3556. if ( this.node === null ) this.setNodeType( this.uniformType );
  3557. const value = this.getValueFromReference();
  3558. if ( Array.isArray( value ) ) {
  3559. this.node.array = value;
  3560. } else {
  3561. this.node.value = value;
  3562. }
  3563. }
  3564. }
  3565. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  3566. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  3567. class MaterialReferenceNode extends ReferenceNode {
  3568. static get type() {
  3569. return 'MaterialReferenceNode';
  3570. }
  3571. constructor( property, inputType, material = null ) {
  3572. super( property, inputType, material );
  3573. this.material = material;
  3574. //this.updateType = NodeUpdateType.RENDER;
  3575. this.isMaterialReferenceNode = true;
  3576. }
  3577. /*setNodeType( node ) {
  3578. super.setNodeType( node );
  3579. this.node.groupNode = renderGroup;
  3580. }*/
  3581. updateReference( state ) {
  3582. this.reference = this.material !== null ? this.material : state.material;
  3583. return this.reference;
  3584. }
  3585. }
  3586. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  3587. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  3588. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  3589. builder.geometry.computeTangents();
  3590. }
  3591. return attribute( 'tangent', 'vec4' );
  3592. } )();
  3593. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  3594. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  3595. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  3596. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  3597. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  3598. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  3599. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  3600. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  3601. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  3602. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  3603. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  3604. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  3605. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  3606. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  3607. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  3608. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  3609. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  3610. let bentNormal = anisotropyB.cross( positionViewDirection );
  3611. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  3612. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  3613. return bentNormal;
  3614. } )();
  3615. // Normal Mapping Without Precomputed Tangents
  3616. // http://www.thetenthplanet.de/archives/1180
  3617. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  3618. const { eye_pos, surf_norm, mapN, uv } = inputs;
  3619. const q0 = eye_pos.dFdx();
  3620. const q1 = eye_pos.dFdy();
  3621. const st0 = uv.dFdx();
  3622. const st1 = uv.dFdy();
  3623. const N = surf_norm; // normalized
  3624. const q1perp = q1.cross( N );
  3625. const q0perp = N.cross( q0 );
  3626. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  3627. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  3628. const det = T.dot( T ).max( B.dot( B ) );
  3629. const scale = faceDirection.mul( det.inverseSqrt() );
  3630. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  3631. } );
  3632. class NormalMapNode extends TempNode {
  3633. static get type() {
  3634. return 'NormalMapNode';
  3635. }
  3636. constructor( node, scaleNode = null ) {
  3637. super( 'vec3' );
  3638. this.node = node;
  3639. this.scaleNode = scaleNode;
  3640. this.normalMapType = TangentSpaceNormalMap;
  3641. }
  3642. setup( builder ) {
  3643. const { normalMapType, scaleNode } = this;
  3644. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  3645. if ( scaleNode !== null ) {
  3646. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  3647. }
  3648. let outputNode = null;
  3649. if ( normalMapType === ObjectSpaceNormalMap ) {
  3650. outputNode = transformNormalToView( normalMap );
  3651. } else if ( normalMapType === TangentSpaceNormalMap ) {
  3652. const tangent = builder.hasGeometryAttribute( 'tangent' );
  3653. if ( tangent === true ) {
  3654. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  3655. } else {
  3656. outputNode = perturbNormal2Arb( {
  3657. eye_pos: positionView,
  3658. surf_norm: normalView,
  3659. mapN: normalMap,
  3660. uv: uv()
  3661. } );
  3662. }
  3663. }
  3664. return outputNode;
  3665. }
  3666. }
  3667. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  3668. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  3669. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  3670. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  3671. // It's used to preserve the same TextureNode instance
  3672. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  3673. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  3674. return vec2(
  3675. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  3676. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  3677. ).mul( bumpScale );
  3678. } );
  3679. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  3680. const perturbNormalArb = Fn( ( inputs ) => {
  3681. const { surf_pos, surf_norm, dHdxy } = inputs;
  3682. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  3683. const vSigmaX = surf_pos.dFdx().normalize();
  3684. const vSigmaY = surf_pos.dFdy().normalize();
  3685. const vN = surf_norm; // normalized
  3686. const R1 = vSigmaY.cross( vN );
  3687. const R2 = vN.cross( vSigmaX );
  3688. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  3689. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  3690. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  3691. } );
  3692. class BumpMapNode extends TempNode {
  3693. static get type() {
  3694. return 'BumpMapNode';
  3695. }
  3696. constructor( textureNode, scaleNode = null ) {
  3697. super( 'vec3' );
  3698. this.textureNode = textureNode;
  3699. this.scaleNode = scaleNode;
  3700. }
  3701. setup() {
  3702. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  3703. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  3704. return perturbNormalArb( {
  3705. surf_pos: positionView,
  3706. surf_norm: normalView,
  3707. dHdxy
  3708. } );
  3709. }
  3710. }
  3711. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  3712. const _propertyCache = new Map();
  3713. class MaterialNode extends Node {
  3714. static get type() {
  3715. return 'MaterialNode';
  3716. }
  3717. constructor( scope ) {
  3718. super();
  3719. this.scope = scope;
  3720. }
  3721. getCache( property, type ) {
  3722. let node = _propertyCache.get( property );
  3723. if ( node === undefined ) {
  3724. node = materialReference( property, type );
  3725. _propertyCache.set( property, node );
  3726. }
  3727. return node;
  3728. }
  3729. getFloat( property ) {
  3730. return this.getCache( property, 'float' );
  3731. }
  3732. getColor( property ) {
  3733. return this.getCache( property, 'color' );
  3734. }
  3735. getTexture( property ) {
  3736. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  3737. }
  3738. setup( builder ) {
  3739. const material = builder.context.material;
  3740. const scope = this.scope;
  3741. let node = null;
  3742. if ( scope === MaterialNode.COLOR ) {
  3743. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  3744. if ( material.map && material.map.isTexture === true ) {
  3745. node = colorNode.mul( this.getTexture( 'map' ) );
  3746. } else {
  3747. node = colorNode;
  3748. }
  3749. } else if ( scope === MaterialNode.OPACITY ) {
  3750. const opacityNode = this.getFloat( scope );
  3751. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  3752. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  3753. } else {
  3754. node = opacityNode;
  3755. }
  3756. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  3757. if ( material.specularMap && material.specularMap.isTexture === true ) {
  3758. node = this.getTexture( 'specular' ).r;
  3759. } else {
  3760. node = float( 1 );
  3761. }
  3762. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  3763. const specularIntensity = this.getFloat( scope );
  3764. if ( material.specularMap ) {
  3765. node = specularIntensity.mul( this.getTexture( scope ).a );
  3766. } else {
  3767. node = specularIntensity;
  3768. }
  3769. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  3770. const specularColorNode = this.getColor( scope );
  3771. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  3772. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  3773. } else {
  3774. node = specularColorNode;
  3775. }
  3776. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  3777. const roughnessNode = this.getFloat( scope );
  3778. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  3779. node = roughnessNode.mul( this.getTexture( scope ).g );
  3780. } else {
  3781. node = roughnessNode;
  3782. }
  3783. } else if ( scope === MaterialNode.METALNESS ) {
  3784. const metalnessNode = this.getFloat( scope );
  3785. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  3786. node = metalnessNode.mul( this.getTexture( scope ).b );
  3787. } else {
  3788. node = metalnessNode;
  3789. }
  3790. } else if ( scope === MaterialNode.EMISSIVE ) {
  3791. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  3792. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  3793. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  3794. node = emissiveNode.mul( this.getTexture( scope ) );
  3795. } else {
  3796. node = emissiveNode;
  3797. }
  3798. } else if ( scope === MaterialNode.NORMAL ) {
  3799. if ( material.normalMap ) {
  3800. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  3801. node.normalMapType = material.normalMapType;
  3802. } else if ( material.bumpMap ) {
  3803. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  3804. } else {
  3805. node = normalView;
  3806. }
  3807. } else if ( scope === MaterialNode.CLEARCOAT ) {
  3808. const clearcoatNode = this.getFloat( scope );
  3809. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  3810. node = clearcoatNode.mul( this.getTexture( scope ).r );
  3811. } else {
  3812. node = clearcoatNode;
  3813. }
  3814. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  3815. const clearcoatRoughnessNode = this.getFloat( scope );
  3816. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  3817. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  3818. } else {
  3819. node = clearcoatRoughnessNode;
  3820. }
  3821. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  3822. if ( material.clearcoatNormalMap ) {
  3823. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  3824. } else {
  3825. node = normalView;
  3826. }
  3827. } else if ( scope === MaterialNode.SHEEN ) {
  3828. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  3829. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  3830. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  3831. } else {
  3832. node = sheenNode;
  3833. }
  3834. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  3835. const sheenRoughnessNode = this.getFloat( scope );
  3836. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  3837. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  3838. } else {
  3839. node = sheenRoughnessNode;
  3840. }
  3841. node = node.clamp( 0.07, 1.0 );
  3842. } else if ( scope === MaterialNode.ANISOTROPY ) {
  3843. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  3844. const anisotropyPolar = this.getTexture( scope );
  3845. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  3846. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  3847. } else {
  3848. node = materialAnisotropyVector;
  3849. }
  3850. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  3851. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  3852. if ( material.iridescenceThicknessMap ) {
  3853. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  3854. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  3855. } else {
  3856. node = iridescenceThicknessMaximum;
  3857. }
  3858. } else if ( scope === MaterialNode.TRANSMISSION ) {
  3859. const transmissionNode = this.getFloat( scope );
  3860. if ( material.transmissionMap ) {
  3861. node = transmissionNode.mul( this.getTexture( scope ).r );
  3862. } else {
  3863. node = transmissionNode;
  3864. }
  3865. } else if ( scope === MaterialNode.THICKNESS ) {
  3866. const thicknessNode = this.getFloat( scope );
  3867. if ( material.thicknessMap ) {
  3868. node = thicknessNode.mul( this.getTexture( scope ).g );
  3869. } else {
  3870. node = thicknessNode;
  3871. }
  3872. } else if ( scope === MaterialNode.IOR ) {
  3873. node = this.getFloat( scope );
  3874. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  3875. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  3876. } else if ( scope === MaterialNode.AO_MAP ) {
  3877. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  3878. } else {
  3879. const outputType = this.getNodeType( builder );
  3880. node = this.getCache( scope, outputType );
  3881. }
  3882. return node;
  3883. }
  3884. }
  3885. MaterialNode.ALPHA_TEST = 'alphaTest';
  3886. MaterialNode.COLOR = 'color';
  3887. MaterialNode.OPACITY = 'opacity';
  3888. MaterialNode.SHININESS = 'shininess';
  3889. MaterialNode.SPECULAR = 'specular';
  3890. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  3891. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  3892. MaterialNode.SPECULAR_COLOR = 'specularColor';
  3893. MaterialNode.REFLECTIVITY = 'reflectivity';
  3894. MaterialNode.ROUGHNESS = 'roughness';
  3895. MaterialNode.METALNESS = 'metalness';
  3896. MaterialNode.NORMAL = 'normal';
  3897. MaterialNode.CLEARCOAT = 'clearcoat';
  3898. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  3899. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  3900. MaterialNode.EMISSIVE = 'emissive';
  3901. MaterialNode.ROTATION = 'rotation';
  3902. MaterialNode.SHEEN = 'sheen';
  3903. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  3904. MaterialNode.ANISOTROPY = 'anisotropy';
  3905. MaterialNode.IRIDESCENCE = 'iridescence';
  3906. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  3907. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  3908. MaterialNode.IOR = 'ior';
  3909. MaterialNode.TRANSMISSION = 'transmission';
  3910. MaterialNode.THICKNESS = 'thickness';
  3911. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  3912. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  3913. MaterialNode.LINE_SCALE = 'scale';
  3914. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  3915. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  3916. MaterialNode.LINE_WIDTH = 'linewidth';
  3917. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  3918. MaterialNode.POINT_WIDTH = 'pointWidth';
  3919. MaterialNode.DISPERSION = 'dispersion';
  3920. MaterialNode.LIGHT_MAP = 'light';
  3921. MaterialNode.AO_MAP = 'ao';
  3922. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  3923. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  3924. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  3925. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  3926. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  3927. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  3928. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  3929. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  3930. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  3931. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  3932. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  3933. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  3934. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  3935. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  3936. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  3937. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  3938. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  3939. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  3940. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  3941. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  3942. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  3943. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  3944. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  3945. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  3946. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  3947. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  3948. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  3949. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  3950. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  3951. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  3952. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  3953. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  3954. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  3955. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  3956. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  3957. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  3958. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  3959. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  3960. return frame.material;
  3961. } ).onRenderUpdate( function ( { material } ) {
  3962. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  3963. } );
  3964. class ModelViewProjectionNode extends TempNode {
  3965. static get type() {
  3966. return 'ModelViewProjectionNode';
  3967. }
  3968. constructor( positionNode = null ) {
  3969. super( 'vec4' );
  3970. this.positionNode = positionNode;
  3971. }
  3972. setup( builder ) {
  3973. if ( builder.shaderStage === 'fragment' ) {
  3974. return varying( builder.context.mvp );
  3975. }
  3976. const position = this.positionNode || positionLocal;
  3977. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  3978. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  3979. }
  3980. }
  3981. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  3982. class IndexNode extends Node {
  3983. static get type() {
  3984. return 'IndexNode';
  3985. }
  3986. constructor( scope ) {
  3987. super( 'uint' );
  3988. this.scope = scope;
  3989. this.isInstanceIndexNode = true;
  3990. }
  3991. generate( builder ) {
  3992. const nodeType = this.getNodeType( builder );
  3993. const scope = this.scope;
  3994. let propertyName;
  3995. if ( scope === IndexNode.VERTEX ) {
  3996. // The index of a vertex within a mesh.
  3997. propertyName = builder.getVertexIndex();
  3998. } else if ( scope === IndexNode.INSTANCE ) {
  3999. // The index of either a mesh instance or an invocation of a compute shader.
  4000. propertyName = builder.getInstanceIndex();
  4001. } else if ( scope === IndexNode.DRAW ) {
  4002. // The index of a draw call.
  4003. propertyName = builder.getDrawIndex();
  4004. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4005. // The index of a compute invocation within the scope of a workgroup load.
  4006. propertyName = builder.getInvocationLocalIndex();
  4007. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4008. // The index of a compute invocation within the scope of a subgroup.
  4009. propertyName = builder.getInvocationSubgroupIndex();
  4010. } else if ( scope === IndexNode.SUBGROUP ) {
  4011. // The index of the subgroup the current compute invocation belongs to.
  4012. propertyName = builder.getSubgroupIndex();
  4013. } else {
  4014. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4015. }
  4016. let output;
  4017. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4018. output = propertyName;
  4019. } else {
  4020. const nodeVarying = varying( this );
  4021. output = nodeVarying.build( builder, nodeType );
  4022. }
  4023. return output;
  4024. }
  4025. }
  4026. IndexNode.VERTEX = 'vertex';
  4027. IndexNode.INSTANCE = 'instance';
  4028. IndexNode.SUBGROUP = 'subgroup';
  4029. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4030. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  4031. IndexNode.DRAW = 'draw';
  4032. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  4033. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  4034. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  4035. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  4036. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  4037. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  4038. class InstanceNode extends Node {
  4039. static get type() {
  4040. return 'InstanceNode';
  4041. }
  4042. constructor( count, instanceMatrix, instanceColor ) {
  4043. super( 'void' );
  4044. this.count = count;
  4045. this.instanceMatrix = instanceMatrix;
  4046. this.instanceColor = instanceColor;
  4047. this.instanceMatrixNode = null;
  4048. this.instanceColorNode = null;
  4049. this.updateType = NodeUpdateType.FRAME;
  4050. this.buffer = null;
  4051. this.bufferColor = null;
  4052. }
  4053. setup( builder ) {
  4054. const { count, instanceMatrix, instanceColor } = this;
  4055. let { instanceMatrixNode, instanceColorNode } = this;
  4056. if ( instanceMatrixNode === null ) {
  4057. // 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.
  4058. if ( count <= 1000 ) {
  4059. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  4060. } else {
  4061. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  4062. this.buffer = buffer;
  4063. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4064. const instanceBuffers = [
  4065. // F.Signature -> bufferAttribute( array, type, stride, offset )
  4066. bufferFn( buffer, 'vec4', 16, 0 ),
  4067. bufferFn( buffer, 'vec4', 16, 4 ),
  4068. bufferFn( buffer, 'vec4', 16, 8 ),
  4069. bufferFn( buffer, 'vec4', 16, 12 )
  4070. ];
  4071. instanceMatrixNode = mat4( ...instanceBuffers );
  4072. }
  4073. this.instanceMatrixNode = instanceMatrixNode;
  4074. }
  4075. if ( instanceColor && instanceColorNode === null ) {
  4076. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  4077. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4078. this.bufferColor = buffer;
  4079. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  4080. this.instanceColorNode = instanceColorNode;
  4081. }
  4082. // POSITION
  4083. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  4084. positionLocal.assign( instancePosition );
  4085. // NORMAL
  4086. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4087. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  4088. // ASSIGNS
  4089. normalLocal.assign( instanceNormal );
  4090. }
  4091. // COLOR
  4092. if ( this.instanceColorNode !== null ) {
  4093. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  4094. }
  4095. }
  4096. update( /*frame*/ ) {
  4097. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  4098. this.buffer.version = this.instanceMatrix.version;
  4099. }
  4100. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  4101. this.bufferColor.version = this.instanceColor.version;
  4102. }
  4103. }
  4104. }
  4105. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  4106. class InstancedMeshNode extends InstanceNode {
  4107. static get type() {
  4108. return 'InstancedMeshNode';
  4109. }
  4110. constructor( instanceMesh ) {
  4111. const { count, instanceMatrix, instanceColor } = instanceMesh;
  4112. super( count, instanceMatrix, instanceColor );
  4113. this.instanceMesh = instanceMesh;
  4114. }
  4115. }
  4116. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  4117. class BatchNode extends Node {
  4118. static get type() {
  4119. return 'BatchNode';
  4120. }
  4121. constructor( batchMesh ) {
  4122. super( 'void' );
  4123. this.batchMesh = batchMesh;
  4124. this.batchingIdNode = null;
  4125. }
  4126. setup( builder ) {
  4127. // POSITION
  4128. if ( this.batchingIdNode === null ) {
  4129. if ( builder.getDrawIndex() === null ) {
  4130. this.batchingIdNode = instanceIndex;
  4131. } else {
  4132. this.batchingIdNode = drawIndex;
  4133. }
  4134. }
  4135. const getIndirectIndex = Fn( ( [ id ] ) => {
  4136. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  4137. const x = int( id ).modInt( int( size ) );
  4138. const y = int( id ).div( int( size ) );
  4139. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  4140. } ).setLayout( {
  4141. name: 'getIndirectIndex',
  4142. type: 'uint',
  4143. inputs: [
  4144. { name: 'id', type: 'int' }
  4145. ]
  4146. } );
  4147. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  4148. const matricesTexture = this.batchMesh._matricesTexture;
  4149. const size = textureSize( textureLoad( matricesTexture ), 0 );
  4150. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  4151. const x = j.modInt( size );
  4152. const y = j.div( int( size ) );
  4153. const batchingMatrix = mat4(
  4154. textureLoad( matricesTexture, ivec2( x, y ) ),
  4155. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  4156. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  4157. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  4158. );
  4159. const colorsTexture = this.batchMesh._colorsTexture;
  4160. if ( colorsTexture !== null ) {
  4161. const getBatchingColor = Fn( ( [ id ] ) => {
  4162. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  4163. const j = id;
  4164. const x = j.modInt( size );
  4165. const y = j.div( size );
  4166. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  4167. } ).setLayout( {
  4168. name: 'getBatchingColor',
  4169. type: 'vec3',
  4170. inputs: [
  4171. { name: 'id', type: 'int' }
  4172. ]
  4173. } );
  4174. const color = getBatchingColor( indirectId );
  4175. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  4176. }
  4177. const bm = mat3( batchingMatrix );
  4178. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  4179. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  4180. const batchingNormal = bm.mul( transformedNormal ).xyz;
  4181. normalLocal.assign( batchingNormal );
  4182. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4183. tangentLocal.mulAssign( bm );
  4184. }
  4185. }
  4186. }
  4187. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  4188. const _frameId = new WeakMap();
  4189. class SkinningNode extends Node {
  4190. static get type() {
  4191. return 'SkinningNode';
  4192. }
  4193. constructor( skinnedMesh, useReference = false ) {
  4194. super( 'void' );
  4195. this.skinnedMesh = skinnedMesh;
  4196. this.useReference = useReference;
  4197. this.updateType = NodeUpdateType.OBJECT;
  4198. //
  4199. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  4200. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  4201. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  4202. if ( useReference ) {
  4203. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  4204. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  4205. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4206. } else {
  4207. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  4208. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  4209. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  4210. }
  4211. this.bindMatrixNode = bindMatrixNode;
  4212. this.bindMatrixInverseNode = bindMatrixInverseNode;
  4213. this.boneMatricesNode = boneMatricesNode;
  4214. this.previousBoneMatricesNode = null;
  4215. }
  4216. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  4217. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4218. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4219. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4220. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4221. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4222. // POSITION
  4223. const skinVertex = bindMatrixNode.mul( position );
  4224. const skinned = add(
  4225. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  4226. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  4227. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  4228. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  4229. );
  4230. return bindMatrixInverseNode.mul( skinned ).xyz;
  4231. }
  4232. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  4233. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4234. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4235. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4236. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4237. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4238. // NORMAL
  4239. let skinMatrix = add(
  4240. skinWeightNode.x.mul( boneMatX ),
  4241. skinWeightNode.y.mul( boneMatY ),
  4242. skinWeightNode.z.mul( boneMatZ ),
  4243. skinWeightNode.w.mul( boneMatW )
  4244. );
  4245. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  4246. return skinMatrix.transformDirection( normal ).xyz;
  4247. }
  4248. getPreviousSkinnedPosition( builder ) {
  4249. const skinnedMesh = builder.object;
  4250. if ( this.previousBoneMatricesNode === null ) {
  4251. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  4252. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4253. }
  4254. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  4255. }
  4256. needsPreviousBoneMatrices( builder ) {
  4257. const mrt = builder.renderer.getMRT();
  4258. return mrt && mrt.has( 'velocity' );
  4259. }
  4260. setup( builder ) {
  4261. if ( this.needsPreviousBoneMatrices( builder ) ) {
  4262. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  4263. }
  4264. const skinPosition = this.getSkinnedPosition();
  4265. positionLocal.assign( skinPosition );
  4266. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4267. const skinNormal = this.getSkinnedNormal();
  4268. normalLocal.assign( skinNormal );
  4269. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4270. tangentLocal.assign( skinNormal );
  4271. }
  4272. }
  4273. }
  4274. generate( builder, output ) {
  4275. if ( output !== 'void' ) {
  4276. return positionLocal.build( builder, output );
  4277. }
  4278. }
  4279. update( frame ) {
  4280. const object = this.useReference ? frame.object : this.skinnedMesh;
  4281. const skeleton = object.skeleton;
  4282. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  4283. _frameId.set( skeleton, frame.frameId );
  4284. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  4285. skeleton.update();
  4286. }
  4287. }
  4288. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  4289. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  4290. class LoopNode extends Node {
  4291. static get type() {
  4292. return 'LoopNode';
  4293. }
  4294. constructor( params = [] ) {
  4295. super();
  4296. this.params = params;
  4297. }
  4298. getVarName( index ) {
  4299. return String.fromCharCode( 'i'.charCodeAt() + index );
  4300. }
  4301. getProperties( builder ) {
  4302. const properties = builder.getNodeProperties( this );
  4303. if ( properties.stackNode !== undefined ) return properties;
  4304. //
  4305. const inputs = {};
  4306. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4307. const param = this.params[ i ];
  4308. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  4309. const type = ( param.isNode !== true && param.type ) || 'int';
  4310. inputs[ name ] = expression( name, type );
  4311. }
  4312. const stack = builder.addStack(); // TODO: cache() it
  4313. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  4314. properties.stackNode = stack;
  4315. builder.removeStack();
  4316. return properties;
  4317. }
  4318. getNodeType( builder ) {
  4319. const { returnsNode } = this.getProperties( builder );
  4320. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  4321. }
  4322. setup( builder ) {
  4323. // setup properties
  4324. this.getProperties( builder );
  4325. }
  4326. generate( builder ) {
  4327. const properties = this.getProperties( builder );
  4328. const params = this.params;
  4329. const stackNode = properties.stackNode;
  4330. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  4331. const param = params[ i ];
  4332. let start = null, end = null, name = null, type = null, condition = null, update = null;
  4333. if ( param.isNode ) {
  4334. type = 'int';
  4335. name = this.getVarName( i );
  4336. start = '0';
  4337. end = param.build( builder, type );
  4338. condition = '<';
  4339. } else {
  4340. type = param.type || 'int';
  4341. name = param.name || this.getVarName( i );
  4342. start = param.start;
  4343. end = param.end;
  4344. condition = param.condition;
  4345. update = param.update;
  4346. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  4347. else if ( start && start.isNode ) start = start.build( builder, type );
  4348. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  4349. else if ( end && end.isNode ) end = end.build( builder, type );
  4350. if ( start !== undefined && end === undefined ) {
  4351. start = start + ' - 1';
  4352. end = '0';
  4353. condition = '>=';
  4354. } else if ( end !== undefined && start === undefined ) {
  4355. start = '0';
  4356. condition = '<';
  4357. }
  4358. if ( condition === undefined ) {
  4359. if ( Number( start ) > Number( end ) ) {
  4360. condition = '>=';
  4361. } else {
  4362. condition = '<';
  4363. }
  4364. }
  4365. }
  4366. const internalParam = { start, end, condition };
  4367. //
  4368. const startSnippet = internalParam.start;
  4369. const endSnippet = internalParam.end;
  4370. let declarationSnippet = '';
  4371. let conditionalSnippet = '';
  4372. let updateSnippet = '';
  4373. if ( ! update ) {
  4374. if ( type === 'int' || type === 'uint' ) {
  4375. if ( condition.includes( '<' ) ) update = '++';
  4376. else update = '--';
  4377. } else {
  4378. if ( condition.includes( '<' ) ) update = '+= 1.';
  4379. else update = '-= 1.';
  4380. }
  4381. }
  4382. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  4383. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  4384. updateSnippet += name + ' ' + update;
  4385. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  4386. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  4387. }
  4388. const stackSnippet = stackNode.build( builder, 'void' );
  4389. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  4390. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  4391. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4392. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  4393. }
  4394. builder.addFlowTab();
  4395. return returnsSnippet;
  4396. }
  4397. }
  4398. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  4399. const Continue = () => expression( 'continue' ).append();
  4400. const Break = () => expression( 'break' ).append();
  4401. //
  4402. const loop = ( ...params ) => { // @deprecated, r168
  4403. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  4404. return Loop( ...params );
  4405. };
  4406. const _morphTextures = /*@__PURE__*/ new WeakMap();
  4407. const _morphVec4 = /*@__PURE__*/ new Vector4();
  4408. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  4409. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  4410. const y = texelIndex.div( width );
  4411. const x = texelIndex.sub( y.mul( width ) );
  4412. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  4413. return bufferAttrib.mul( influence );
  4414. } );
  4415. function getEntry( geometry ) {
  4416. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4417. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  4418. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  4419. // instead of using attributes, the WebGL 2 code path encodes morph targets
  4420. // into an array of data textures. Each layer represents a single morph target.
  4421. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4422. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4423. let entry = _morphTextures.get( geometry );
  4424. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  4425. if ( entry !== undefined ) entry.texture.dispose();
  4426. const morphTargets = geometry.morphAttributes.position || [];
  4427. const morphNormals = geometry.morphAttributes.normal || [];
  4428. const morphColors = geometry.morphAttributes.color || [];
  4429. let vertexDataCount = 0;
  4430. if ( hasMorphPosition === true ) vertexDataCount = 1;
  4431. if ( hasMorphNormals === true ) vertexDataCount = 2;
  4432. if ( hasMorphColors === true ) vertexDataCount = 3;
  4433. let width = geometry.attributes.position.count * vertexDataCount;
  4434. let height = 1;
  4435. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  4436. if ( width > maxTextureSize ) {
  4437. height = Math.ceil( width / maxTextureSize );
  4438. width = maxTextureSize;
  4439. }
  4440. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  4441. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  4442. bufferTexture.type = FloatType;
  4443. bufferTexture.needsUpdate = true;
  4444. // fill buffer
  4445. const vertexDataStride = vertexDataCount * 4;
  4446. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  4447. const morphTarget = morphTargets[ i ];
  4448. const morphNormal = morphNormals[ i ];
  4449. const morphColor = morphColors[ i ];
  4450. const offset = width * height * 4 * i;
  4451. for ( let j = 0; j < morphTarget.count; j ++ ) {
  4452. const stride = j * vertexDataStride;
  4453. if ( hasMorphPosition === true ) {
  4454. _morphVec4.fromBufferAttribute( morphTarget, j );
  4455. buffer[ offset + stride + 0 ] = _morphVec4.x;
  4456. buffer[ offset + stride + 1 ] = _morphVec4.y;
  4457. buffer[ offset + stride + 2 ] = _morphVec4.z;
  4458. buffer[ offset + stride + 3 ] = 0;
  4459. }
  4460. if ( hasMorphNormals === true ) {
  4461. _morphVec4.fromBufferAttribute( morphNormal, j );
  4462. buffer[ offset + stride + 4 ] = _morphVec4.x;
  4463. buffer[ offset + stride + 5 ] = _morphVec4.y;
  4464. buffer[ offset + stride + 6 ] = _morphVec4.z;
  4465. buffer[ offset + stride + 7 ] = 0;
  4466. }
  4467. if ( hasMorphColors === true ) {
  4468. _morphVec4.fromBufferAttribute( morphColor, j );
  4469. buffer[ offset + stride + 8 ] = _morphVec4.x;
  4470. buffer[ offset + stride + 9 ] = _morphVec4.y;
  4471. buffer[ offset + stride + 10 ] = _morphVec4.z;
  4472. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  4473. }
  4474. }
  4475. }
  4476. entry = {
  4477. count: morphTargetsCount,
  4478. texture: bufferTexture,
  4479. stride: vertexDataCount,
  4480. size: new Vector2( width, height )
  4481. };
  4482. _morphTextures.set( geometry, entry );
  4483. function disposeTexture() {
  4484. bufferTexture.dispose();
  4485. _morphTextures.delete( geometry );
  4486. geometry.removeEventListener( 'dispose', disposeTexture );
  4487. }
  4488. geometry.addEventListener( 'dispose', disposeTexture );
  4489. }
  4490. return entry;
  4491. }
  4492. class MorphNode extends Node {
  4493. static get type() {
  4494. return 'MorphNode';
  4495. }
  4496. constructor( mesh ) {
  4497. super( 'void' );
  4498. this.mesh = mesh;
  4499. this.morphBaseInfluence = uniform( 1 );
  4500. this.updateType = NodeUpdateType.OBJECT;
  4501. }
  4502. setup( builder ) {
  4503. const { geometry } = builder;
  4504. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4505. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  4506. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4507. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4508. // nodes
  4509. const { texture: bufferMap, stride, size } = getEntry( geometry );
  4510. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  4511. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  4512. const width = int( size.width );
  4513. Loop( morphTargetsCount, ( { i } ) => {
  4514. const influence = float( 0 ).toVar();
  4515. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  4516. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  4517. } else {
  4518. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  4519. }
  4520. if ( hasMorphPosition === true ) {
  4521. positionLocal.addAssign( getMorph( {
  4522. bufferMap,
  4523. influence,
  4524. stride,
  4525. width,
  4526. depth: i,
  4527. offset: int( 0 )
  4528. } ) );
  4529. }
  4530. if ( hasMorphNormals === true ) {
  4531. normalLocal.addAssign( getMorph( {
  4532. bufferMap,
  4533. influence,
  4534. stride,
  4535. width,
  4536. depth: i,
  4537. offset: int( 1 )
  4538. } ) );
  4539. }
  4540. } );
  4541. }
  4542. update() {
  4543. const morphBaseInfluence = this.morphBaseInfluence;
  4544. if ( this.mesh.geometry.morphTargetsRelative ) {
  4545. morphBaseInfluence.value = 1;
  4546. } else {
  4547. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  4548. }
  4549. }
  4550. }
  4551. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  4552. class LightingNode extends Node {
  4553. static get type() {
  4554. return 'LightingNode';
  4555. }
  4556. constructor() {
  4557. super( 'vec3' );
  4558. this.isLightingNode = true;
  4559. }
  4560. generate( /*builder*/ ) {
  4561. console.warn( 'Abstract function.' );
  4562. }
  4563. }
  4564. class AONode extends LightingNode {
  4565. static get type() {
  4566. return 'AONode';
  4567. }
  4568. constructor( aoNode = null ) {
  4569. super();
  4570. this.aoNode = aoNode;
  4571. }
  4572. setup( builder ) {
  4573. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  4574. }
  4575. }
  4576. class LightingContextNode extends ContextNode {
  4577. static get type() {
  4578. return 'LightingContextNode';
  4579. }
  4580. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  4581. super( node );
  4582. this.lightingModel = lightingModel;
  4583. this.backdropNode = backdropNode;
  4584. this.backdropAlphaNode = backdropAlphaNode;
  4585. this._value = null;
  4586. }
  4587. getContext() {
  4588. const { backdropNode, backdropAlphaNode } = this;
  4589. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  4590. directSpecular = vec3().toVar( 'directSpecular' ),
  4591. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  4592. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  4593. const reflectedLight = {
  4594. directDiffuse,
  4595. directSpecular,
  4596. indirectDiffuse,
  4597. indirectSpecular
  4598. };
  4599. const context = {
  4600. radiance: vec3().toVar( 'radiance' ),
  4601. irradiance: vec3().toVar( 'irradiance' ),
  4602. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  4603. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  4604. reflectedLight,
  4605. backdrop: backdropNode,
  4606. backdropAlpha: backdropAlphaNode
  4607. };
  4608. return context;
  4609. }
  4610. setup( builder ) {
  4611. this.value = this._value || ( this._value = this.getContext() );
  4612. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  4613. return super.setup( builder );
  4614. }
  4615. }
  4616. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  4617. class IrradianceNode extends LightingNode {
  4618. static get type() {
  4619. return 'IrradianceNode';
  4620. }
  4621. constructor( node ) {
  4622. super();
  4623. this.node = node;
  4624. }
  4625. setup( builder ) {
  4626. builder.context.irradiance.addAssign( this.node );
  4627. }
  4628. }
  4629. let screenSizeVec, viewportVec;
  4630. class ScreenNode extends Node {
  4631. static get type() {
  4632. return 'ScreenNode';
  4633. }
  4634. constructor( scope ) {
  4635. super();
  4636. this.scope = scope;
  4637. this.isViewportNode = true;
  4638. }
  4639. getNodeType() {
  4640. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  4641. else return 'vec2';
  4642. }
  4643. getUpdateType() {
  4644. let updateType = NodeUpdateType.NONE;
  4645. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  4646. updateType = NodeUpdateType.RENDER;
  4647. }
  4648. this.updateType = updateType;
  4649. return updateType;
  4650. }
  4651. update( { renderer } ) {
  4652. const renderTarget = renderer.getRenderTarget();
  4653. if ( this.scope === ScreenNode.VIEWPORT ) {
  4654. if ( renderTarget !== null ) {
  4655. viewportVec.copy( renderTarget.viewport );
  4656. } else {
  4657. renderer.getViewport( viewportVec );
  4658. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  4659. }
  4660. } else {
  4661. if ( renderTarget !== null ) {
  4662. screenSizeVec.width = renderTarget.width;
  4663. screenSizeVec.height = renderTarget.height;
  4664. } else {
  4665. renderer.getDrawingBufferSize( screenSizeVec );
  4666. }
  4667. }
  4668. }
  4669. setup( /*builder*/ ) {
  4670. const scope = this.scope;
  4671. let output = null;
  4672. if ( scope === ScreenNode.SIZE ) {
  4673. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  4674. } else if ( scope === ScreenNode.VIEWPORT ) {
  4675. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  4676. } else {
  4677. output = vec2( screenCoordinate.div( screenSize ) );
  4678. }
  4679. return output;
  4680. }
  4681. generate( builder ) {
  4682. if ( this.scope === ScreenNode.COORDINATE ) {
  4683. let coord = builder.getFragCoord();
  4684. if ( builder.isFlipY() ) {
  4685. // follow webgpu standards
  4686. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  4687. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  4688. }
  4689. return coord;
  4690. }
  4691. return super.generate( builder );
  4692. }
  4693. }
  4694. ScreenNode.COORDINATE = 'coordinate';
  4695. ScreenNode.VIEWPORT = 'viewport';
  4696. ScreenNode.SIZE = 'size';
  4697. ScreenNode.UV = 'uv';
  4698. // Screen
  4699. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  4700. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  4701. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  4702. // Viewport
  4703. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  4704. const viewportSize = viewport.zw;
  4705. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  4706. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  4707. // Deprecated
  4708. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  4709. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  4710. return screenSize;
  4711. }, 'vec2' ).once() )();
  4712. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4713. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  4714. return screenUV;
  4715. }, 'vec2' ).once() )();
  4716. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4717. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  4718. return screenUV.flipY();
  4719. }, 'vec2' ).once() )();
  4720. const _size$4 = /*@__PURE__*/ new Vector2();
  4721. class ViewportTextureNode extends TextureNode {
  4722. static get type() {
  4723. return 'ViewportTextureNode';
  4724. }
  4725. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  4726. if ( framebufferTexture === null ) {
  4727. framebufferTexture = new FramebufferTexture();
  4728. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  4729. }
  4730. super( framebufferTexture, uvNode, levelNode );
  4731. this.generateMipmaps = false;
  4732. this.isOutputTextureNode = true;
  4733. this.updateBeforeType = NodeUpdateType.FRAME;
  4734. }
  4735. updateBefore( frame ) {
  4736. const renderer = frame.renderer;
  4737. renderer.getDrawingBufferSize( _size$4 );
  4738. //
  4739. const framebufferTexture = this.value;
  4740. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  4741. framebufferTexture.image.width = _size$4.width;
  4742. framebufferTexture.image.height = _size$4.height;
  4743. framebufferTexture.needsUpdate = true;
  4744. }
  4745. //
  4746. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  4747. framebufferTexture.generateMipmaps = this.generateMipmaps;
  4748. renderer.copyFramebufferToTexture( framebufferTexture );
  4749. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  4750. }
  4751. clone() {
  4752. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  4753. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  4754. return viewportTextureNode;
  4755. }
  4756. }
  4757. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  4758. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  4759. let sharedDepthbuffer = null;
  4760. class ViewportDepthTextureNode extends ViewportTextureNode {
  4761. static get type() {
  4762. return 'ViewportDepthTextureNode';
  4763. }
  4764. constructor( uvNode = screenUV, levelNode = null ) {
  4765. if ( sharedDepthbuffer === null ) {
  4766. sharedDepthbuffer = new DepthTexture();
  4767. }
  4768. super( uvNode, levelNode, sharedDepthbuffer );
  4769. }
  4770. }
  4771. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  4772. class ViewportDepthNode extends Node {
  4773. static get type() {
  4774. return 'ViewportDepthNode';
  4775. }
  4776. constructor( scope, valueNode = null ) {
  4777. super( 'float' );
  4778. this.scope = scope;
  4779. this.valueNode = valueNode;
  4780. this.isViewportDepthNode = true;
  4781. }
  4782. generate( builder ) {
  4783. const { scope } = this;
  4784. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4785. return builder.getFragDepth();
  4786. }
  4787. return super.generate( builder );
  4788. }
  4789. setup( { camera } ) {
  4790. const { scope } = this;
  4791. const value = this.valueNode;
  4792. let node = null;
  4793. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4794. if ( value !== null ) {
  4795. node = depthBase().assign( value );
  4796. }
  4797. } else if ( scope === ViewportDepthNode.DEPTH ) {
  4798. if ( camera.isPerspectiveCamera ) {
  4799. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  4800. } else {
  4801. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4802. }
  4803. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  4804. if ( value !== null ) {
  4805. if ( camera.isPerspectiveCamera ) {
  4806. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  4807. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  4808. } else {
  4809. node = value;
  4810. }
  4811. } else {
  4812. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4813. }
  4814. }
  4815. return node;
  4816. }
  4817. }
  4818. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  4819. ViewportDepthNode.DEPTH = 'depth';
  4820. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  4821. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  4822. // -near maps to 0; -far maps to 1
  4823. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  4824. // maps orthographic depth in [ 0, 1 ] to viewZ
  4825. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  4826. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  4827. // -near maps to 0; -far maps to 1
  4828. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  4829. // maps perspective depth in [ 0, 1 ] to viewZ
  4830. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  4831. // -near maps to 0; -far maps to 1
  4832. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  4833. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  4834. // The final logarithmic depth formula used here is adapted from one described in an
  4835. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  4836. // which was an improvement upon an earlier formula one described in an
  4837. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  4838. // Ulrich's formula is the following:
  4839. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  4840. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  4841. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  4842. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  4843. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  4844. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  4845. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  4846. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  4847. // be used, and ultimately Ulrich's "near plane" version was chosen.
  4848. // Outerra eventually made another improvement to their original "C-constant" variant,
  4849. // but it still does not incorporate the camera near plane (for this version,
  4850. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  4851. // Here we make 4 changes to Ulrich's formula:
  4852. // 1. Clamp the camera near plane so we don't divide by 0.
  4853. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  4854. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  4855. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  4856. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  4857. // so we do the same here, hence the 'viewZ.negate()' call.
  4858. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  4859. near = near.max( 1e-6 ).toVar();
  4860. const numerator = log2( viewZ.negate().div( near ) );
  4861. const denominator = log2( far.div( near ) );
  4862. return numerator.div( denominator );
  4863. };
  4864. // maps logarithmic depth in [ 0, 1 ] to viewZ
  4865. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  4866. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  4867. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  4868. // a negative viewZ).
  4869. const exponent = depth.mul( log( far.div( near ) ) );
  4870. return float( Math.E ).pow( exponent ).mul( near ).negate();
  4871. };
  4872. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  4873. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  4874. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  4875. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  4876. depth.assign = ( value ) => depthBase( value );
  4877. class BuiltinNode extends Node {
  4878. constructor( name ) {
  4879. super( 'float' );
  4880. this.name = name;
  4881. this.isBuiltinNode = true;
  4882. }
  4883. generate( /* builder */ ) {
  4884. return this.name;
  4885. }
  4886. }
  4887. const builtin = nodeProxy( BuiltinNode );
  4888. class ClippingNode extends Node {
  4889. static get type() {
  4890. return 'ClippingNode';
  4891. }
  4892. constructor( scope = ClippingNode.DEFAULT ) {
  4893. super();
  4894. this.scope = scope;
  4895. }
  4896. setup( builder ) {
  4897. super.setup( builder );
  4898. const clippingContext = builder.clippingContext;
  4899. const { intersectionPlanes, unionPlanes } = clippingContext;
  4900. this.hardwareClipping = builder.material.hardwareClipping;
  4901. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  4902. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  4903. } else if ( this.scope === ClippingNode.HARDWARE ) {
  4904. return this.setupHardwareClipping( unionPlanes, builder );
  4905. } else {
  4906. return this.setupDefault( intersectionPlanes, unionPlanes );
  4907. }
  4908. }
  4909. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  4910. return Fn( () => {
  4911. const distanceToPlane = float().toVar( 'distanceToPlane' );
  4912. const distanceGradient = float().toVar( 'distanceToGradient' );
  4913. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  4914. const numUnionPlanes = unionPlanes.length;
  4915. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4916. const clippingPlanes = uniformArray( unionPlanes );
  4917. Loop( numUnionPlanes, ( { i } ) => {
  4918. const plane = clippingPlanes.element( i );
  4919. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4920. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4921. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  4922. } );
  4923. }
  4924. const numIntersectionPlanes = intersectionPlanes.length;
  4925. if ( numIntersectionPlanes > 0 ) {
  4926. const clippingPlanes = uniformArray( intersectionPlanes );
  4927. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  4928. Loop( numIntersectionPlanes, ( { i } ) => {
  4929. const plane = clippingPlanes.element( i );
  4930. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4931. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4932. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  4933. } );
  4934. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  4935. }
  4936. diffuseColor.a.mulAssign( clipOpacity );
  4937. diffuseColor.a.equal( 0.0 ).discard();
  4938. } )();
  4939. }
  4940. setupDefault( intersectionPlanes, unionPlanes ) {
  4941. return Fn( () => {
  4942. const numUnionPlanes = unionPlanes.length;
  4943. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4944. const clippingPlanes = uniformArray( unionPlanes );
  4945. Loop( numUnionPlanes, ( { i } ) => {
  4946. const plane = clippingPlanes.element( i );
  4947. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  4948. } );
  4949. }
  4950. const numIntersectionPlanes = intersectionPlanes.length;
  4951. if ( numIntersectionPlanes > 0 ) {
  4952. const clippingPlanes = uniformArray( intersectionPlanes );
  4953. const clipped = bool( true ).toVar( 'clipped' );
  4954. Loop( numIntersectionPlanes, ( { i } ) => {
  4955. const plane = clippingPlanes.element( i );
  4956. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  4957. } );
  4958. clipped.discard();
  4959. }
  4960. } )();
  4961. }
  4962. setupHardwareClipping( unionPlanes, builder ) {
  4963. const numUnionPlanes = unionPlanes.length;
  4964. builder.enableHardwareClipping( numUnionPlanes );
  4965. return Fn( () => {
  4966. const clippingPlanes = uniformArray( unionPlanes );
  4967. const hw_clip_distances = builtin( builder.getClipDistance() );
  4968. Loop( numUnionPlanes, ( { i } ) => {
  4969. const plane = clippingPlanes.element( i );
  4970. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  4971. hw_clip_distances.element( i ).assign( distance );
  4972. } );
  4973. } )();
  4974. }
  4975. }
  4976. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  4977. ClippingNode.DEFAULT = 'default';
  4978. ClippingNode.HARDWARE = 'hardware';
  4979. const clipping = () => nodeObject( new ClippingNode() );
  4980. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  4981. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  4982. /**
  4983. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  4984. */
  4985. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  4986. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4987. 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 ) ) ) ) ) );
  4988. } );
  4989. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4990. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  4991. } );
  4992. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  4993. // Find the discretized derivatives of our coordinates
  4994. const maxDeriv = max$1(
  4995. length( dFdx( position.xyz ) ),
  4996. length( dFdy( position.xyz ) )
  4997. ).toVar( 'maxDeriv' );
  4998. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  4999. // Find two nearest log-discretized noise scales
  5000. const pixScales = vec2(
  5001. exp2( floor( log2( pixScale ) ) ),
  5002. exp2( ceil( log2( pixScale ) ) )
  5003. ).toVar( 'pixScales' );
  5004. // Compute alpha thresholds at our two noise scales
  5005. const alpha = vec2(
  5006. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5007. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5008. ).toVar( 'alpha' );
  5009. // Factor to interpolate lerp with
  5010. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  5011. // Interpolate alpha threshold from noise at two scales
  5012. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  5013. // Pass into CDF to compute uniformly distrib threshold
  5014. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  5015. const cases = vec3(
  5016. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5017. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5018. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  5019. // Find our final, uniformly distributed alpha threshold (ατ)
  5020. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5021. // Avoids ατ == 0. Could also do ατ =1-ατ
  5022. return clamp( threshold, 1.0e-6, 1.0 );
  5023. } );
  5024. class NodeMaterial extends Material {
  5025. static get type() {
  5026. return 'NodeMaterial';
  5027. }
  5028. get type() {
  5029. return this.constructor.type;
  5030. }
  5031. set type( _value ) { /* */ }
  5032. constructor() {
  5033. super();
  5034. this.isNodeMaterial = true;
  5035. this.forceSinglePass = false;
  5036. this.fog = true;
  5037. this.lights = false;
  5038. this.hardwareClipping = false;
  5039. this.lightsNode = null;
  5040. this.envNode = null;
  5041. this.aoNode = null;
  5042. this.colorNode = null;
  5043. this.normalNode = null;
  5044. this.opacityNode = null;
  5045. this.backdropNode = null;
  5046. this.backdropAlphaNode = null;
  5047. this.alphaTestNode = null;
  5048. this.positionNode = null;
  5049. this.geometryNode = null;
  5050. this.depthNode = null;
  5051. this.shadowPositionNode = null;
  5052. this.receivedShadowNode = null;
  5053. this.castShadowNode = null;
  5054. this.outputNode = null;
  5055. this.mrtNode = null;
  5056. this.fragmentNode = null;
  5057. this.vertexNode = null;
  5058. }
  5059. customProgramCacheKey() {
  5060. return this.type + getCacheKey$1( this );
  5061. }
  5062. build( builder ) {
  5063. this.setup( builder );
  5064. }
  5065. setupObserver( builder ) {
  5066. return new NodeMaterialObserver( builder );
  5067. }
  5068. setup( builder ) {
  5069. builder.context.setupNormal = () => this.setupNormal( builder );
  5070. const renderer = builder.renderer;
  5071. const renderTarget = renderer.getRenderTarget();
  5072. // < VERTEX STAGE >
  5073. builder.addStack();
  5074. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  5075. if ( this.geometryNode !== null ) {
  5076. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  5077. }
  5078. builder.addFlow( 'vertex', builder.removeStack() );
  5079. // < FRAGMENT STAGE >
  5080. builder.addStack();
  5081. let resultNode;
  5082. const clippingNode = this.setupClipping( builder );
  5083. if ( this.depthWrite === true ) {
  5084. // only write depth if depth buffer is configured
  5085. if ( renderTarget !== null ) {
  5086. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  5087. } else {
  5088. if ( renderer.depth === true ) this.setupDepth( builder );
  5089. }
  5090. }
  5091. if ( this.fragmentNode === null ) {
  5092. this.setupDiffuseColor( builder );
  5093. this.setupVariants( builder );
  5094. const outgoingLightNode = this.setupLighting( builder );
  5095. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  5096. // force unsigned floats - useful for RenderTargets
  5097. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  5098. resultNode = this.setupOutput( builder, basicOutput );
  5099. // OUTPUT NODE
  5100. output.assign( resultNode );
  5101. //
  5102. if ( this.outputNode !== null ) resultNode = this.outputNode;
  5103. // MRT
  5104. if ( renderTarget !== null ) {
  5105. const mrt = renderer.getMRT();
  5106. const materialMRT = this.mrtNode;
  5107. if ( mrt !== null ) {
  5108. resultNode = mrt;
  5109. if ( materialMRT !== null ) {
  5110. resultNode = mrt.merge( materialMRT );
  5111. }
  5112. } else if ( materialMRT !== null ) {
  5113. resultNode = materialMRT;
  5114. }
  5115. }
  5116. } else {
  5117. let fragmentNode = this.fragmentNode;
  5118. if ( fragmentNode.isOutputStructNode !== true ) {
  5119. fragmentNode = vec4( fragmentNode );
  5120. }
  5121. resultNode = this.setupOutput( builder, fragmentNode );
  5122. }
  5123. builder.stack.outputNode = resultNode;
  5124. builder.addFlow( 'fragment', builder.removeStack() );
  5125. // < MONITOR >
  5126. builder.monitor = this.setupObserver( builder );
  5127. }
  5128. setupClipping( builder ) {
  5129. if ( builder.clippingContext === null ) return null;
  5130. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  5131. let result = null;
  5132. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  5133. const samples = builder.renderer.samples;
  5134. if ( this.alphaToCoverage && samples > 1 ) {
  5135. // to be added to flow when the color/alpha value has been determined
  5136. result = clippingAlpha();
  5137. } else {
  5138. builder.stack.add( clipping() );
  5139. }
  5140. }
  5141. return result;
  5142. }
  5143. setupHardwareClipping( builder ) {
  5144. this.hardwareClipping = false;
  5145. if ( builder.clippingContext === null ) return;
  5146. const candidateCount = builder.clippingContext.unionPlanes.length;
  5147. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  5148. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  5149. builder.stack.add( hardwareClipping() );
  5150. this.hardwareClipping = true;
  5151. }
  5152. return;
  5153. }
  5154. setupDepth( builder ) {
  5155. const { renderer, camera } = builder;
  5156. // Depth
  5157. let depthNode = this.depthNode;
  5158. if ( depthNode === null ) {
  5159. const mrt = renderer.getMRT();
  5160. if ( mrt && mrt.has( 'depth' ) ) {
  5161. depthNode = mrt.get( 'depth' );
  5162. } else if ( renderer.logarithmicDepthBuffer === true ) {
  5163. if ( camera.isPerspectiveCamera ) {
  5164. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  5165. } else {
  5166. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5167. }
  5168. }
  5169. }
  5170. if ( depthNode !== null ) {
  5171. depth.assign( depthNode ).append();
  5172. }
  5173. }
  5174. setupPosition( builder ) {
  5175. const { object } = builder;
  5176. const geometry = object.geometry;
  5177. builder.addStack();
  5178. // Vertex
  5179. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  5180. morphReference( object ).append();
  5181. }
  5182. if ( object.isSkinnedMesh === true ) {
  5183. skinningReference( object ).append();
  5184. }
  5185. if ( this.displacementMap ) {
  5186. const displacementMap = materialReference( 'displacementMap', 'texture' );
  5187. const displacementScale = materialReference( 'displacementScale', 'float' );
  5188. const displacementBias = materialReference( 'displacementBias', 'float' );
  5189. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  5190. }
  5191. if ( object.isBatchedMesh ) {
  5192. batch( object ).append();
  5193. }
  5194. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  5195. instancedMesh( object ).append();
  5196. }
  5197. if ( this.positionNode !== null ) {
  5198. positionLocal.assign( this.positionNode );
  5199. }
  5200. this.setupHardwareClipping( builder );
  5201. const mvp = modelViewProjection();
  5202. builder.context.vertex = builder.removeStack();
  5203. builder.context.mvp = mvp;
  5204. return mvp;
  5205. }
  5206. setupDiffuseColor( { object, geometry } ) {
  5207. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  5208. // VERTEX COLORS
  5209. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  5210. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  5211. }
  5212. // Instanced colors
  5213. if ( object.instanceColor ) {
  5214. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  5215. colorNode = instanceColor.mul( colorNode );
  5216. }
  5217. if ( object.isBatchedMesh && object._colorsTexture ) {
  5218. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  5219. colorNode = batchColor.mul( colorNode );
  5220. }
  5221. // COLOR
  5222. diffuseColor.assign( colorNode );
  5223. // OPACITY
  5224. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5225. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  5226. // ALPHA TEST
  5227. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  5228. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  5229. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  5230. }
  5231. // ALPHA HASH
  5232. if ( this.alphaHash === true ) {
  5233. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  5234. }
  5235. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  5236. diffuseColor.a.assign( 1.0 );
  5237. }
  5238. }
  5239. setupVariants( /*builder*/ ) {
  5240. // Interface function.
  5241. }
  5242. setupOutgoingLight() {
  5243. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  5244. }
  5245. setupNormal() {
  5246. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  5247. }
  5248. setupEnvironment( /*builder*/ ) {
  5249. let node = null;
  5250. if ( this.envNode ) {
  5251. node = this.envNode;
  5252. } else if ( this.envMap ) {
  5253. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  5254. }
  5255. return node;
  5256. }
  5257. setupLightMap( builder ) {
  5258. let node = null;
  5259. if ( builder.material.lightMap ) {
  5260. node = new IrradianceNode( materialLightMap );
  5261. }
  5262. return node;
  5263. }
  5264. setupLights( builder ) {
  5265. const materialLightsNode = [];
  5266. //
  5267. const envNode = this.setupEnvironment( builder );
  5268. if ( envNode && envNode.isLightingNode ) {
  5269. materialLightsNode.push( envNode );
  5270. }
  5271. const lightMapNode = this.setupLightMap( builder );
  5272. if ( lightMapNode && lightMapNode.isLightingNode ) {
  5273. materialLightsNode.push( lightMapNode );
  5274. }
  5275. if ( this.aoNode !== null || builder.material.aoMap ) {
  5276. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  5277. materialLightsNode.push( new AONode( aoNode ) );
  5278. }
  5279. let lightsN = this.lightsNode || builder.lightsNode;
  5280. if ( materialLightsNode.length > 0 ) {
  5281. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  5282. }
  5283. return lightsN;
  5284. }
  5285. setupLightingModel( /*builder*/ ) {
  5286. // Interface function.
  5287. }
  5288. setupLighting( builder ) {
  5289. const { material } = builder;
  5290. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  5291. // OUTGOING LIGHT
  5292. const lights = this.lights === true || this.lightsNode !== null;
  5293. const lightsNode = lights ? this.setupLights( builder ) : null;
  5294. let outgoingLightNode = this.setupOutgoingLight( builder );
  5295. if ( lightsNode && lightsNode.getScope().hasLights ) {
  5296. const lightingModel = this.setupLightingModel( builder );
  5297. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  5298. } else if ( backdropNode !== null ) {
  5299. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  5300. }
  5301. // EMISSIVE
  5302. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  5303. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  5304. outgoingLightNode = outgoingLightNode.add( emissive );
  5305. }
  5306. return outgoingLightNode;
  5307. }
  5308. setupOutput( builder, outputNode ) {
  5309. // FOG
  5310. if ( this.fog === true ) {
  5311. const fogNode = builder.fogNode;
  5312. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  5313. }
  5314. return outputNode;
  5315. }
  5316. setDefaultValues( material ) {
  5317. // This approach is to reuse the native refreshUniforms*
  5318. // and turn available the use of features like transmission and environment in core
  5319. for ( const property in material ) {
  5320. const value = material[ property ];
  5321. if ( this[ property ] === undefined ) {
  5322. this[ property ] = value;
  5323. if ( value && value.clone ) this[ property ] = value.clone();
  5324. }
  5325. }
  5326. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  5327. for ( const key in descriptors ) {
  5328. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  5329. descriptors[ key ].get !== undefined ) {
  5330. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  5331. }
  5332. }
  5333. }
  5334. toJSON( meta ) {
  5335. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5336. if ( isRoot ) {
  5337. meta = {
  5338. textures: {},
  5339. images: {},
  5340. nodes: {}
  5341. };
  5342. }
  5343. const data = Material.prototype.toJSON.call( this, meta );
  5344. const nodeChildren = getNodeChildren( this );
  5345. data.inputNodes = {};
  5346. for ( const { property, childNode } of nodeChildren ) {
  5347. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  5348. }
  5349. // TODO: Copied from Object3D.toJSON
  5350. function extractFromCache( cache ) {
  5351. const values = [];
  5352. for ( const key in cache ) {
  5353. const data = cache[ key ];
  5354. delete data.metadata;
  5355. values.push( data );
  5356. }
  5357. return values;
  5358. }
  5359. if ( isRoot ) {
  5360. const textures = extractFromCache( meta.textures );
  5361. const images = extractFromCache( meta.images );
  5362. const nodes = extractFromCache( meta.nodes );
  5363. if ( textures.length > 0 ) data.textures = textures;
  5364. if ( images.length > 0 ) data.images = images;
  5365. if ( nodes.length > 0 ) data.nodes = nodes;
  5366. }
  5367. return data;
  5368. }
  5369. copy( source ) {
  5370. this.lightsNode = source.lightsNode;
  5371. this.envNode = source.envNode;
  5372. this.colorNode = source.colorNode;
  5373. this.normalNode = source.normalNode;
  5374. this.opacityNode = source.opacityNode;
  5375. this.backdropNode = source.backdropNode;
  5376. this.backdropAlphaNode = source.backdropAlphaNode;
  5377. this.alphaTestNode = source.alphaTestNode;
  5378. this.positionNode = source.positionNode;
  5379. this.geometryNode = source.geometryNode;
  5380. this.depthNode = source.depthNode;
  5381. this.shadowPositionNode = source.shadowPositionNode;
  5382. this.receivedShadowNode = source.receivedShadowNode;
  5383. this.castShadowNode = source.castShadowNode;
  5384. this.outputNode = source.outputNode;
  5385. this.mrtNode = source.mrtNode;
  5386. this.fragmentNode = source.fragmentNode;
  5387. this.vertexNode = source.vertexNode;
  5388. return super.copy( source );
  5389. }
  5390. }
  5391. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  5392. class InstancedPointsNodeMaterial extends NodeMaterial {
  5393. static get type() {
  5394. return 'InstancedPointsNodeMaterial';
  5395. }
  5396. constructor( params = {} ) {
  5397. super();
  5398. this.lights = false;
  5399. this.useAlphaToCoverage = true;
  5400. this.useColor = params.vertexColors;
  5401. this.pointWidth = 1;
  5402. this.pointColorNode = null;
  5403. this.pointWidthNode = null;
  5404. this.setDefaultValues( _defaultValues$e );
  5405. this.setValues( params );
  5406. }
  5407. setup( builder ) {
  5408. this.setupShaders( builder );
  5409. super.setup( builder );
  5410. }
  5411. setupShaders( { renderer } ) {
  5412. const useAlphaToCoverage = this.alphaToCoverage;
  5413. const useColor = this.useColor;
  5414. this.vertexNode = Fn( () => {
  5415. const instancePosition = attribute( 'instancePosition' ).xyz;
  5416. // camera space
  5417. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  5418. const aspect = viewport.z.div( viewport.w );
  5419. // clip space
  5420. const clipPos = cameraProjectionMatrix.mul( mvPos );
  5421. // offset in ndc space
  5422. const offset = positionGeometry.xy.toVar();
  5423. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  5424. offset.assign( offset.div( viewport.z ) );
  5425. offset.y.assign( offset.y.mul( aspect ) );
  5426. // back to clip space
  5427. offset.assign( offset.mul( clipPos.w ) );
  5428. //clipPos.xy += offset;
  5429. clipPos.addAssign( vec4( offset, 0, 0 ) );
  5430. return clipPos;
  5431. } )();
  5432. this.fragmentNode = Fn( () => {
  5433. const alpha = float( 1 ).toVar();
  5434. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  5435. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5436. const dlen = float( len2.fwidth() ).toVar();
  5437. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5438. } else {
  5439. len2.greaterThan( 1.0 ).discard();
  5440. }
  5441. let pointColorNode;
  5442. if ( this.pointColorNode ) {
  5443. pointColorNode = this.pointColorNode;
  5444. } else {
  5445. if ( useColor ) {
  5446. const instanceColor = attribute( 'instanceColor' );
  5447. pointColorNode = instanceColor.mul( materialColor );
  5448. } else {
  5449. pointColorNode = materialColor;
  5450. }
  5451. }
  5452. alpha.mulAssign( materialOpacity );
  5453. return vec4( pointColorNode, alpha );
  5454. } )();
  5455. }
  5456. get alphaToCoverage() {
  5457. return this.useAlphaToCoverage;
  5458. }
  5459. set alphaToCoverage( value ) {
  5460. if ( this.useAlphaToCoverage !== value ) {
  5461. this.useAlphaToCoverage = value;
  5462. this.needsUpdate = true;
  5463. }
  5464. }
  5465. }
  5466. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  5467. class LineBasicNodeMaterial extends NodeMaterial {
  5468. static get type() {
  5469. return 'LineBasicNodeMaterial';
  5470. }
  5471. constructor( parameters ) {
  5472. super();
  5473. this.isLineBasicNodeMaterial = true;
  5474. this.lights = false;
  5475. this.setDefaultValues( _defaultValues$d );
  5476. this.setValues( parameters );
  5477. }
  5478. }
  5479. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  5480. class LineDashedNodeMaterial extends NodeMaterial {
  5481. static get type() {
  5482. return 'LineDashedNodeMaterial';
  5483. }
  5484. constructor( parameters ) {
  5485. super();
  5486. this.isLineDashedNodeMaterial = true;
  5487. this.lights = false;
  5488. this.setDefaultValues( _defaultValues$c );
  5489. this.dashOffset = 0;
  5490. this.offsetNode = null;
  5491. this.dashScaleNode = null;
  5492. this.dashSizeNode = null;
  5493. this.gapSizeNode = null;
  5494. this.setValues( parameters );
  5495. }
  5496. setupVariants() {
  5497. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5498. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5499. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5500. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5501. dashSize.assign( dashSizeNode );
  5502. gapSize.assign( gapSizeNode );
  5503. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  5504. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  5505. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  5506. }
  5507. }
  5508. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  5509. class Line2NodeMaterial extends NodeMaterial {
  5510. static get type() {
  5511. return 'Line2NodeMaterial';
  5512. }
  5513. constructor( params = {} ) {
  5514. super();
  5515. this.lights = false;
  5516. this.setDefaultValues( _defaultValues$b );
  5517. this.useAlphaToCoverage = true;
  5518. this.useColor = params.vertexColors;
  5519. this.useDash = params.dashed;
  5520. this.useWorldUnits = false;
  5521. this.dashOffset = 0;
  5522. this.lineWidth = 1;
  5523. this.lineColorNode = null;
  5524. this.offsetNode = null;
  5525. this.dashScaleNode = null;
  5526. this.dashSizeNode = null;
  5527. this.gapSizeNode = null;
  5528. this.setValues( params );
  5529. }
  5530. setup( builder ) {
  5531. this.setupShaders( builder );
  5532. super.setup( builder );
  5533. }
  5534. setupShaders( { renderer } ) {
  5535. const useAlphaToCoverage = this.alphaToCoverage;
  5536. const useColor = this.useColor;
  5537. const useDash = this.dashed;
  5538. const useWorldUnits = this.worldUnits;
  5539. const trimSegment = Fn( ( { start, end } ) => {
  5540. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  5541. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  5542. const nearEstimate = b.mul( - 0.5 ).div( a );
  5543. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  5544. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  5545. } ).setLayout( {
  5546. name: 'trimSegment',
  5547. type: 'vec4',
  5548. inputs: [
  5549. { name: 'start', type: 'vec4' },
  5550. { name: 'end', type: 'vec4' }
  5551. ]
  5552. } );
  5553. this.vertexNode = Fn( () => {
  5554. const instanceStart = attribute( 'instanceStart' );
  5555. const instanceEnd = attribute( 'instanceEnd' );
  5556. // camera space
  5557. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  5558. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  5559. if ( useDash ) {
  5560. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5561. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5562. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  5563. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  5564. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  5565. lineDistance = lineDistance.add( offsetNode );
  5566. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  5567. }
  5568. if ( useWorldUnits ) {
  5569. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  5570. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  5571. }
  5572. const aspect = viewport.z.div( viewport.w );
  5573. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  5574. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  5575. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  5576. // perhaps there is a more elegant solution -- WestLangley
  5577. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  5578. If( perspective, () => {
  5579. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  5580. end.assign( trimSegment( { start: start, end: end } ) );
  5581. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  5582. start.assign( trimSegment( { start: end, end: start } ) );
  5583. } );
  5584. } );
  5585. // clip space
  5586. const clipStart = cameraProjectionMatrix.mul( start );
  5587. const clipEnd = cameraProjectionMatrix.mul( end );
  5588. // ndc space
  5589. const ndcStart = clipStart.xyz.div( clipStart.w );
  5590. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  5591. // direction
  5592. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  5593. // account for clip-space aspect ratio
  5594. dir.x.assign( dir.x.mul( aspect ) );
  5595. dir.assign( dir.normalize() );
  5596. const clip = vec4().toVar();
  5597. if ( useWorldUnits ) {
  5598. // get the offset direction as perpendicular to the view vector
  5599. const worldDir = end.xyz.sub( start.xyz ).normalize();
  5600. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  5601. const worldUp = worldDir.cross( tmpFwd ).normalize();
  5602. const worldFwd = worldDir.cross( worldUp );
  5603. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  5604. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  5605. // height offset
  5606. const hw = materialLineWidth.mul( 0.5 );
  5607. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  5608. // don't extend the line if we're rendering dashes because we
  5609. // won't be rendering the endcaps
  5610. if ( ! useDash ) {
  5611. // cap extension
  5612. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  5613. // add width to the box
  5614. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  5615. // endcaps
  5616. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  5617. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  5618. } );
  5619. }
  5620. // project the worldpos
  5621. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  5622. // shift the depth of the projected points so the line
  5623. // segments overlap neatly
  5624. const clipPose = vec3().toVar();
  5625. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  5626. clip.z.assign( clipPose.z.mul( clip.w ) );
  5627. } else {
  5628. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  5629. // undo aspect ratio adjustment
  5630. dir.x.assign( dir.x.div( aspect ) );
  5631. offset.x.assign( offset.x.div( aspect ) );
  5632. // sign flip
  5633. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  5634. // endcaps
  5635. If( positionGeometry.y.lessThan( 0.0 ), () => {
  5636. offset.assign( offset.sub( dir ) );
  5637. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  5638. offset.assign( offset.add( dir ) );
  5639. } );
  5640. // adjust for linewidth
  5641. offset.assign( offset.mul( materialLineWidth ) );
  5642. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  5643. offset.assign( offset.div( viewport.w ) );
  5644. // select end
  5645. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  5646. // back to clip space
  5647. offset.assign( offset.mul( clip.w ) );
  5648. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  5649. }
  5650. return clip;
  5651. } )();
  5652. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  5653. const p13 = p1.sub( p3 );
  5654. const p43 = p4.sub( p3 );
  5655. const p21 = p2.sub( p1 );
  5656. const d1343 = p13.dot( p43 );
  5657. const d4321 = p43.dot( p21 );
  5658. const d1321 = p13.dot( p21 );
  5659. const d4343 = p43.dot( p43 );
  5660. const d2121 = p21.dot( p21 );
  5661. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  5662. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  5663. const mua = numer.div( denom ).clamp();
  5664. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  5665. return vec2( mua, mub );
  5666. } );
  5667. this.fragmentNode = Fn( () => {
  5668. const vUv = uv();
  5669. if ( useDash ) {
  5670. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5671. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5672. dashSize.assign( dashSizeNode );
  5673. gapSize.assign( gapSizeNode );
  5674. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  5675. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  5676. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  5677. }
  5678. const alpha = float( 1 ).toVar( 'alpha' );
  5679. if ( useWorldUnits ) {
  5680. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  5681. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  5682. // Find the closest points on the view ray and the line segment
  5683. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  5684. const lineDir = worldEnd.sub( worldStart );
  5685. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  5686. const p1 = worldStart.add( lineDir.mul( params.x ) );
  5687. const p2 = rayEnd.mul( params.y );
  5688. const delta = p1.sub( p2 );
  5689. const len = delta.length();
  5690. const norm = len.div( materialLineWidth );
  5691. if ( ! useDash ) {
  5692. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5693. const dnorm = norm.fwidth();
  5694. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  5695. } else {
  5696. norm.greaterThan( 0.5 ).discard();
  5697. }
  5698. }
  5699. } else {
  5700. // round endcaps
  5701. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5702. const a = vUv.x;
  5703. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5704. const len2 = a.mul( a ).add( b.mul( b ) );
  5705. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  5706. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5707. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5708. } );
  5709. } else {
  5710. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5711. const a = vUv.x;
  5712. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5713. const len2 = a.mul( a ).add( b.mul( b ) );
  5714. len2.greaterThan( 1.0 ).discard();
  5715. } );
  5716. }
  5717. }
  5718. let lineColorNode;
  5719. if ( this.lineColorNode ) {
  5720. lineColorNode = this.lineColorNode;
  5721. } else {
  5722. if ( useColor ) {
  5723. const instanceColorStart = attribute( 'instanceColorStart' );
  5724. const instanceColorEnd = attribute( 'instanceColorEnd' );
  5725. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  5726. lineColorNode = instanceColor.mul( materialColor );
  5727. } else {
  5728. lineColorNode = materialColor;
  5729. }
  5730. }
  5731. return vec4( lineColorNode, alpha );
  5732. } )();
  5733. }
  5734. get worldUnits() {
  5735. return this.useWorldUnits;
  5736. }
  5737. set worldUnits( value ) {
  5738. if ( this.useWorldUnits !== value ) {
  5739. this.useWorldUnits = value;
  5740. this.needsUpdate = true;
  5741. }
  5742. }
  5743. get dashed() {
  5744. return this.useDash;
  5745. }
  5746. set dashed( value ) {
  5747. if ( this.useDash !== value ) {
  5748. this.useDash = value;
  5749. this.needsUpdate = true;
  5750. }
  5751. }
  5752. get alphaToCoverage() {
  5753. return this.useAlphaToCoverage;
  5754. }
  5755. set alphaToCoverage( value ) {
  5756. if ( this.useAlphaToCoverage !== value ) {
  5757. this.useAlphaToCoverage = value;
  5758. this.needsUpdate = true;
  5759. }
  5760. }
  5761. }
  5762. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  5763. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  5764. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  5765. class MeshNormalNodeMaterial extends NodeMaterial {
  5766. static get type() {
  5767. return 'MeshNormalNodeMaterial';
  5768. }
  5769. constructor( parameters ) {
  5770. super();
  5771. this.lights = false;
  5772. this.isMeshNormalNodeMaterial = true;
  5773. this.setDefaultValues( _defaultValues$a );
  5774. this.setValues( parameters );
  5775. }
  5776. setupDiffuseColor() {
  5777. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5778. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  5779. }
  5780. }
  5781. class EquirectUVNode extends TempNode {
  5782. static get type() {
  5783. return 'EquirectUVNode';
  5784. }
  5785. constructor( dirNode = positionWorldDirection ) {
  5786. super( 'vec2' );
  5787. this.dirNode = dirNode;
  5788. }
  5789. setup() {
  5790. const dir = this.dirNode;
  5791. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  5792. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  5793. return vec2( u, v );
  5794. }
  5795. }
  5796. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  5797. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  5798. class CubeRenderTarget extends WebGLCubeRenderTarget {
  5799. constructor( size = 1, options = {} ) {
  5800. super( size, options );
  5801. this.isCubeRenderTarget = true;
  5802. }
  5803. fromEquirectangularTexture( renderer, texture$1 ) {
  5804. const currentMinFilter = texture$1.minFilter;
  5805. const currentGenerateMipmaps = texture$1.generateMipmaps;
  5806. texture$1.generateMipmaps = true;
  5807. this.texture.type = texture$1.type;
  5808. this.texture.colorSpace = texture$1.colorSpace;
  5809. this.texture.generateMipmaps = texture$1.generateMipmaps;
  5810. this.texture.minFilter = texture$1.minFilter;
  5811. this.texture.magFilter = texture$1.magFilter;
  5812. const geometry = new BoxGeometry( 5, 5, 5 );
  5813. const uvNode = equirectUV( positionWorldDirection );
  5814. const material = new NodeMaterial();
  5815. material.colorNode = texture( texture$1, uvNode, 0 );
  5816. material.side = BackSide;
  5817. material.blending = NoBlending;
  5818. const mesh = new Mesh( geometry, material );
  5819. const scene = new Scene();
  5820. scene.add( mesh );
  5821. // Avoid blurred poles
  5822. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  5823. const camera = new CubeCamera( 1, 10, this );
  5824. const currentMRT = renderer.getMRT();
  5825. renderer.setMRT( null );
  5826. camera.update( renderer, scene );
  5827. renderer.setMRT( currentMRT );
  5828. texture$1.minFilter = currentMinFilter;
  5829. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  5830. mesh.geometry.dispose();
  5831. mesh.material.dispose();
  5832. return this;
  5833. }
  5834. }
  5835. const _cache$1 = new WeakMap();
  5836. class CubeMapNode extends TempNode {
  5837. static get type() {
  5838. return 'CubeMapNode';
  5839. }
  5840. constructor( envNode ) {
  5841. super( 'vec3' );
  5842. this.envNode = envNode;
  5843. this._cubeTexture = null;
  5844. this._cubeTextureNode = cubeTexture();
  5845. const defaultTexture = new CubeTexture();
  5846. defaultTexture.isRenderTargetTexture = true;
  5847. this._defaultTexture = defaultTexture;
  5848. this.updateBeforeType = NodeUpdateType.RENDER;
  5849. }
  5850. updateBefore( frame ) {
  5851. const { renderer, material } = frame;
  5852. const envNode = this.envNode;
  5853. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  5854. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  5855. if ( texture && texture.isTexture ) {
  5856. const mapping = texture.mapping;
  5857. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  5858. // check for converted cubemap map
  5859. if ( _cache$1.has( texture ) ) {
  5860. const cubeMap = _cache$1.get( texture );
  5861. mapTextureMapping( cubeMap, texture.mapping );
  5862. this._cubeTexture = cubeMap;
  5863. } else {
  5864. // create cube map from equirectangular map
  5865. const image = texture.image;
  5866. if ( isEquirectangularMapReady$1( image ) ) {
  5867. const renderTarget = new CubeRenderTarget( image.height );
  5868. renderTarget.fromEquirectangularTexture( renderer, texture );
  5869. mapTextureMapping( renderTarget.texture, texture.mapping );
  5870. this._cubeTexture = renderTarget.texture;
  5871. _cache$1.set( texture, renderTarget.texture );
  5872. texture.addEventListener( 'dispose', onTextureDispose );
  5873. } else {
  5874. // default cube texture as fallback when equirectangular texture is not yet loaded
  5875. this._cubeTexture = this._defaultTexture;
  5876. }
  5877. }
  5878. //
  5879. this._cubeTextureNode.value = this._cubeTexture;
  5880. } else {
  5881. // envNode already refers to a cube map
  5882. this._cubeTextureNode = this.envNode;
  5883. }
  5884. }
  5885. }
  5886. }
  5887. setup( builder ) {
  5888. this.updateBefore( builder );
  5889. return this._cubeTextureNode;
  5890. }
  5891. }
  5892. function isEquirectangularMapReady$1( image ) {
  5893. if ( image === null || image === undefined ) return false;
  5894. return image.height > 0;
  5895. }
  5896. function onTextureDispose( event ) {
  5897. const texture = event.target;
  5898. texture.removeEventListener( 'dispose', onTextureDispose );
  5899. const renderTarget = _cache$1.get( texture );
  5900. if ( renderTarget !== undefined ) {
  5901. _cache$1.delete( texture );
  5902. renderTarget.dispose();
  5903. }
  5904. }
  5905. function mapTextureMapping( texture, mapping ) {
  5906. if ( mapping === EquirectangularReflectionMapping ) {
  5907. texture.mapping = CubeReflectionMapping;
  5908. } else if ( mapping === EquirectangularRefractionMapping ) {
  5909. texture.mapping = CubeRefractionMapping;
  5910. }
  5911. }
  5912. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  5913. class BasicEnvironmentNode extends LightingNode {
  5914. static get type() {
  5915. return 'BasicEnvironmentNode';
  5916. }
  5917. constructor( envNode = null ) {
  5918. super();
  5919. this.envNode = envNode;
  5920. }
  5921. setup( builder ) {
  5922. // environment property is used in the finish() method of BasicLightingModel
  5923. builder.context.environment = cubeMapNode( this.envNode );
  5924. }
  5925. }
  5926. class BasicLightMapNode extends LightingNode {
  5927. static get type() {
  5928. return 'BasicLightMapNode';
  5929. }
  5930. constructor( lightMapNode = null ) {
  5931. super();
  5932. this.lightMapNode = lightMapNode;
  5933. }
  5934. setup( builder ) {
  5935. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  5936. const RECIPROCAL_PI = float( 1 / Math.PI );
  5937. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  5938. }
  5939. }
  5940. class LightingModel {
  5941. start( /*input, stack, builder*/ ) { }
  5942. finish( /*input, stack, builder*/ ) { }
  5943. direct( /*input, stack, builder*/ ) { }
  5944. directRectArea( /*input, stack, builder*/ ) {}
  5945. indirect( /*input, stack, builder*/ ) { }
  5946. ambientOcclusion( /*input, stack, builder*/ ) { }
  5947. }
  5948. class BasicLightingModel extends LightingModel {
  5949. constructor() {
  5950. super();
  5951. }
  5952. indirect( context, stack, builder ) {
  5953. const ambientOcclusion = context.ambientOcclusion;
  5954. const reflectedLight = context.reflectedLight;
  5955. const irradianceLightMap = builder.context.irradianceLightMap;
  5956. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  5957. // accumulation (baked indirect lighting only)
  5958. if ( irradianceLightMap ) {
  5959. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  5960. } else {
  5961. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  5962. }
  5963. // modulation
  5964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  5965. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  5966. }
  5967. finish( context, stack, builder ) {
  5968. const material = builder.material;
  5969. const outgoingLight = context.outgoingLight;
  5970. const envNode = builder.context.environment;
  5971. if ( envNode ) {
  5972. switch ( material.combine ) {
  5973. case MultiplyOperation:
  5974. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  5975. break;
  5976. case MixOperation:
  5977. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  5978. break;
  5979. case AddOperation:
  5980. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  5981. break;
  5982. default:
  5983. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  5984. break;
  5985. }
  5986. }
  5987. }
  5988. }
  5989. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  5990. class MeshBasicNodeMaterial extends NodeMaterial {
  5991. static get type() {
  5992. return 'MeshBasicNodeMaterial';
  5993. }
  5994. constructor( parameters ) {
  5995. super();
  5996. this.isMeshBasicNodeMaterial = true;
  5997. this.lights = true;
  5998. this.setDefaultValues( _defaultValues$9 );
  5999. this.setValues( parameters );
  6000. }
  6001. setupNormal() {
  6002. return normalView; // see #28839
  6003. }
  6004. setupEnvironment( builder ) {
  6005. const envNode = super.setupEnvironment( builder );
  6006. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6007. }
  6008. setupLightMap( builder ) {
  6009. let node = null;
  6010. if ( builder.material.lightMap ) {
  6011. node = new BasicLightMapNode( materialLightMap );
  6012. }
  6013. return node;
  6014. }
  6015. setupOutgoingLight() {
  6016. return diffuseColor.rgb;
  6017. }
  6018. setupLightingModel() {
  6019. return new BasicLightingModel();
  6020. }
  6021. }
  6022. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  6023. // Original approximation by Christophe Schlick '94
  6024. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  6025. // Optimized variant (presented by Epic at SIGGRAPH '13)
  6026. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  6027. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  6028. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  6029. } ); // validated
  6030. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  6031. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  6032. } ); // validated
  6033. const G_BlinnPhong_Implicit = () => float( 0.25 );
  6034. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  6035. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  6036. } );
  6037. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6038. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6039. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6040. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6041. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  6042. const G = G_BlinnPhong_Implicit();
  6043. const D = D_BlinnPhong( { dotNH } );
  6044. return F.mul( G ).mul( D );
  6045. } );
  6046. class PhongLightingModel extends BasicLightingModel {
  6047. constructor( specular = true ) {
  6048. super();
  6049. this.specular = specular;
  6050. }
  6051. direct( { lightDirection, lightColor, reflectedLight } ) {
  6052. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6053. const irradiance = dotNL.mul( lightColor );
  6054. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6055. if ( this.specular === true ) {
  6056. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  6057. }
  6058. }
  6059. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  6060. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6061. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6062. }
  6063. }
  6064. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  6065. class MeshLambertNodeMaterial extends NodeMaterial {
  6066. static get type() {
  6067. return 'MeshLambertNodeMaterial';
  6068. }
  6069. constructor( parameters ) {
  6070. super();
  6071. this.isMeshLambertNodeMaterial = true;
  6072. this.lights = true;
  6073. this.setDefaultValues( _defaultValues$8 );
  6074. this.setValues( parameters );
  6075. }
  6076. setupEnvironment( builder ) {
  6077. const envNode = super.setupEnvironment( builder );
  6078. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6079. }
  6080. setupLightingModel( /*builder*/ ) {
  6081. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  6082. }
  6083. }
  6084. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  6085. class MeshPhongNodeMaterial extends NodeMaterial {
  6086. static get type() {
  6087. return 'MeshPhongNodeMaterial';
  6088. }
  6089. constructor( parameters ) {
  6090. super();
  6091. this.isMeshPhongNodeMaterial = true;
  6092. this.lights = true;
  6093. this.shininessNode = null;
  6094. this.specularNode = null;
  6095. this.setDefaultValues( _defaultValues$7 );
  6096. this.setValues( parameters );
  6097. }
  6098. setupEnvironment( builder ) {
  6099. const envNode = super.setupEnvironment( builder );
  6100. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6101. }
  6102. setupLightingModel( /*builder*/ ) {
  6103. return new PhongLightingModel();
  6104. }
  6105. setupVariants() {
  6106. // SHININESS
  6107. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  6108. shininess.assign( shininessNode );
  6109. // SPECULAR COLOR
  6110. const specularNode = this.specularNode || materialSpecular;
  6111. specularColor.assign( specularNode );
  6112. }
  6113. copy( source ) {
  6114. this.shininessNode = source.shininessNode;
  6115. this.specularNode = source.specularNode;
  6116. return super.copy( source );
  6117. }
  6118. }
  6119. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  6120. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  6121. return float( 0 );
  6122. }
  6123. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  6124. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  6125. return geometryRoughness;
  6126. } );
  6127. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  6128. const { roughness } = inputs;
  6129. const geometryRoughness = getGeometryRoughness();
  6130. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  6131. roughnessFactor = roughnessFactor.add( geometryRoughness );
  6132. roughnessFactor = roughnessFactor.min( 1.0 );
  6133. return roughnessFactor;
  6134. } );
  6135. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  6136. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  6137. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  6138. const a2 = alpha.pow2();
  6139. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  6140. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  6141. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  6142. } ).setLayout( {
  6143. name: 'V_GGX_SmithCorrelated',
  6144. type: 'float',
  6145. inputs: [
  6146. { name: 'alpha', type: 'float' },
  6147. { name: 'dotNL', type: 'float' },
  6148. { name: 'dotNV', type: 'float' }
  6149. ]
  6150. } ); // validated
  6151. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6152. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  6153. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  6154. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  6155. const v = div( 0.5, gv.add( gl ) );
  6156. return v.saturate();
  6157. } ).setLayout( {
  6158. name: 'V_GGX_SmithCorrelated_Anisotropic',
  6159. type: 'float',
  6160. inputs: [
  6161. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6162. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6163. { name: 'dotTV', type: 'float', qualifier: 'in' },
  6164. { name: 'dotBV', type: 'float', qualifier: 'in' },
  6165. { name: 'dotTL', type: 'float', qualifier: 'in' },
  6166. { name: 'dotBL', type: 'float', qualifier: 'in' },
  6167. { name: 'dotNV', type: 'float', qualifier: 'in' },
  6168. { name: 'dotNL', type: 'float', qualifier: 'in' }
  6169. ]
  6170. } );
  6171. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  6172. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  6173. // alpha is "roughness squared" in Disney’s reparameterization
  6174. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  6175. const a2 = alpha.pow2();
  6176. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  6177. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  6178. } ).setLayout( {
  6179. name: 'D_GGX',
  6180. type: 'float',
  6181. inputs: [
  6182. { name: 'alpha', type: 'float' },
  6183. { name: 'dotNH', type: 'float' }
  6184. ]
  6185. } ); // validated
  6186. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  6187. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6188. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  6189. const a2 = alphaT.mul( alphaB );
  6190. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  6191. const v2 = v.dot( v );
  6192. const w2 = a2.div( v2 );
  6193. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  6194. } ).setLayout( {
  6195. name: 'D_GGX_Anisotropic',
  6196. type: 'float',
  6197. inputs: [
  6198. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6199. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6200. { name: 'dotNH', type: 'float', qualifier: 'in' },
  6201. { name: 'dotTH', type: 'float', qualifier: 'in' },
  6202. { name: 'dotBH', type: 'float', qualifier: 'in' }
  6203. ]
  6204. } );
  6205. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  6206. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  6207. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  6208. const normalView = inputs.normalView || transformedNormalView;
  6209. const alpha = roughness.pow2(); // UE4's roughness
  6210. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6211. const dotNL = normalView.dot( lightDirection ).clamp();
  6212. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6213. const dotNH = normalView.dot( halfDir ).clamp();
  6214. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6215. let F = F_Schlick( { f0, f90, dotVH } );
  6216. let V, D;
  6217. if ( defined( USE_IRIDESCENCE ) ) {
  6218. F = iridescence.mix( F, f );
  6219. }
  6220. if ( defined( USE_ANISOTROPY ) ) {
  6221. const dotTL = anisotropyT.dot( lightDirection );
  6222. const dotTV = anisotropyT.dot( positionViewDirection );
  6223. const dotTH = anisotropyT.dot( halfDir );
  6224. const dotBL = anisotropyB.dot( lightDirection );
  6225. const dotBV = anisotropyB.dot( positionViewDirection );
  6226. const dotBH = anisotropyB.dot( halfDir );
  6227. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  6228. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  6229. } else {
  6230. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  6231. D = D_GGX( { alpha, dotNH } );
  6232. }
  6233. return F.mul( V ).mul( D );
  6234. } ); // validated
  6235. // Analytical approximation of the DFG LUT, one half of the
  6236. // split-sum approximation used in indirect specular lighting.
  6237. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  6238. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  6239. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  6240. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  6241. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  6242. const r = roughness.mul( c0 ).add( c1 );
  6243. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  6244. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  6245. return fab;
  6246. } ).setLayout( {
  6247. name: 'DFGApprox',
  6248. type: 'vec2',
  6249. inputs: [
  6250. { name: 'roughness', type: 'float' },
  6251. { name: 'dotNV', type: 'vec3' }
  6252. ]
  6253. } );
  6254. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  6255. const { dotNV, specularColor, specularF90, roughness } = inputs;
  6256. const fab = DFGApprox( { dotNV, roughness } );
  6257. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6258. } );
  6259. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  6260. const x = dotVH.oneMinus().saturate();
  6261. const x2 = x.mul( x );
  6262. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  6263. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  6264. } ).setLayout( {
  6265. name: 'Schlick_to_F0',
  6266. type: 'vec3',
  6267. inputs: [
  6268. { name: 'f', type: 'vec3' },
  6269. { name: 'f90', type: 'float' },
  6270. { name: 'dotVH', type: 'float' }
  6271. ]
  6272. } );
  6273. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6274. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  6275. const alpha = roughness.pow2();
  6276. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  6277. const invAlpha = float( 1.0 ).div( alpha );
  6278. const cos2h = dotNH.pow2();
  6279. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  6280. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  6281. } ).setLayout( {
  6282. name: 'D_Charlie',
  6283. type: 'float',
  6284. inputs: [
  6285. { name: 'roughness', type: 'float' },
  6286. { name: 'dotNH', type: 'float' }
  6287. ]
  6288. } );
  6289. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6290. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  6291. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  6292. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  6293. } ).setLayout( {
  6294. name: 'V_Neubelt',
  6295. type: 'float',
  6296. inputs: [
  6297. { name: 'dotNV', type: 'float' },
  6298. { name: 'dotNL', type: 'float' }
  6299. ]
  6300. } );
  6301. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6302. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6303. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6304. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  6305. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6306. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  6307. const V = V_Neubelt( { dotNV, dotNL } );
  6308. return sheen.mul( D ).mul( V );
  6309. } );
  6310. // Rect Area Light
  6311. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  6312. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  6313. // code: https://github.com/selfshadow/ltc_code/
  6314. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  6315. const LUT_SIZE = 64.0;
  6316. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  6317. const LUT_BIAS = 0.5 / LUT_SIZE;
  6318. const dotNV = N.dot( V ).saturate();
  6319. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  6320. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  6321. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  6322. return uv;
  6323. } ).setLayout( {
  6324. name: 'LTC_Uv',
  6325. type: 'vec2',
  6326. inputs: [
  6327. { name: 'N', type: 'vec3' },
  6328. { name: 'V', type: 'vec3' },
  6329. { name: 'roughness', type: 'float' }
  6330. ]
  6331. } );
  6332. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  6333. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  6334. // An approximation of the form factor of a horizon-clipped rectangle.
  6335. const l = f.length();
  6336. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  6337. } ).setLayout( {
  6338. name: 'LTC_ClippedSphereFormFactor',
  6339. type: 'float',
  6340. inputs: [
  6341. { name: 'f', type: 'vec3' }
  6342. ]
  6343. } );
  6344. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  6345. const x = v1.dot( v2 );
  6346. const y = x.abs().toVar();
  6347. // rational polynomial approximation to theta / sin( theta ) / 2PI
  6348. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  6349. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  6350. const v = a.div( b );
  6351. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  6352. return v1.cross( v2 ).mul( theta_sintheta );
  6353. } ).setLayout( {
  6354. name: 'LTC_EdgeVectorFormFactor',
  6355. type: 'vec3',
  6356. inputs: [
  6357. { name: 'v1', type: 'vec3' },
  6358. { name: 'v2', type: 'vec3' }
  6359. ]
  6360. } );
  6361. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  6362. // bail if point is on back side of plane of light
  6363. // assumes ccw winding order of light vertices
  6364. const v1 = p1.sub( p0 ).toVar();
  6365. const v2 = p3.sub( p0 ).toVar();
  6366. const lightNormal = v1.cross( v2 );
  6367. const result = vec3().toVar();
  6368. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  6369. // construct orthonormal basis around N
  6370. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  6371. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  6372. // compute transform
  6373. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  6374. // transform rect
  6375. // & project rect onto sphere
  6376. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  6377. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  6378. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  6379. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  6380. // calculate vector form factor
  6381. const vectorFormFactor = vec3( 0 ).toVar();
  6382. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  6383. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  6384. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  6385. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  6386. // adjust for horizon clipping
  6387. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  6388. } );
  6389. return result;
  6390. } ).setLayout( {
  6391. name: 'LTC_Evaluate',
  6392. type: 'vec3',
  6393. inputs: [
  6394. { name: 'N', type: 'vec3' },
  6395. { name: 'V', type: 'vec3' },
  6396. { name: 'P', type: 'vec3' },
  6397. { name: 'mInv', type: 'mat3' },
  6398. { name: 'p0', type: 'vec3' },
  6399. { name: 'p1', type: 'vec3' },
  6400. { name: 'p2', type: 'vec3' },
  6401. { name: 'p3', type: 'vec3' }
  6402. ]
  6403. } );
  6404. // Mipped Bicubic Texture Filtering by N8
  6405. // https://www.shadertoy.com/view/Dl2SDW
  6406. const bC = 1.0 / 6.0;
  6407. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  6408. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  6409. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  6410. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  6411. const g0 = ( a ) => w0( a ).add( w1( a ) );
  6412. const g1 = ( a ) => w2( a ).add( w3( a ) );
  6413. // h0 and h1 are the two offset functions
  6414. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  6415. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  6416. const bicubic = ( textureNode, texelSize, lod ) => {
  6417. const uv = textureNode.uvNode;
  6418. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  6419. const iuv = floor( uvScaled );
  6420. const fuv = fract( uvScaled );
  6421. const g0x = g0( fuv.x );
  6422. const g1x = g1( fuv.x );
  6423. const h0x = h0( fuv.x );
  6424. const h1x = h1( fuv.x );
  6425. const h0y = h0( fuv.y );
  6426. const h1y = h1( fuv.y );
  6427. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6428. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6429. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6430. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6431. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  6432. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  6433. return a.add( b );
  6434. };
  6435. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  6436. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  6437. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  6438. const fLodSizeInv = div( 1.0, fLodSize );
  6439. const cLodSizeInv = div( 1.0, cLodSize );
  6440. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  6441. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  6442. return fract( lodNode ).mix( fSample, cSample );
  6443. } );
  6444. //
  6445. // Transmission
  6446. //
  6447. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  6448. // Direction of refracted light.
  6449. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  6450. // Compute rotation-independant scaling of the model matrix.
  6451. const modelScale = vec3(
  6452. length( modelMatrix[ 0 ].xyz ),
  6453. length( modelMatrix[ 1 ].xyz ),
  6454. length( modelMatrix[ 2 ].xyz )
  6455. );
  6456. // The thickness is specified in local space.
  6457. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  6458. } ).setLayout( {
  6459. name: 'getVolumeTransmissionRay',
  6460. type: 'vec3',
  6461. inputs: [
  6462. { name: 'n', type: 'vec3' },
  6463. { name: 'v', type: 'vec3' },
  6464. { name: 'thickness', type: 'float' },
  6465. { name: 'ior', type: 'float' },
  6466. { name: 'modelMatrix', type: 'mat4' }
  6467. ]
  6468. } );
  6469. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  6470. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  6471. // an IOR of 1.5 results in the default amount of microfacet refraction.
  6472. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  6473. } ).setLayout( {
  6474. name: 'applyIorToRoughness',
  6475. type: 'float',
  6476. inputs: [
  6477. { name: 'roughness', type: 'float' },
  6478. { name: 'ior', type: 'float' }
  6479. ]
  6480. } );
  6481. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  6482. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  6483. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  6484. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  6485. const transmissionSample = vTexture.uv( fragCoord );
  6486. //const transmissionSample = viewportMipTexture( fragCoord );
  6487. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  6488. return textureBicubic( transmissionSample, lod );
  6489. } );
  6490. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  6491. If( attenuationDistance.notEqual( 0 ), () => {
  6492. // Compute light attenuation using Beer's law.
  6493. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  6494. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  6495. return transmittance;
  6496. } );
  6497. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  6498. return vec3( 1.0 );
  6499. } ).setLayout( {
  6500. name: 'volumeAttenuation',
  6501. type: 'vec3',
  6502. inputs: [
  6503. { name: 'transmissionDistance', type: 'float' },
  6504. { name: 'attenuationColor', type: 'vec3' },
  6505. { name: 'attenuationDistance', type: 'float' }
  6506. ]
  6507. } );
  6508. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  6509. let transmittedLight, transmittance;
  6510. if ( dispersion ) {
  6511. transmittedLight = vec4().toVar();
  6512. transmittance = vec3().toVar();
  6513. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  6514. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  6515. Loop( { start: 0, end: 3 }, ( { i } ) => {
  6516. const ior = iors.element( i );
  6517. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6518. const refractedRayExit = position.add( transmissionRay );
  6519. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6520. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6521. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6522. refractionCoords.addAssign( 1.0 );
  6523. refractionCoords.divAssign( 2.0 );
  6524. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6525. // Sample framebuffer to get pixel the refracted ray hits.
  6526. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  6527. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  6528. transmittedLight.a.addAssign( transmissionSample.a );
  6529. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  6530. } );
  6531. transmittedLight.a.divAssign( 3.0 );
  6532. } else {
  6533. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6534. const refractedRayExit = position.add( transmissionRay );
  6535. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6536. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6537. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6538. refractionCoords.addAssign( 1.0 );
  6539. refractionCoords.divAssign( 2.0 );
  6540. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6541. // Sample framebuffer to get pixel the refracted ray hits.
  6542. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  6543. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  6544. }
  6545. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  6546. const dotNV = n.dot( v ).clamp();
  6547. // Get the specular component.
  6548. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  6549. dotNV,
  6550. specularColor,
  6551. specularF90,
  6552. roughness
  6553. } ) );
  6554. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  6555. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  6556. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  6557. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  6558. } );
  6559. //
  6560. // Iridescence
  6561. //
  6562. // XYZ to linear-sRGB color space
  6563. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  6564. 3.2404542, - 0.9692660, 0.0556434,
  6565. - 1.5371385, 1.8760108, - 0.2040259,
  6566. - 0.4985314, 0.0415560, 1.0572252
  6567. );
  6568. // Assume air interface for top
  6569. // Note: We don't handle the case fresnel0 == 1
  6570. const Fresnel0ToIor = ( fresnel0 ) => {
  6571. const sqrtF0 = fresnel0.sqrt();
  6572. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  6573. };
  6574. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  6575. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  6576. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  6577. };
  6578. // Fresnel equations for dielectric/dielectric interfaces.
  6579. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  6580. // Evaluation XYZ sensitivity curves in Fourier space
  6581. const evalSensitivity = ( OPD, shift ) => {
  6582. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  6583. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  6584. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  6585. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  6586. 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() );
  6587. 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() );
  6588. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  6589. const rgb = XYZ_TO_REC709.mul( xyz );
  6590. return rgb;
  6591. };
  6592. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  6593. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  6594. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  6595. // Evaluate the cosTheta on the base layer (Snell law)
  6596. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  6597. // Handle TIR:
  6598. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  6599. If( cosTheta2Sq.lessThan( 0 ), () => {
  6600. return vec3( 1.0 );
  6601. } );
  6602. const cosTheta2 = cosTheta2Sq.sqrt();
  6603. // First interface
  6604. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  6605. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  6606. //const R21 = R12;
  6607. const T121 = R12.oneMinus();
  6608. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  6609. const phi21 = float( Math.PI ).sub( phi12 );
  6610. // Second interface
  6611. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  6612. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  6613. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  6614. const phi23 = vec3(
  6615. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6616. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6617. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  6618. );
  6619. // Phase shift
  6620. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  6621. const phi = vec3( phi21 ).add( phi23 );
  6622. // Compound terms
  6623. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  6624. const r123 = R123.sqrt();
  6625. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  6626. // Reflectance term for m = 0 (DC term amplitude)
  6627. const C0 = R12.add( Rs );
  6628. const I = C0.toVar();
  6629. // Reflectance term for m > 0 (pairs of diracs)
  6630. const Cm = Rs.sub( T121 ).toVar();
  6631. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  6632. Cm.mulAssign( r123 );
  6633. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  6634. I.addAssign( Cm.mul( Sm ) );
  6635. } );
  6636. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  6637. return I.max( vec3( 0.0 ) );
  6638. } ).setLayout( {
  6639. name: 'evalIridescence',
  6640. type: 'vec3',
  6641. inputs: [
  6642. { name: 'outsideIOR', type: 'float' },
  6643. { name: 'eta2', type: 'float' },
  6644. { name: 'cosTheta1', type: 'float' },
  6645. { name: 'thinFilmThickness', type: 'float' },
  6646. { name: 'baseF0', type: 'vec3' }
  6647. ]
  6648. } );
  6649. //
  6650. // Sheen
  6651. //
  6652. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  6653. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  6654. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  6655. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  6656. const dotNV = normal.dot( viewDir ).saturate();
  6657. const r2 = roughness.pow2();
  6658. const a = select(
  6659. roughness.lessThan( 0.25 ),
  6660. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  6661. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  6662. );
  6663. const b = select(
  6664. roughness.lessThan( 0.25 ),
  6665. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  6666. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  6667. );
  6668. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  6669. return DG.mul( 1.0 / Math.PI ).saturate();
  6670. } );
  6671. const clearcoatF0 = vec3( 0.04 );
  6672. const clearcoatF90 = float( 1 );
  6673. //
  6674. class PhysicalLightingModel extends LightingModel {
  6675. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  6676. super();
  6677. this.clearcoat = clearcoat;
  6678. this.sheen = sheen;
  6679. this.iridescence = iridescence;
  6680. this.anisotropy = anisotropy;
  6681. this.transmission = transmission;
  6682. this.dispersion = dispersion;
  6683. this.clearcoatRadiance = null;
  6684. this.clearcoatSpecularDirect = null;
  6685. this.clearcoatSpecularIndirect = null;
  6686. this.sheenSpecularDirect = null;
  6687. this.sheenSpecularIndirect = null;
  6688. this.iridescenceFresnel = null;
  6689. this.iridescenceF0 = null;
  6690. }
  6691. start( context ) {
  6692. if ( this.clearcoat === true ) {
  6693. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  6694. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  6695. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  6696. }
  6697. if ( this.sheen === true ) {
  6698. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  6699. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  6700. }
  6701. if ( this.iridescence === true ) {
  6702. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  6703. this.iridescenceFresnel = evalIridescence( {
  6704. outsideIOR: float( 1.0 ),
  6705. eta2: iridescenceIOR,
  6706. cosTheta1: dotNVi,
  6707. thinFilmThickness: iridescenceThickness,
  6708. baseF0: specularColor
  6709. } );
  6710. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  6711. }
  6712. if ( this.transmission === true ) {
  6713. const position = positionWorld;
  6714. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  6715. const n = transformedNormalWorld;
  6716. context.backdrop = getIBLVolumeRefraction(
  6717. n,
  6718. v,
  6719. roughness,
  6720. diffuseColor,
  6721. specularColor,
  6722. specularF90, // specularF90
  6723. position, // positionWorld
  6724. modelWorldMatrix, // modelMatrix
  6725. cameraViewMatrix, // viewMatrix
  6726. cameraProjectionMatrix, // projMatrix
  6727. ior,
  6728. thickness,
  6729. attenuationColor,
  6730. attenuationDistance,
  6731. this.dispersion ? dispersion : null
  6732. );
  6733. context.backdropAlpha = transmission;
  6734. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  6735. }
  6736. }
  6737. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  6738. // Approximates multiscattering in order to preserve energy.
  6739. // http://www.jcgt.org/published/0008/01/03/
  6740. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  6741. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6742. const fab = DFGApprox( { roughness, dotNV } );
  6743. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  6744. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6745. const Ess = fab.x.add( fab.y );
  6746. const Ems = Ess.oneMinus();
  6747. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  6748. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  6749. singleScatter.addAssign( FssEss );
  6750. multiScatter.addAssign( Fms.mul( Ems ) );
  6751. }
  6752. direct( { lightDirection, lightColor, reflectedLight } ) {
  6753. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6754. const irradiance = dotNL.mul( lightColor );
  6755. if ( this.sheen === true ) {
  6756. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  6757. }
  6758. if ( this.clearcoat === true ) {
  6759. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  6760. const ccIrradiance = dotNLcc.mul( lightColor );
  6761. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  6762. }
  6763. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6764. 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 } ) ) );
  6765. }
  6766. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  6767. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  6768. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  6769. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  6770. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  6771. const N = transformedNormalView;
  6772. const V = positionViewDirection;
  6773. const P = positionView.toVar();
  6774. const uv = LTC_Uv( { N, V, roughness } );
  6775. const t1 = ltc_1.uv( uv ).toVar();
  6776. const t2 = ltc_2.uv( uv ).toVar();
  6777. const mInv = mat3(
  6778. vec3( t1.x, 0, t1.y ),
  6779. vec3( 0, 1, 0 ),
  6780. vec3( t1.z, 0, t1.w )
  6781. ).toVar();
  6782. // LTC Fresnel Approximation by Stephen Hill
  6783. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  6784. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  6785. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  6786. 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 } ) ) );
  6787. }
  6788. indirect( context, stack, builder ) {
  6789. this.indirectDiffuse( context, stack, builder );
  6790. this.indirectSpecular( context, stack, builder );
  6791. this.ambientOcclusion( context, stack, builder );
  6792. }
  6793. indirectDiffuse( { irradiance, reflectedLight } ) {
  6794. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6795. }
  6796. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  6797. if ( this.sheen === true ) {
  6798. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  6799. sheen,
  6800. IBLSheenBRDF( {
  6801. normal: transformedNormalView,
  6802. viewDir: positionViewDirection,
  6803. roughness: sheenRoughness
  6804. } )
  6805. ) );
  6806. }
  6807. if ( this.clearcoat === true ) {
  6808. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6809. const clearcoatEnv = EnvironmentBRDF( {
  6810. dotNV: dotNVcc,
  6811. specularColor: clearcoatF0,
  6812. specularF90: clearcoatF90,
  6813. roughness: clearcoatRoughness
  6814. } );
  6815. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  6816. }
  6817. // Both indirect specular and indirect diffuse light accumulate here
  6818. const singleScattering = vec3().toVar( 'singleScattering' );
  6819. const multiScattering = vec3().toVar( 'multiScattering' );
  6820. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  6821. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  6822. const totalScattering = singleScattering.add( multiScattering );
  6823. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  6824. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  6825. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  6826. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  6827. }
  6828. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  6829. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6830. const aoNV = dotNV.add( ambientOcclusion );
  6831. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  6832. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  6833. if ( this.clearcoat === true ) {
  6834. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  6835. }
  6836. if ( this.sheen === true ) {
  6837. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  6838. }
  6839. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6840. reflectedLight.indirectSpecular.mulAssign( aoNode );
  6841. }
  6842. finish( context ) {
  6843. const { outgoingLight } = context;
  6844. if ( this.clearcoat === true ) {
  6845. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6846. const Fcc = F_Schlick( {
  6847. dotVH: dotNVcc,
  6848. f0: clearcoatF0,
  6849. f90: clearcoatF90
  6850. } );
  6851. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  6852. outgoingLight.assign( clearcoatLight );
  6853. }
  6854. if ( this.sheen === true ) {
  6855. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  6856. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  6857. outgoingLight.assign( sheenLight );
  6858. }
  6859. }
  6860. }
  6861. // These defines must match with PMREMGenerator
  6862. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  6863. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  6864. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  6865. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  6866. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  6867. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  6868. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  6869. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  6870. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  6871. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  6872. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  6873. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  6874. // These shader functions convert between the UV coordinates of a single face of
  6875. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  6876. // sampling a textureCube (not generally normalized ).
  6877. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  6878. const absDirection = vec3( abs( direction ) ).toVar();
  6879. const face = float( - 1.0 ).toVar();
  6880. If( absDirection.x.greaterThan( absDirection.z ), () => {
  6881. If( absDirection.x.greaterThan( absDirection.y ), () => {
  6882. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  6883. } ).Else( () => {
  6884. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6885. } );
  6886. } ).Else( () => {
  6887. If( absDirection.z.greaterThan( absDirection.y ), () => {
  6888. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  6889. } ).Else( () => {
  6890. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6891. } );
  6892. } );
  6893. return face;
  6894. } ).setLayout( {
  6895. name: 'getFace',
  6896. type: 'float',
  6897. inputs: [
  6898. { name: 'direction', type: 'vec3' }
  6899. ]
  6900. } );
  6901. // RH coordinate system; PMREM face-indexing convention
  6902. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  6903. const uv = vec2().toVar();
  6904. If( face.equal( 0.0 ), () => {
  6905. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  6906. } ).ElseIf( face.equal( 1.0 ), () => {
  6907. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  6908. } ).ElseIf( face.equal( 2.0 ), () => {
  6909. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  6910. } ).ElseIf( face.equal( 3.0 ), () => {
  6911. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  6912. } ).ElseIf( face.equal( 4.0 ), () => {
  6913. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  6914. } ).Else( () => {
  6915. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  6916. } );
  6917. return mul( 0.5, uv.add( 1.0 ) );
  6918. } ).setLayout( {
  6919. name: 'getUV',
  6920. type: 'vec2',
  6921. inputs: [
  6922. { name: 'direction', type: 'vec3' },
  6923. { name: 'face', type: 'float' }
  6924. ]
  6925. } );
  6926. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  6927. const mip = float( 0.0 ).toVar();
  6928. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  6929. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  6930. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  6931. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  6932. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  6933. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  6934. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  6935. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  6936. } ).Else( () => {
  6937. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  6938. } );
  6939. return mip;
  6940. } ).setLayout( {
  6941. name: 'roughnessToMip',
  6942. type: 'float',
  6943. inputs: [
  6944. { name: 'roughness', type: 'float' }
  6945. ]
  6946. } );
  6947. // RH coordinate system; PMREM face-indexing convention
  6948. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  6949. const uv = uv_immutable.toVar();
  6950. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  6951. const direction = vec3( uv, 1.0 ).toVar();
  6952. If( face.equal( 0.0 ), () => {
  6953. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  6954. } ).ElseIf( face.equal( 1.0 ), () => {
  6955. direction.assign( direction.xzy );
  6956. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  6957. } ).ElseIf( face.equal( 2.0 ), () => {
  6958. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  6959. } ).ElseIf( face.equal( 3.0 ), () => {
  6960. direction.assign( direction.zyx );
  6961. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  6962. } ).ElseIf( face.equal( 4.0 ), () => {
  6963. direction.assign( direction.xzy );
  6964. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  6965. } ).ElseIf( face.equal( 5.0 ), () => {
  6966. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  6967. } );
  6968. return direction;
  6969. } ).setLayout( {
  6970. name: 'getDirection',
  6971. type: 'vec3',
  6972. inputs: [
  6973. { name: 'uv', type: 'vec2' },
  6974. { name: 'face', type: 'float' }
  6975. ]
  6976. } );
  6977. //
  6978. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6979. const roughness = float( roughness_immutable );
  6980. const sampleDir = vec3( sampleDir_immutable );
  6981. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  6982. const mipF = fract( mip );
  6983. const mipInt = floor( mip );
  6984. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6985. If( mipF.notEqual( 0.0 ), () => {
  6986. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6987. color0.assign( mix( color0, color1, mipF ) );
  6988. } );
  6989. return color0;
  6990. } );
  6991. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6992. const mipInt = float( mipInt_immutable ).toVar();
  6993. const direction = vec3( direction_immutable );
  6994. const face = float( getFace( direction ) ).toVar();
  6995. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  6996. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  6997. const faceSize = float( exp2( mipInt ) ).toVar();
  6998. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  6999. If( face.greaterThan( 2.0 ), () => {
  7000. uv.y.addAssign( faceSize );
  7001. face.subAssign( 3.0 );
  7002. } );
  7003. uv.x.addAssign( face.mul( faceSize ) );
  7004. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  7005. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  7006. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  7007. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  7008. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  7009. } );
  7010. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7011. const cosTheta = cos( theta );
  7012. // Rodrigues' axis-angle rotation
  7013. const sampleDirection = outputDirection.mul( cosTheta )
  7014. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  7015. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  7016. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  7017. } );
  7018. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7019. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  7020. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  7021. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  7022. } );
  7023. axis.assign( normalize( axis ) );
  7024. const gl_FragColor = vec3().toVar();
  7025. 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 } ) ) );
  7026. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  7027. If( i.greaterThanEqual( samples ), () => {
  7028. Break();
  7029. } );
  7030. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  7031. 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 } ) ) );
  7032. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7033. } );
  7034. return vec4( gl_FragColor, 1 );
  7035. } );
  7036. let _generator = null;
  7037. const _cache = new WeakMap();
  7038. function _generateCubeUVSize( imageHeight ) {
  7039. const maxMip = Math.log2( imageHeight ) - 2;
  7040. const texelHeight = 1.0 / imageHeight;
  7041. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  7042. return { texelWidth, texelHeight, maxMip };
  7043. }
  7044. function _getPMREMFromTexture( texture ) {
  7045. let cacheTexture = _cache.get( texture );
  7046. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  7047. if ( pmremVersion !== texture.pmremVersion ) {
  7048. const image = texture.image;
  7049. if ( texture.isCubeTexture ) {
  7050. if ( isCubeMapReady( image ) ) {
  7051. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  7052. } else {
  7053. return null;
  7054. }
  7055. } else {
  7056. if ( isEquirectangularMapReady( image ) ) {
  7057. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  7058. } else {
  7059. return null;
  7060. }
  7061. }
  7062. cacheTexture.pmremVersion = texture.pmremVersion;
  7063. _cache.set( texture, cacheTexture );
  7064. }
  7065. return cacheTexture.texture;
  7066. }
  7067. class PMREMNode extends TempNode {
  7068. static get type() {
  7069. return 'PMREMNode';
  7070. }
  7071. constructor( value, uvNode = null, levelNode = null ) {
  7072. super( 'vec3' );
  7073. this._value = value;
  7074. this._pmrem = null;
  7075. this.uvNode = uvNode;
  7076. this.levelNode = levelNode;
  7077. this._generator = null;
  7078. const defaultTexture = new Texture();
  7079. defaultTexture.isRenderTargetTexture = true;
  7080. this._texture = texture( defaultTexture );
  7081. this._width = uniform( 0 );
  7082. this._height = uniform( 0 );
  7083. this._maxMip = uniform( 0 );
  7084. this.updateBeforeType = NodeUpdateType.RENDER;
  7085. }
  7086. set value( value ) {
  7087. this._value = value;
  7088. this._pmrem = null;
  7089. }
  7090. get value() {
  7091. return this._value;
  7092. }
  7093. updateFromTexture( texture ) {
  7094. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  7095. this._texture.value = texture;
  7096. this._width.value = cubeUVSize.texelWidth;
  7097. this._height.value = cubeUVSize.texelHeight;
  7098. this._maxMip.value = cubeUVSize.maxMip;
  7099. }
  7100. updateBefore() {
  7101. let pmrem = this._pmrem;
  7102. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  7103. const texture = this._value;
  7104. if ( pmremVersion !== texture.pmremVersion ) {
  7105. if ( texture.isPMREMTexture === true ) {
  7106. pmrem = texture;
  7107. } else {
  7108. pmrem = _getPMREMFromTexture( texture );
  7109. }
  7110. if ( pmrem !== null ) {
  7111. this._pmrem = pmrem;
  7112. this.updateFromTexture( pmrem );
  7113. }
  7114. }
  7115. }
  7116. setup( builder ) {
  7117. if ( _generator === null ) {
  7118. _generator = builder.createPMREMGenerator();
  7119. }
  7120. //
  7121. this.updateBefore( builder );
  7122. //
  7123. let uvNode = this.uvNode;
  7124. if ( uvNode === null && builder.context.getUV ) {
  7125. uvNode = builder.context.getUV( this );
  7126. }
  7127. //
  7128. const texture = this.value;
  7129. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  7130. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  7131. }
  7132. //
  7133. let levelNode = this.levelNode;
  7134. if ( levelNode === null && builder.context.getTextureLevel ) {
  7135. levelNode = builder.context.getTextureLevel( this );
  7136. }
  7137. //
  7138. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  7139. }
  7140. }
  7141. function isCubeMapReady( image ) {
  7142. if ( image === null || image === undefined ) return false;
  7143. let count = 0;
  7144. const length = 6;
  7145. for ( let i = 0; i < length; i ++ ) {
  7146. if ( image[ i ] !== undefined ) count ++;
  7147. }
  7148. return count === length;
  7149. }
  7150. function isEquirectangularMapReady( image ) {
  7151. if ( image === null || image === undefined ) return false;
  7152. return image.height > 0;
  7153. }
  7154. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  7155. const _envNodeCache = new WeakMap();
  7156. class EnvironmentNode extends LightingNode {
  7157. static get type() {
  7158. return 'EnvironmentNode';
  7159. }
  7160. constructor( envNode = null ) {
  7161. super();
  7162. this.envNode = envNode;
  7163. }
  7164. setup( builder ) {
  7165. const { material } = builder;
  7166. let envNode = this.envNode;
  7167. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7168. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7169. let cacheEnvNode = _envNodeCache.get( value );
  7170. if ( cacheEnvNode === undefined ) {
  7171. cacheEnvNode = pmremTexture( value );
  7172. _envNodeCache.set( value, cacheEnvNode );
  7173. }
  7174. envNode = cacheEnvNode;
  7175. }
  7176. //
  7177. const envMap = material.envMap;
  7178. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  7179. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  7180. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  7181. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  7182. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  7183. const isolateRadiance = cache( radiance );
  7184. const isolateIrradiance = cache( irradiance );
  7185. //
  7186. builder.context.radiance.addAssign( isolateRadiance );
  7187. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  7188. //
  7189. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  7190. if ( clearcoatRadiance ) {
  7191. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  7192. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  7193. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  7194. }
  7195. }
  7196. }
  7197. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  7198. let reflectVec = null;
  7199. return {
  7200. getUV: () => {
  7201. if ( reflectVec === null ) {
  7202. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  7203. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  7204. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  7205. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  7206. }
  7207. return reflectVec;
  7208. },
  7209. getTextureLevel: () => {
  7210. return roughnessNode;
  7211. }
  7212. };
  7213. };
  7214. const createIrradianceContext = ( normalWorldNode ) => {
  7215. return {
  7216. getUV: () => {
  7217. return normalWorldNode;
  7218. },
  7219. getTextureLevel: () => {
  7220. return float( 1.0 );
  7221. }
  7222. };
  7223. };
  7224. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  7225. class MeshStandardNodeMaterial extends NodeMaterial {
  7226. static get type() {
  7227. return 'MeshStandardNodeMaterial';
  7228. }
  7229. constructor( parameters ) {
  7230. super();
  7231. this.isMeshStandardNodeMaterial = true;
  7232. this.lights = true;
  7233. this.emissiveNode = null;
  7234. this.metalnessNode = null;
  7235. this.roughnessNode = null;
  7236. this.setDefaultValues( _defaultValues$6 );
  7237. this.setValues( parameters );
  7238. }
  7239. setupEnvironment( builder ) {
  7240. let envNode = super.setupEnvironment( builder );
  7241. if ( envNode === null && builder.environmentNode ) {
  7242. envNode = builder.environmentNode;
  7243. }
  7244. return envNode ? new EnvironmentNode( envNode ) : null;
  7245. }
  7246. setupLightingModel( /*builder*/ ) {
  7247. return new PhysicalLightingModel();
  7248. }
  7249. setupSpecular() {
  7250. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  7251. specularColor.assign( specularColorNode );
  7252. specularF90.assign( 1.0 );
  7253. }
  7254. setupVariants() {
  7255. // METALNESS
  7256. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  7257. metalness.assign( metalnessNode );
  7258. // ROUGHNESS
  7259. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  7260. roughnessNode = getRoughness( { roughness: roughnessNode } );
  7261. roughness.assign( roughnessNode );
  7262. // SPECULAR COLOR
  7263. this.setupSpecular();
  7264. // DIFFUSE COLOR
  7265. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  7266. }
  7267. copy( source ) {
  7268. this.emissiveNode = source.emissiveNode;
  7269. this.metalnessNode = source.metalnessNode;
  7270. this.roughnessNode = source.roughnessNode;
  7271. return super.copy( source );
  7272. }
  7273. }
  7274. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  7275. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  7276. static get type() {
  7277. return 'MeshPhysicalNodeMaterial';
  7278. }
  7279. constructor( parameters ) {
  7280. super();
  7281. this.isMeshPhysicalNodeMaterial = true;
  7282. this.clearcoatNode = null;
  7283. this.clearcoatRoughnessNode = null;
  7284. this.clearcoatNormalNode = null;
  7285. this.sheenNode = null;
  7286. this.sheenRoughnessNode = null;
  7287. this.iridescenceNode = null;
  7288. this.iridescenceIORNode = null;
  7289. this.iridescenceThicknessNode = null;
  7290. this.specularIntensityNode = null;
  7291. this.specularColorNode = null;
  7292. this.iorNode = null;
  7293. this.transmissionNode = null;
  7294. this.thicknessNode = null;
  7295. this.attenuationDistanceNode = null;
  7296. this.attenuationColorNode = null;
  7297. this.dispersionNode = null;
  7298. this.anisotropyNode = null;
  7299. this.setDefaultValues( _defaultValues$5 );
  7300. this.setValues( parameters );
  7301. }
  7302. get useClearcoat() {
  7303. return this.clearcoat > 0 || this.clearcoatNode !== null;
  7304. }
  7305. get useIridescence() {
  7306. return this.iridescence > 0 || this.iridescenceNode !== null;
  7307. }
  7308. get useSheen() {
  7309. return this.sheen > 0 || this.sheenNode !== null;
  7310. }
  7311. get useAnisotropy() {
  7312. return this.anisotropy > 0 || this.anisotropyNode !== null;
  7313. }
  7314. get useTransmission() {
  7315. return this.transmission > 0 || this.transmissionNode !== null;
  7316. }
  7317. get useDispersion() {
  7318. return this.dispersion > 0 || this.dispersionNode !== null;
  7319. }
  7320. setupSpecular() {
  7321. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  7322. ior.assign( iorNode );
  7323. 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 ) );
  7324. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  7325. }
  7326. setupLightingModel( /*builder*/ ) {
  7327. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  7328. }
  7329. setupVariants( builder ) {
  7330. super.setupVariants( builder );
  7331. // CLEARCOAT
  7332. if ( this.useClearcoat ) {
  7333. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  7334. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  7335. clearcoat.assign( clearcoatNode );
  7336. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  7337. }
  7338. // SHEEN
  7339. if ( this.useSheen ) {
  7340. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  7341. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  7342. sheen.assign( sheenNode );
  7343. sheenRoughness.assign( sheenRoughnessNode );
  7344. }
  7345. // IRIDESCENCE
  7346. if ( this.useIridescence ) {
  7347. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  7348. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  7349. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  7350. iridescence.assign( iridescenceNode );
  7351. iridescenceIOR.assign( iridescenceIORNode );
  7352. iridescenceThickness.assign( iridescenceThicknessNode );
  7353. }
  7354. // ANISOTROPY
  7355. if ( this.useAnisotropy ) {
  7356. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  7357. anisotropy.assign( anisotropyV.length() );
  7358. If( anisotropy.equal( 0.0 ), () => {
  7359. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  7360. } ).Else( () => {
  7361. anisotropyV.divAssign( vec2( anisotropy ) );
  7362. anisotropy.assign( anisotropy.saturate() );
  7363. } );
  7364. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  7365. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  7366. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  7367. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  7368. }
  7369. // TRANSMISSION
  7370. if ( this.useTransmission ) {
  7371. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  7372. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  7373. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  7374. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  7375. transmission.assign( transmissionNode );
  7376. thickness.assign( thicknessNode );
  7377. attenuationDistance.assign( attenuationDistanceNode );
  7378. attenuationColor.assign( attenuationColorNode );
  7379. if ( this.useDispersion ) {
  7380. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  7381. dispersion.assign( dispersionNode );
  7382. }
  7383. }
  7384. }
  7385. setupClearcoatNormal() {
  7386. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  7387. }
  7388. setup( builder ) {
  7389. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  7390. super.setup( builder );
  7391. }
  7392. copy( source ) {
  7393. this.clearcoatNode = source.clearcoatNode;
  7394. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  7395. this.clearcoatNormalNode = source.clearcoatNormalNode;
  7396. this.sheenNode = source.sheenNode;
  7397. this.sheenRoughnessNode = source.sheenRoughnessNode;
  7398. this.iridescenceNode = source.iridescenceNode;
  7399. this.iridescenceIORNode = source.iridescenceIORNode;
  7400. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  7401. this.specularIntensityNode = source.specularIntensityNode;
  7402. this.specularColorNode = source.specularColorNode;
  7403. this.transmissionNode = source.transmissionNode;
  7404. this.thicknessNode = source.thicknessNode;
  7405. this.attenuationDistanceNode = source.attenuationDistanceNode;
  7406. this.attenuationColorNode = source.attenuationColorNode;
  7407. this.dispersionNode = source.dispersionNode;
  7408. this.anisotropyNode = source.anisotropyNode;
  7409. return super.copy( source );
  7410. }
  7411. }
  7412. class SSSLightingModel extends PhysicalLightingModel {
  7413. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  7414. super( useClearcoat, useSheen, useIridescence );
  7415. this.useSSS = useSSS;
  7416. }
  7417. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7418. if ( this.useSSS === true ) {
  7419. const material = builder.material;
  7420. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  7421. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  7422. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  7423. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  7424. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  7425. }
  7426. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  7427. }
  7428. }
  7429. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  7430. static get type() {
  7431. return 'MeshSSSNodeMaterial';
  7432. }
  7433. constructor( parameters ) {
  7434. super( parameters );
  7435. this.thicknessColorNode = null;
  7436. this.thicknessDistortionNode = float( 0.1 );
  7437. this.thicknessAmbientNode = float( 0.0 );
  7438. this.thicknessAttenuationNode = float( .1 );
  7439. this.thicknessPowerNode = float( 2.0 );
  7440. this.thicknessScaleNode = float( 10.0 );
  7441. }
  7442. get useSSS() {
  7443. return this.thicknessColorNode !== null;
  7444. }
  7445. setupLightingModel( /*builder*/ ) {
  7446. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  7447. }
  7448. copy( source ) {
  7449. this.thicknessColorNode = source.thicknessColorNode;
  7450. this.thicknessDistortionNode = source.thicknessDistortionNode;
  7451. this.thicknessAmbientNode = source.thicknessAmbientNode;
  7452. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  7453. this.thicknessPowerNode = source.thicknessPowerNode;
  7454. this.thicknessScaleNode = source.thicknessScaleNode;
  7455. return super.copy( source );
  7456. }
  7457. }
  7458. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  7459. // dotNL will be from -1.0 to 1.0
  7460. const dotNL = normal.dot( lightDirection );
  7461. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  7462. if ( builder.material.gradientMap ) {
  7463. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  7464. return vec3( gradientMap.r );
  7465. } else {
  7466. const fw = coord.fwidth().mul( 0.5 );
  7467. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  7468. }
  7469. } );
  7470. class ToonLightingModel extends LightingModel {
  7471. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7472. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  7473. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7474. }
  7475. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7476. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7477. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7478. }
  7479. }
  7480. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  7481. class MeshToonNodeMaterial extends NodeMaterial {
  7482. static get type() {
  7483. return 'MeshToonNodeMaterial';
  7484. }
  7485. constructor( parameters ) {
  7486. super();
  7487. this.isMeshToonNodeMaterial = true;
  7488. this.lights = true;
  7489. this.setDefaultValues( _defaultValues$4 );
  7490. this.setValues( parameters );
  7491. }
  7492. setupLightingModel( /*builder*/ ) {
  7493. return new ToonLightingModel();
  7494. }
  7495. }
  7496. class MatcapUVNode extends TempNode {
  7497. static get type() {
  7498. return 'MatcapUVNode';
  7499. }
  7500. constructor() {
  7501. super( 'vec2' );
  7502. }
  7503. setup() {
  7504. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  7505. const y = positionViewDirection.cross( x );
  7506. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  7507. }
  7508. }
  7509. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  7510. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  7511. class MeshMatcapNodeMaterial extends NodeMaterial {
  7512. static get type() {
  7513. return 'MeshMatcapNodeMaterial';
  7514. }
  7515. constructor( parameters ) {
  7516. super();
  7517. this.lights = false;
  7518. this.isMeshMatcapNodeMaterial = true;
  7519. this.setDefaultValues( _defaultValues$3 );
  7520. this.setValues( parameters );
  7521. }
  7522. setupVariants( builder ) {
  7523. const uv = matcapUV;
  7524. let matcapColor;
  7525. if ( builder.material.matcap ) {
  7526. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  7527. } else {
  7528. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  7529. }
  7530. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  7531. }
  7532. }
  7533. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  7534. class PointsNodeMaterial extends NodeMaterial {
  7535. static get type() {
  7536. return 'PointsNodeMaterial';
  7537. }
  7538. constructor( parameters ) {
  7539. super();
  7540. this.isPointsNodeMaterial = true;
  7541. this.lights = false;
  7542. this.transparent = true;
  7543. this.sizeNode = null;
  7544. this.setDefaultValues( _defaultValues$2 );
  7545. this.setValues( parameters );
  7546. }
  7547. copy( source ) {
  7548. this.sizeNode = source.sizeNode;
  7549. return super.copy( source );
  7550. }
  7551. }
  7552. class RotateNode extends TempNode {
  7553. static get type() {
  7554. return 'RotateNode';
  7555. }
  7556. constructor( positionNode, rotationNode ) {
  7557. super();
  7558. this.positionNode = positionNode;
  7559. this.rotationNode = rotationNode;
  7560. }
  7561. getNodeType( builder ) {
  7562. return this.positionNode.getNodeType( builder );
  7563. }
  7564. setup( builder ) {
  7565. const { rotationNode, positionNode } = this;
  7566. const nodeType = this.getNodeType( builder );
  7567. if ( nodeType === 'vec2' ) {
  7568. const cosAngle = rotationNode.cos();
  7569. const sinAngle = rotationNode.sin();
  7570. const rotationMatrix = mat2(
  7571. cosAngle, sinAngle,
  7572. sinAngle.negate(), cosAngle
  7573. );
  7574. return rotationMatrix.mul( positionNode );
  7575. } else {
  7576. const rotation = rotationNode;
  7577. 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 ) );
  7578. 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 ) );
  7579. 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 ) );
  7580. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  7581. }
  7582. }
  7583. }
  7584. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  7585. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  7586. class SpriteNodeMaterial extends NodeMaterial {
  7587. static get type() {
  7588. return 'SpriteNodeMaterial';
  7589. }
  7590. constructor( parameters ) {
  7591. super();
  7592. this.isSpriteNodeMaterial = true;
  7593. this.lights = false;
  7594. this._useSizeAttenuation = true;
  7595. this.positionNode = null;
  7596. this.rotationNode = null;
  7597. this.scaleNode = null;
  7598. this.setDefaultValues( _defaultValues$1 );
  7599. this.setValues( parameters );
  7600. }
  7601. setupPosition( { object, camera, context } ) {
  7602. const sizeAttenuation = this.sizeAttenuation;
  7603. // < VERTEX STAGE >
  7604. const { positionNode, rotationNode, scaleNode } = this;
  7605. const vertex = positionLocal;
  7606. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  7607. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  7608. if ( scaleNode !== null ) {
  7609. scale = scale.mul( scaleNode );
  7610. }
  7611. if ( ! sizeAttenuation ) {
  7612. if ( camera.isPerspectiveCamera ) {
  7613. scale = scale.mul( mvPosition.z.negate() );
  7614. } else {
  7615. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  7616. scale = scale.mul( orthoScale.mul( 2 ) );
  7617. }
  7618. }
  7619. let alignedPosition = vertex.xy;
  7620. if ( object.center && object.center.isVector2 === true ) {
  7621. const center = reference$1( 'center', 'vec2' );
  7622. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  7623. }
  7624. alignedPosition = alignedPosition.mul( scale );
  7625. const rotation = float( rotationNode || materialRotation );
  7626. const rotatedPosition = rotate( alignedPosition, rotation );
  7627. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  7628. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  7629. context.vertex = vertex;
  7630. return modelViewProjection;
  7631. }
  7632. copy( source ) {
  7633. this.positionNode = source.positionNode;
  7634. this.rotationNode = source.rotationNode;
  7635. this.scaleNode = source.scaleNode;
  7636. return super.copy( source );
  7637. }
  7638. get sizeAttenuation() {
  7639. return this._useSizeAttenuation;
  7640. }
  7641. set sizeAttenuation( value ) {
  7642. if ( this._useSizeAttenuation !== value ) {
  7643. this._useSizeAttenuation = value;
  7644. this.needsUpdate = true;
  7645. }
  7646. }
  7647. }
  7648. class ShadowMaskModel extends LightingModel {
  7649. constructor() {
  7650. super();
  7651. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  7652. }
  7653. direct( { shadowMask } ) {
  7654. this.shadowNode.mulAssign( shadowMask );
  7655. }
  7656. finish( context ) {
  7657. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  7658. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  7659. }
  7660. }
  7661. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  7662. class ShadowNodeMaterial extends NodeMaterial {
  7663. static get type() {
  7664. return 'ShadowNodeMaterial';
  7665. }
  7666. constructor( parameters ) {
  7667. super();
  7668. this.isShadowNodeMaterial = true;
  7669. this.lights = true;
  7670. this.setDefaultValues( _defaultValues );
  7671. this.setValues( parameters );
  7672. }
  7673. setupLightingModel( /*builder*/ ) {
  7674. return new ShadowMaskModel();
  7675. }
  7676. }
  7677. const normal = Fn( ( { texture, uv } ) => {
  7678. const epsilon = 0.0001;
  7679. const ret = vec3().toVar();
  7680. If( uv.x.lessThan( epsilon ), () => {
  7681. ret.assign( vec3( 1, 0, 0 ) );
  7682. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  7683. ret.assign( vec3( 0, 1, 0 ) );
  7684. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  7685. ret.assign( vec3( 0, 0, 1 ) );
  7686. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  7687. ret.assign( vec3( - 1, 0, 0 ) );
  7688. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  7689. ret.assign( vec3( 0, - 1, 0 ) );
  7690. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  7691. ret.assign( vec3( 0, 0, - 1 ) );
  7692. } ).Else( () => {
  7693. const step = 0.01;
  7694. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  7695. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  7696. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  7697. ret.assign( vec3( x, y, z ) );
  7698. } );
  7699. return ret.normalize();
  7700. } );
  7701. class Texture3DNode extends TextureNode {
  7702. static get type() {
  7703. return 'Texture3DNode';
  7704. }
  7705. constructor( value, uvNode = null, levelNode = null ) {
  7706. super( value, uvNode, levelNode );
  7707. this.isTexture3DNode = true;
  7708. }
  7709. getInputType( /*builder*/ ) {
  7710. return 'texture3D';
  7711. }
  7712. getDefaultUV() {
  7713. return vec3( 0.5, 0.5, 0.5 );
  7714. }
  7715. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  7716. setupUV( builder, uvNode ) {
  7717. return uvNode;
  7718. }
  7719. generateUV( builder, uvNode ) {
  7720. return uvNode.build( builder, 'vec3' );
  7721. }
  7722. normal( uvNode ) {
  7723. return normal( { texture: this, uv: uvNode } );
  7724. }
  7725. }
  7726. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  7727. class VolumeNodeMaterial extends NodeMaterial {
  7728. static get type() {
  7729. return 'VolumeNodeMaterial';
  7730. }
  7731. constructor( params = {} ) {
  7732. super();
  7733. this.lights = false;
  7734. this.isVolumeNodeMaterial = true;
  7735. this.testNode = null;
  7736. this.setValues( params );
  7737. }
  7738. setup( builder ) {
  7739. const map = texture3D( this.map, null, 0 );
  7740. const hitBox = Fn( ( { orig, dir } ) => {
  7741. const box_min = vec3( - 0.5 );
  7742. const box_max = vec3( 0.5 );
  7743. const inv_dir = dir.reciprocal();
  7744. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  7745. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  7746. const tmin = min$1( tmin_tmp, tmax_tmp );
  7747. const tmax = max$1( tmin_tmp, tmax_tmp );
  7748. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  7749. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  7750. return vec2( t0, t1 );
  7751. } );
  7752. this.fragmentNode = Fn( () => {
  7753. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  7754. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  7755. const rayDir = vDirection.normalize();
  7756. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  7757. bounds.x.greaterThan( bounds.y ).discard();
  7758. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  7759. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  7760. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  7761. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  7762. delta.divAssign( materialReference( 'steps', 'float' ) );
  7763. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  7764. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  7765. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  7766. if ( this.testNode !== null ) {
  7767. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  7768. } else {
  7769. // default to show surface of mesh
  7770. ac.a.assign( 1 );
  7771. Break();
  7772. }
  7773. p.addAssign( rayDir.mul( delta ) );
  7774. } );
  7775. ac.a.equal( 0 ).discard();
  7776. return vec4( ac );
  7777. } )();
  7778. super.setup( builder );
  7779. }
  7780. }
  7781. class Animation {
  7782. constructor( nodes, info ) {
  7783. this.nodes = nodes;
  7784. this.info = info;
  7785. this._context = self;
  7786. this._animationLoop = null;
  7787. this._requestId = null;
  7788. }
  7789. start() {
  7790. const update = ( time, frame ) => {
  7791. this._requestId = this._context.requestAnimationFrame( update );
  7792. if ( this.info.autoReset === true ) this.info.reset();
  7793. this.nodes.nodeFrame.update();
  7794. this.info.frame = this.nodes.nodeFrame.frameId;
  7795. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  7796. };
  7797. update();
  7798. }
  7799. stop() {
  7800. this._context.cancelAnimationFrame( this._requestId );
  7801. this._requestId = null;
  7802. }
  7803. setAnimationLoop( callback ) {
  7804. this._animationLoop = callback;
  7805. }
  7806. setContext( context ) {
  7807. this._context = context;
  7808. }
  7809. dispose() {
  7810. this.stop();
  7811. }
  7812. }
  7813. class ChainMap {
  7814. constructor() {
  7815. this.weakMap = new WeakMap();
  7816. }
  7817. get( keys ) {
  7818. let map = this.weakMap;
  7819. for ( let i = 0; i < keys.length; i ++ ) {
  7820. map = map.get( keys[ i ] );
  7821. if ( map === undefined ) return undefined;
  7822. }
  7823. return map.get( keys[ keys.length - 1 ] );
  7824. }
  7825. set( keys, value ) {
  7826. let map = this.weakMap;
  7827. for ( let i = 0; i < keys.length; i ++ ) {
  7828. const key = keys[ i ];
  7829. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  7830. map = map.get( key );
  7831. }
  7832. return map.set( keys[ keys.length - 1 ], value );
  7833. }
  7834. delete( keys ) {
  7835. let map = this.weakMap;
  7836. for ( let i = 0; i < keys.length; i ++ ) {
  7837. map = map.get( keys[ i ] );
  7838. if ( map === undefined ) return false;
  7839. }
  7840. return map.delete( keys[ keys.length - 1 ] );
  7841. }
  7842. }
  7843. let _id$7 = 0;
  7844. function getKeys( obj ) {
  7845. const keys = Object.keys( obj );
  7846. let proto = Object.getPrototypeOf( obj );
  7847. while ( proto ) {
  7848. const descriptors = Object.getOwnPropertyDescriptors( proto );
  7849. for ( const key in descriptors ) {
  7850. if ( descriptors[ key ] !== undefined ) {
  7851. const descriptor = descriptors[ key ];
  7852. if ( descriptor && typeof descriptor.get === 'function' ) {
  7853. keys.push( key );
  7854. }
  7855. }
  7856. }
  7857. proto = Object.getPrototypeOf( proto );
  7858. }
  7859. return keys;
  7860. }
  7861. class RenderObject {
  7862. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  7863. this._nodes = nodes;
  7864. this._geometries = geometries;
  7865. this.id = _id$7 ++;
  7866. this.renderer = renderer;
  7867. this.object = object;
  7868. this.material = material;
  7869. this.scene = scene;
  7870. this.camera = camera;
  7871. this.lightsNode = lightsNode;
  7872. this.context = renderContext;
  7873. this.geometry = object.geometry;
  7874. this.version = material.version;
  7875. this.drawRange = null;
  7876. this.attributes = null;
  7877. this.pipeline = null;
  7878. this.vertexBuffers = null;
  7879. this.drawParams = null;
  7880. this.bundle = null;
  7881. this.clippingContext = clippingContext;
  7882. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  7883. this.initialNodesCacheKey = this.getDynamicCacheKey();
  7884. this.initialCacheKey = this.getCacheKey();
  7885. this._nodeBuilderState = null;
  7886. this._bindings = null;
  7887. this._monitor = null;
  7888. this.onDispose = null;
  7889. this.isRenderObject = true;
  7890. this.onMaterialDispose = () => {
  7891. this.dispose();
  7892. };
  7893. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  7894. }
  7895. updateClipping( parent ) {
  7896. this.clippingContext = parent;
  7897. }
  7898. get clippingNeedsUpdate() {
  7899. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  7900. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  7901. return true;
  7902. }
  7903. get hardwareClippingPlanes() {
  7904. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  7905. }
  7906. getNodeBuilderState() {
  7907. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  7908. }
  7909. getMonitor() {
  7910. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  7911. }
  7912. getBindings() {
  7913. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  7914. }
  7915. getIndex() {
  7916. return this._geometries.getIndex( this );
  7917. }
  7918. getIndirect() {
  7919. return this._geometries.getIndirect( this );
  7920. }
  7921. getChainArray() {
  7922. return [ this.object, this.material, this.context, this.lightsNode ];
  7923. }
  7924. setGeometry( geometry ) {
  7925. this.geometry = geometry;
  7926. this.attributes = null;
  7927. }
  7928. getAttributes() {
  7929. if ( this.attributes !== null ) return this.attributes;
  7930. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  7931. const geometry = this.geometry;
  7932. const attributes = [];
  7933. const vertexBuffers = new Set();
  7934. for ( const nodeAttribute of nodeAttributes ) {
  7935. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  7936. if ( attribute === undefined ) continue;
  7937. attributes.push( attribute );
  7938. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  7939. vertexBuffers.add( bufferAttribute );
  7940. }
  7941. this.attributes = attributes;
  7942. this.vertexBuffers = Array.from( vertexBuffers.values() );
  7943. return attributes;
  7944. }
  7945. getVertexBuffers() {
  7946. if ( this.vertexBuffers === null ) this.getAttributes();
  7947. return this.vertexBuffers;
  7948. }
  7949. getDrawParameters() {
  7950. const { object, material, geometry, group, drawRange } = this;
  7951. const drawParams = this.drawParams || ( this.drawParams = {
  7952. vertexCount: 0,
  7953. firstVertex: 0,
  7954. instanceCount: 0,
  7955. firstInstance: 0
  7956. } );
  7957. const index = this.getIndex();
  7958. const hasIndex = ( index !== null );
  7959. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  7960. if ( instanceCount === 0 ) return null;
  7961. drawParams.instanceCount = instanceCount;
  7962. if ( object.isBatchedMesh === true ) return drawParams;
  7963. let rangeFactor = 1;
  7964. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  7965. rangeFactor = 2;
  7966. }
  7967. let firstVertex = drawRange.start * rangeFactor;
  7968. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  7969. if ( group !== null ) {
  7970. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  7971. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  7972. }
  7973. const position = geometry.attributes.position;
  7974. let itemCount = Infinity;
  7975. if ( hasIndex ) {
  7976. itemCount = index.count;
  7977. } else if ( position !== undefined && position !== null ) {
  7978. itemCount = position.count;
  7979. }
  7980. firstVertex = Math.max( firstVertex, 0 );
  7981. lastVertex = Math.min( lastVertex, itemCount );
  7982. const count = lastVertex - firstVertex;
  7983. if ( count < 0 || count === Infinity ) return null;
  7984. drawParams.vertexCount = count;
  7985. drawParams.firstVertex = firstVertex;
  7986. return drawParams;
  7987. }
  7988. getGeometryCacheKey() {
  7989. const { geometry } = this;
  7990. let cacheKey = '';
  7991. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  7992. const attribute = geometry.attributes[ name ];
  7993. cacheKey += name + ',';
  7994. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  7995. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  7996. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  7997. if ( attribute.normalized ) cacheKey += 'n,';
  7998. }
  7999. if ( geometry.index ) {
  8000. cacheKey += 'index,';
  8001. }
  8002. return cacheKey;
  8003. }
  8004. getMaterialCacheKey() {
  8005. const { object, material } = this;
  8006. let cacheKey = material.customProgramCacheKey();
  8007. for ( const property of getKeys( material ) ) {
  8008. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  8009. const value = material[ property ];
  8010. let valueKey;
  8011. if ( value !== null ) {
  8012. // some material values require a formatting
  8013. const type = typeof value;
  8014. if ( type === 'number' ) {
  8015. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  8016. } else if ( type === 'object' ) {
  8017. valueKey = '{';
  8018. if ( value.isTexture ) {
  8019. valueKey += value.mapping;
  8020. }
  8021. valueKey += '}';
  8022. } else {
  8023. valueKey = String( value );
  8024. }
  8025. } else {
  8026. valueKey = String( value );
  8027. }
  8028. cacheKey += /*property + ':' +*/ valueKey + ',';
  8029. }
  8030. cacheKey += this.clippingContextCacheKey + ',';
  8031. if ( object.geometry ) {
  8032. cacheKey += this.getGeometryCacheKey();
  8033. }
  8034. if ( object.skeleton ) {
  8035. cacheKey += object.skeleton.bones.length + ',';
  8036. }
  8037. if ( object.morphTargetInfluences ) {
  8038. cacheKey += object.morphTargetInfluences.length + ',';
  8039. }
  8040. if ( object.isBatchedMesh ) {
  8041. cacheKey += object._matricesTexture.uuid + ',';
  8042. if ( object._colorsTexture !== null ) {
  8043. cacheKey += object._colorsTexture.uuid + ',';
  8044. }
  8045. }
  8046. if ( object.count > 1 ) {
  8047. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  8048. cacheKey += object.uuid + ',';
  8049. }
  8050. cacheKey += object.receiveShadow + ',';
  8051. return hashString( cacheKey );
  8052. }
  8053. get needsGeometryUpdate() {
  8054. return this.geometry.id !== this.object.geometry.id;
  8055. }
  8056. get needsUpdate() {
  8057. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  8058. }
  8059. getDynamicCacheKey() {
  8060. // Environment Nodes Cache Key
  8061. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  8062. if ( this.object.receiveShadow ) {
  8063. cacheKey += 1;
  8064. }
  8065. return cacheKey;
  8066. }
  8067. getCacheKey() {
  8068. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  8069. }
  8070. dispose() {
  8071. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  8072. this.onDispose();
  8073. }
  8074. }
  8075. const chainArray = [];
  8076. class RenderObjects {
  8077. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  8078. this.renderer = renderer;
  8079. this.nodes = nodes;
  8080. this.geometries = geometries;
  8081. this.pipelines = pipelines;
  8082. this.bindings = bindings;
  8083. this.info = info;
  8084. this.chainMaps = {};
  8085. }
  8086. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8087. const chainMap = this.getChainMap( passId );
  8088. // reuse chainArray
  8089. chainArray[ 0 ] = object;
  8090. chainArray[ 1 ] = material;
  8091. chainArray[ 2 ] = renderContext;
  8092. chainArray[ 3 ] = lightsNode;
  8093. let renderObject = chainMap.get( chainArray );
  8094. if ( renderObject === undefined ) {
  8095. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8096. chainMap.set( chainArray, renderObject );
  8097. } else {
  8098. renderObject.updateClipping( clippingContext );
  8099. if ( renderObject.needsGeometryUpdate ) {
  8100. renderObject.setGeometry( object.geometry );
  8101. }
  8102. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  8103. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  8104. renderObject.dispose();
  8105. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8106. } else {
  8107. renderObject.version = material.version;
  8108. }
  8109. }
  8110. }
  8111. return renderObject;
  8112. }
  8113. getChainMap( passId = 'default' ) {
  8114. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  8115. }
  8116. dispose() {
  8117. this.chainMaps = {};
  8118. }
  8119. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8120. const chainMap = this.getChainMap( passId );
  8121. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  8122. renderObject.onDispose = () => {
  8123. this.pipelines.delete( renderObject );
  8124. this.bindings.delete( renderObject );
  8125. this.nodes.delete( renderObject );
  8126. chainMap.delete( renderObject.getChainArray() );
  8127. };
  8128. return renderObject;
  8129. }
  8130. }
  8131. class DataMap {
  8132. constructor() {
  8133. this.data = new WeakMap();
  8134. }
  8135. get( object ) {
  8136. let map = this.data.get( object );
  8137. if ( map === undefined ) {
  8138. map = {};
  8139. this.data.set( object, map );
  8140. }
  8141. return map;
  8142. }
  8143. delete( object ) {
  8144. let map;
  8145. if ( this.data.has( object ) ) {
  8146. map = this.data.get( object );
  8147. this.data.delete( object );
  8148. }
  8149. return map;
  8150. }
  8151. has( object ) {
  8152. return this.data.has( object );
  8153. }
  8154. dispose() {
  8155. this.data = new WeakMap();
  8156. }
  8157. }
  8158. const AttributeType = {
  8159. VERTEX: 1,
  8160. INDEX: 2,
  8161. STORAGE: 3,
  8162. INDIRECT: 4
  8163. };
  8164. // size of a chunk in bytes (STD140 layout)
  8165. const GPU_CHUNK_BYTES = 16;
  8166. // @TODO: Move to src/constants.js
  8167. const BlendColorFactor = 211;
  8168. const OneMinusBlendColorFactor = 212;
  8169. class Attributes extends DataMap {
  8170. constructor( backend ) {
  8171. super();
  8172. this.backend = backend;
  8173. }
  8174. delete( attribute ) {
  8175. const attributeData = super.delete( attribute );
  8176. if ( attributeData !== undefined ) {
  8177. this.backend.destroyAttribute( attribute );
  8178. }
  8179. return attributeData;
  8180. }
  8181. update( attribute, type ) {
  8182. const data = this.get( attribute );
  8183. if ( data.version === undefined ) {
  8184. if ( type === AttributeType.VERTEX ) {
  8185. this.backend.createAttribute( attribute );
  8186. } else if ( type === AttributeType.INDEX ) {
  8187. this.backend.createIndexAttribute( attribute );
  8188. } else if ( type === AttributeType.STORAGE ) {
  8189. this.backend.createStorageAttribute( attribute );
  8190. } else if ( type === AttributeType.INDIRECT ) {
  8191. this.backend.createIndirectStorageAttribute( attribute );
  8192. }
  8193. data.version = this._getBufferAttribute( attribute ).version;
  8194. } else {
  8195. const bufferAttribute = this._getBufferAttribute( attribute );
  8196. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  8197. this.backend.updateAttribute( attribute );
  8198. data.version = bufferAttribute.version;
  8199. }
  8200. }
  8201. }
  8202. _getBufferAttribute( attribute ) {
  8203. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8204. return attribute;
  8205. }
  8206. }
  8207. function arrayNeedsUint32( array ) {
  8208. // assumes larger values usually on last
  8209. for ( let i = array.length - 1; i >= 0; -- i ) {
  8210. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  8211. }
  8212. return false;
  8213. }
  8214. function getWireframeVersion( geometry ) {
  8215. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  8216. }
  8217. function getWireframeIndex( geometry ) {
  8218. const indices = [];
  8219. const geometryIndex = geometry.index;
  8220. const geometryPosition = geometry.attributes.position;
  8221. if ( geometryIndex !== null ) {
  8222. const array = geometryIndex.array;
  8223. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8224. const a = array[ i + 0 ];
  8225. const b = array[ i + 1 ];
  8226. const c = array[ i + 2 ];
  8227. indices.push( a, b, b, c, c, a );
  8228. }
  8229. } else {
  8230. const array = geometryPosition.array;
  8231. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8232. const a = i + 0;
  8233. const b = i + 1;
  8234. const c = i + 2;
  8235. indices.push( a, b, b, c, c, a );
  8236. }
  8237. }
  8238. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8239. attribute.version = getWireframeVersion( geometry );
  8240. return attribute;
  8241. }
  8242. class Geometries extends DataMap {
  8243. constructor( attributes, info ) {
  8244. super();
  8245. this.attributes = attributes;
  8246. this.info = info;
  8247. this.wireframes = new WeakMap();
  8248. this.attributeCall = new WeakMap();
  8249. }
  8250. has( renderObject ) {
  8251. const geometry = renderObject.geometry;
  8252. return super.has( geometry ) && this.get( geometry ).initialized === true;
  8253. }
  8254. updateForRender( renderObject ) {
  8255. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  8256. this.updateAttributes( renderObject );
  8257. }
  8258. initGeometry( renderObject ) {
  8259. const geometry = renderObject.geometry;
  8260. const geometryData = this.get( geometry );
  8261. geometryData.initialized = true;
  8262. this.info.memory.geometries ++;
  8263. const onDispose = () => {
  8264. this.info.memory.geometries --;
  8265. const index = geometry.index;
  8266. const geometryAttributes = renderObject.getAttributes();
  8267. if ( index !== null ) {
  8268. this.attributes.delete( index );
  8269. }
  8270. for ( const geometryAttribute of geometryAttributes ) {
  8271. this.attributes.delete( geometryAttribute );
  8272. }
  8273. const wireframeAttribute = this.wireframes.get( geometry );
  8274. if ( wireframeAttribute !== undefined ) {
  8275. this.attributes.delete( wireframeAttribute );
  8276. }
  8277. geometry.removeEventListener( 'dispose', onDispose );
  8278. };
  8279. geometry.addEventListener( 'dispose', onDispose );
  8280. }
  8281. updateAttributes( renderObject ) {
  8282. // attributes
  8283. const attributes = renderObject.getAttributes();
  8284. for ( const attribute of attributes ) {
  8285. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  8286. this.updateAttribute( attribute, AttributeType.STORAGE );
  8287. } else {
  8288. this.updateAttribute( attribute, AttributeType.VERTEX );
  8289. }
  8290. }
  8291. // indexes
  8292. const index = this.getIndex( renderObject );
  8293. if ( index !== null ) {
  8294. this.updateAttribute( index, AttributeType.INDEX );
  8295. }
  8296. // indirect
  8297. const indirect = renderObject.geometry.indirect;
  8298. if ( indirect !== null ) {
  8299. this.updateAttribute( indirect, AttributeType.INDIRECT );
  8300. }
  8301. }
  8302. updateAttribute( attribute, type ) {
  8303. const callId = this.info.render.calls;
  8304. if ( ! attribute.isInterleavedBufferAttribute ) {
  8305. if ( this.attributeCall.get( attribute ) !== callId ) {
  8306. this.attributes.update( attribute, type );
  8307. this.attributeCall.set( attribute, callId );
  8308. }
  8309. } else {
  8310. if ( this.attributeCall.get( attribute ) === undefined ) {
  8311. this.attributes.update( attribute, type );
  8312. this.attributeCall.set( attribute, callId );
  8313. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  8314. this.attributes.update( attribute, type );
  8315. this.attributeCall.set( attribute.data, callId );
  8316. this.attributeCall.set( attribute, callId );
  8317. }
  8318. }
  8319. }
  8320. getIndirect( renderObject ) {
  8321. return renderObject.geometry.indirect;
  8322. }
  8323. getIndex( renderObject ) {
  8324. const { geometry, material } = renderObject;
  8325. let index = geometry.index;
  8326. if ( material.wireframe === true ) {
  8327. const wireframes = this.wireframes;
  8328. let wireframeAttribute = wireframes.get( geometry );
  8329. if ( wireframeAttribute === undefined ) {
  8330. wireframeAttribute = getWireframeIndex( geometry );
  8331. wireframes.set( geometry, wireframeAttribute );
  8332. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  8333. this.attributes.delete( wireframeAttribute );
  8334. wireframeAttribute = getWireframeIndex( geometry );
  8335. wireframes.set( geometry, wireframeAttribute );
  8336. }
  8337. index = wireframeAttribute;
  8338. }
  8339. return index;
  8340. }
  8341. }
  8342. class Info {
  8343. constructor() {
  8344. this.autoReset = true;
  8345. this.frame = 0;
  8346. this.calls = 0;
  8347. this.render = {
  8348. calls: 0,
  8349. frameCalls: 0,
  8350. drawCalls: 0,
  8351. triangles: 0,
  8352. points: 0,
  8353. lines: 0,
  8354. timestamp: 0,
  8355. previousFrameCalls: 0,
  8356. timestampCalls: 0
  8357. };
  8358. this.compute = {
  8359. calls: 0,
  8360. frameCalls: 0,
  8361. timestamp: 0,
  8362. previousFrameCalls: 0,
  8363. timestampCalls: 0
  8364. };
  8365. this.memory = {
  8366. geometries: 0,
  8367. textures: 0
  8368. };
  8369. }
  8370. update( object, count, instanceCount ) {
  8371. this.render.drawCalls ++;
  8372. if ( object.isMesh || object.isSprite ) {
  8373. this.render.triangles += instanceCount * ( count / 3 );
  8374. } else if ( object.isPoints ) {
  8375. this.render.points += instanceCount * count;
  8376. } else if ( object.isLineSegments ) {
  8377. this.render.lines += instanceCount * ( count / 2 );
  8378. } else if ( object.isLine ) {
  8379. this.render.lines += instanceCount * ( count - 1 );
  8380. } else {
  8381. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  8382. }
  8383. }
  8384. updateTimestamp( type, time ) {
  8385. if ( this[ type ].timestampCalls === 0 ) {
  8386. this[ type ].timestamp = 0;
  8387. }
  8388. this[ type ].timestamp += time;
  8389. this[ type ].timestampCalls ++;
  8390. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  8391. this[ type ].timestampCalls = 0;
  8392. }
  8393. }
  8394. reset() {
  8395. const previousRenderFrameCalls = this.render.frameCalls;
  8396. this.render.previousFrameCalls = previousRenderFrameCalls;
  8397. const previousComputeFrameCalls = this.compute.frameCalls;
  8398. this.compute.previousFrameCalls = previousComputeFrameCalls;
  8399. this.render.drawCalls = 0;
  8400. this.render.frameCalls = 0;
  8401. this.compute.frameCalls = 0;
  8402. this.render.triangles = 0;
  8403. this.render.points = 0;
  8404. this.render.lines = 0;
  8405. }
  8406. dispose() {
  8407. this.reset();
  8408. this.calls = 0;
  8409. this.render.calls = 0;
  8410. this.compute.calls = 0;
  8411. this.render.timestamp = 0;
  8412. this.compute.timestamp = 0;
  8413. this.memory.geometries = 0;
  8414. this.memory.textures = 0;
  8415. }
  8416. }
  8417. class Pipeline {
  8418. constructor( cacheKey ) {
  8419. this.cacheKey = cacheKey;
  8420. this.usedTimes = 0;
  8421. }
  8422. }
  8423. class RenderPipeline extends Pipeline {
  8424. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  8425. super( cacheKey );
  8426. this.vertexProgram = vertexProgram;
  8427. this.fragmentProgram = fragmentProgram;
  8428. }
  8429. }
  8430. class ComputePipeline extends Pipeline {
  8431. constructor( cacheKey, computeProgram ) {
  8432. super( cacheKey );
  8433. this.computeProgram = computeProgram;
  8434. this.isComputePipeline = true;
  8435. }
  8436. }
  8437. let _id$6 = 0;
  8438. class ProgrammableStage {
  8439. constructor( code, type, transforms = null, attributes = null ) {
  8440. this.id = _id$6 ++;
  8441. this.code = code;
  8442. this.stage = type;
  8443. this.transforms = transforms;
  8444. this.attributes = attributes;
  8445. this.usedTimes = 0;
  8446. }
  8447. }
  8448. class Pipelines extends DataMap {
  8449. constructor( backend, nodes ) {
  8450. super();
  8451. this.backend = backend;
  8452. this.nodes = nodes;
  8453. this.bindings = null; // set by the bindings
  8454. this.caches = new Map();
  8455. this.programs = {
  8456. vertex: new Map(),
  8457. fragment: new Map(),
  8458. compute: new Map()
  8459. };
  8460. }
  8461. getForCompute( computeNode, bindings ) {
  8462. const { backend } = this;
  8463. const data = this.get( computeNode );
  8464. if ( this._needsComputeUpdate( computeNode ) ) {
  8465. const previousPipeline = data.pipeline;
  8466. if ( previousPipeline ) {
  8467. previousPipeline.usedTimes --;
  8468. previousPipeline.computeProgram.usedTimes --;
  8469. }
  8470. // get shader
  8471. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  8472. // programmable stage
  8473. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  8474. if ( stageCompute === undefined ) {
  8475. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  8476. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  8477. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  8478. backend.createProgram( stageCompute );
  8479. }
  8480. // determine compute pipeline
  8481. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  8482. let pipeline = this.caches.get( cacheKey );
  8483. if ( pipeline === undefined ) {
  8484. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8485. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  8486. }
  8487. // keep track of all used times
  8488. pipeline.usedTimes ++;
  8489. stageCompute.usedTimes ++;
  8490. //
  8491. data.version = computeNode.version;
  8492. data.pipeline = pipeline;
  8493. }
  8494. return data.pipeline;
  8495. }
  8496. getForRender( renderObject, promises = null ) {
  8497. const { backend } = this;
  8498. const data = this.get( renderObject );
  8499. if ( this._needsRenderUpdate( renderObject ) ) {
  8500. const previousPipeline = data.pipeline;
  8501. if ( previousPipeline ) {
  8502. previousPipeline.usedTimes --;
  8503. previousPipeline.vertexProgram.usedTimes --;
  8504. previousPipeline.fragmentProgram.usedTimes --;
  8505. }
  8506. // get shader
  8507. const nodeBuilderState = renderObject.getNodeBuilderState();
  8508. // programmable stages
  8509. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  8510. if ( stageVertex === undefined ) {
  8511. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  8512. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  8513. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  8514. backend.createProgram( stageVertex );
  8515. }
  8516. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  8517. if ( stageFragment === undefined ) {
  8518. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  8519. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  8520. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  8521. backend.createProgram( stageFragment );
  8522. }
  8523. // determine render pipeline
  8524. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8525. let pipeline = this.caches.get( cacheKey );
  8526. if ( pipeline === undefined ) {
  8527. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8528. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  8529. } else {
  8530. renderObject.pipeline = pipeline;
  8531. }
  8532. // keep track of all used times
  8533. pipeline.usedTimes ++;
  8534. stageVertex.usedTimes ++;
  8535. stageFragment.usedTimes ++;
  8536. //
  8537. data.pipeline = pipeline;
  8538. }
  8539. return data.pipeline;
  8540. }
  8541. delete( object ) {
  8542. const pipeline = this.get( object ).pipeline;
  8543. if ( pipeline ) {
  8544. // pipeline
  8545. pipeline.usedTimes --;
  8546. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  8547. // programs
  8548. if ( pipeline.isComputePipeline ) {
  8549. pipeline.computeProgram.usedTimes --;
  8550. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  8551. } else {
  8552. pipeline.fragmentProgram.usedTimes --;
  8553. pipeline.vertexProgram.usedTimes --;
  8554. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  8555. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  8556. }
  8557. }
  8558. return super.delete( object );
  8559. }
  8560. dispose() {
  8561. super.dispose();
  8562. this.caches = new Map();
  8563. this.programs = {
  8564. vertex: new Map(),
  8565. fragment: new Map(),
  8566. compute: new Map()
  8567. };
  8568. }
  8569. updateForRender( renderObject ) {
  8570. this.getForRender( renderObject );
  8571. }
  8572. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  8573. // check for existing pipeline
  8574. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  8575. let pipeline = this.caches.get( cacheKey );
  8576. if ( pipeline === undefined ) {
  8577. pipeline = new ComputePipeline( cacheKey, stageCompute );
  8578. this.caches.set( cacheKey, pipeline );
  8579. this.backend.createComputePipeline( pipeline, bindings );
  8580. }
  8581. return pipeline;
  8582. }
  8583. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  8584. // check for existing pipeline
  8585. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8586. let pipeline = this.caches.get( cacheKey );
  8587. if ( pipeline === undefined ) {
  8588. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  8589. this.caches.set( cacheKey, pipeline );
  8590. renderObject.pipeline = pipeline;
  8591. this.backend.createRenderPipeline( renderObject, promises );
  8592. }
  8593. return pipeline;
  8594. }
  8595. _getComputeCacheKey( computeNode, stageCompute ) {
  8596. return computeNode.id + ',' + stageCompute.id;
  8597. }
  8598. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  8599. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  8600. }
  8601. _releasePipeline( pipeline ) {
  8602. this.caches.delete( pipeline.cacheKey );
  8603. }
  8604. _releaseProgram( program ) {
  8605. const code = program.code;
  8606. const stage = program.stage;
  8607. this.programs[ stage ].delete( code );
  8608. }
  8609. _needsComputeUpdate( computeNode ) {
  8610. const data = this.get( computeNode );
  8611. return data.pipeline === undefined || data.version !== computeNode.version;
  8612. }
  8613. _needsRenderUpdate( renderObject ) {
  8614. const data = this.get( renderObject );
  8615. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  8616. }
  8617. }
  8618. class Bindings extends DataMap {
  8619. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  8620. super();
  8621. this.backend = backend;
  8622. this.textures = textures;
  8623. this.pipelines = pipelines;
  8624. this.attributes = attributes;
  8625. this.nodes = nodes;
  8626. this.info = info;
  8627. this.pipelines.bindings = this; // assign bindings to pipelines
  8628. }
  8629. getForRender( renderObject ) {
  8630. const bindings = renderObject.getBindings();
  8631. for ( const bindGroup of bindings ) {
  8632. const groupData = this.get( bindGroup );
  8633. if ( groupData.bindGroup === undefined ) {
  8634. // each object defines an array of bindings (ubos, textures, samplers etc.)
  8635. this._init( bindGroup );
  8636. this.backend.createBindings( bindGroup, bindings, 0 );
  8637. groupData.bindGroup = bindGroup;
  8638. }
  8639. }
  8640. return bindings;
  8641. }
  8642. getForCompute( computeNode ) {
  8643. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  8644. for ( const bindGroup of bindings ) {
  8645. const groupData = this.get( bindGroup );
  8646. if ( groupData.bindGroup === undefined ) {
  8647. this._init( bindGroup );
  8648. this.backend.createBindings( bindGroup, bindings, 0 );
  8649. groupData.bindGroup = bindGroup;
  8650. }
  8651. }
  8652. return bindings;
  8653. }
  8654. updateForCompute( computeNode ) {
  8655. this._updateBindings( this.getForCompute( computeNode ) );
  8656. }
  8657. updateForRender( renderObject ) {
  8658. this._updateBindings( this.getForRender( renderObject ) );
  8659. }
  8660. _updateBindings( bindings ) {
  8661. for ( const bindGroup of bindings ) {
  8662. this._update( bindGroup, bindings );
  8663. }
  8664. }
  8665. _init( bindGroup ) {
  8666. for ( const binding of bindGroup.bindings ) {
  8667. if ( binding.isSampledTexture ) {
  8668. this.textures.updateTexture( binding.texture );
  8669. } else if ( binding.isStorageBuffer ) {
  8670. const attribute = binding.attribute;
  8671. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  8672. this.attributes.update( attribute, attributeType );
  8673. }
  8674. }
  8675. }
  8676. _update( bindGroup, bindings ) {
  8677. const { backend } = this;
  8678. let needsBindingsUpdate = false;
  8679. let cacheBindings = true;
  8680. let cacheIndex = 0;
  8681. let version = 0;
  8682. // iterate over all bindings and check if buffer updates or a new binding group is required
  8683. for ( const binding of bindGroup.bindings ) {
  8684. if ( binding.isNodeUniformsGroup ) {
  8685. const updated = this.nodes.updateGroup( binding );
  8686. if ( ! updated ) continue;
  8687. }
  8688. if ( binding.isUniformBuffer ) {
  8689. const updated = binding.update();
  8690. if ( updated ) {
  8691. backend.updateBinding( binding );
  8692. }
  8693. } else if ( binding.isSampler ) {
  8694. binding.update();
  8695. } else if ( binding.isSampledTexture ) {
  8696. const texturesTextureData = this.textures.get( binding.texture );
  8697. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  8698. const updated = binding.update();
  8699. const texture = binding.texture;
  8700. if ( updated ) {
  8701. this.textures.updateTexture( texture );
  8702. }
  8703. const textureData = backend.get( texture );
  8704. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  8705. cacheBindings = false;
  8706. } else {
  8707. cacheIndex = cacheIndex * 10 + texture.id;
  8708. version += texture.version;
  8709. }
  8710. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  8711. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  8712. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  8713. this.textures.updateTexture( texture );
  8714. needsBindingsUpdate = true;
  8715. }
  8716. if ( texture.isStorageTexture === true ) {
  8717. const textureData = this.get( texture );
  8718. if ( binding.store === true ) {
  8719. textureData.needsMipmap = true;
  8720. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  8721. this.backend.generateMipmaps( texture );
  8722. textureData.needsMipmap = false;
  8723. }
  8724. }
  8725. }
  8726. }
  8727. if ( needsBindingsUpdate === true ) {
  8728. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  8729. }
  8730. }
  8731. }
  8732. function painterSortStable( a, b ) {
  8733. if ( a.groupOrder !== b.groupOrder ) {
  8734. return a.groupOrder - b.groupOrder;
  8735. } else if ( a.renderOrder !== b.renderOrder ) {
  8736. return a.renderOrder - b.renderOrder;
  8737. } else if ( a.material.id !== b.material.id ) {
  8738. return a.material.id - b.material.id;
  8739. } else if ( a.z !== b.z ) {
  8740. return a.z - b.z;
  8741. } else {
  8742. return a.id - b.id;
  8743. }
  8744. }
  8745. function reversePainterSortStable( a, b ) {
  8746. if ( a.groupOrder !== b.groupOrder ) {
  8747. return a.groupOrder - b.groupOrder;
  8748. } else if ( a.renderOrder !== b.renderOrder ) {
  8749. return a.renderOrder - b.renderOrder;
  8750. } else if ( a.z !== b.z ) {
  8751. return b.z - a.z;
  8752. } else {
  8753. return a.id - b.id;
  8754. }
  8755. }
  8756. function needsDoublePass( material ) {
  8757. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  8758. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  8759. }
  8760. class RenderList {
  8761. constructor( lighting, scene, camera ) {
  8762. this.renderItems = [];
  8763. this.renderItemsIndex = 0;
  8764. this.opaque = [];
  8765. this.transparentDoublePass = [];
  8766. this.transparent = [];
  8767. this.bundles = [];
  8768. this.lightsNode = lighting.getNode( scene, camera );
  8769. this.lightsArray = [];
  8770. this.scene = scene;
  8771. this.camera = camera;
  8772. this.occlusionQueryCount = 0;
  8773. }
  8774. begin() {
  8775. this.renderItemsIndex = 0;
  8776. this.opaque.length = 0;
  8777. this.transparentDoublePass.length = 0;
  8778. this.transparent.length = 0;
  8779. this.bundles.length = 0;
  8780. this.lightsArray.length = 0;
  8781. this.occlusionQueryCount = 0;
  8782. return this;
  8783. }
  8784. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8785. let renderItem = this.renderItems[ this.renderItemsIndex ];
  8786. if ( renderItem === undefined ) {
  8787. renderItem = {
  8788. id: object.id,
  8789. object: object,
  8790. geometry: geometry,
  8791. material: material,
  8792. groupOrder: groupOrder,
  8793. renderOrder: object.renderOrder,
  8794. z: z,
  8795. group: group,
  8796. clippingContext: clippingContext
  8797. };
  8798. this.renderItems[ this.renderItemsIndex ] = renderItem;
  8799. } else {
  8800. renderItem.id = object.id;
  8801. renderItem.object = object;
  8802. renderItem.geometry = geometry;
  8803. renderItem.material = material;
  8804. renderItem.groupOrder = groupOrder;
  8805. renderItem.renderOrder = object.renderOrder;
  8806. renderItem.z = z;
  8807. renderItem.group = group;
  8808. renderItem.clippingContext = clippingContext;
  8809. }
  8810. this.renderItemsIndex ++;
  8811. return renderItem;
  8812. }
  8813. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8814. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8815. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  8816. if ( material.transparent === true || material.transmission > 0 ) {
  8817. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  8818. this.transparent.push( renderItem );
  8819. } else {
  8820. this.opaque.push( renderItem );
  8821. }
  8822. }
  8823. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8824. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8825. if ( material.transparent === true || material.transmission > 0 ) {
  8826. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  8827. this.transparent.unshift( renderItem );
  8828. } else {
  8829. this.opaque.unshift( renderItem );
  8830. }
  8831. }
  8832. pushBundle( group ) {
  8833. this.bundles.push( group );
  8834. }
  8835. pushLight( light ) {
  8836. this.lightsArray.push( light );
  8837. }
  8838. sort( customOpaqueSort, customTransparentSort ) {
  8839. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  8840. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  8841. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  8842. }
  8843. finish() {
  8844. // update lights
  8845. this.lightsNode.setLights( this.lightsArray );
  8846. // Clear references from inactive renderItems in the list
  8847. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  8848. const renderItem = this.renderItems[ i ];
  8849. if ( renderItem.id === null ) break;
  8850. renderItem.id = null;
  8851. renderItem.object = null;
  8852. renderItem.geometry = null;
  8853. renderItem.material = null;
  8854. renderItem.groupOrder = null;
  8855. renderItem.renderOrder = null;
  8856. renderItem.z = null;
  8857. renderItem.group = null;
  8858. renderItem.clippingContext = null;
  8859. }
  8860. }
  8861. }
  8862. class RenderLists {
  8863. constructor( lighting ) {
  8864. this.lighting = lighting;
  8865. this.lists = new ChainMap();
  8866. }
  8867. get( scene, camera ) {
  8868. const lists = this.lists;
  8869. const keys = [ scene, camera ];
  8870. let list = lists.get( keys );
  8871. if ( list === undefined ) {
  8872. list = new RenderList( this.lighting, scene, camera );
  8873. lists.set( keys, list );
  8874. }
  8875. return list;
  8876. }
  8877. dispose() {
  8878. this.lists = new ChainMap();
  8879. }
  8880. }
  8881. let id$1 = 0;
  8882. class RenderContext {
  8883. constructor() {
  8884. this.id = id$1 ++;
  8885. this.color = true;
  8886. this.clearColor = true;
  8887. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  8888. this.depth = true;
  8889. this.clearDepth = true;
  8890. this.clearDepthValue = 1;
  8891. this.stencil = false;
  8892. this.clearStencil = true;
  8893. this.clearStencilValue = 1;
  8894. this.viewport = false;
  8895. this.viewportValue = new Vector4();
  8896. this.scissor = false;
  8897. this.scissorValue = new Vector4();
  8898. this.textures = null;
  8899. this.depthTexture = null;
  8900. this.activeCubeFace = 0;
  8901. this.sampleCount = 1;
  8902. this.width = 0;
  8903. this.height = 0;
  8904. this.isRenderContext = true;
  8905. }
  8906. getCacheKey() {
  8907. return getCacheKey( this );
  8908. }
  8909. }
  8910. function getCacheKey( renderContext ) {
  8911. const { textures, activeCubeFace } = renderContext;
  8912. const values = [ activeCubeFace ];
  8913. for ( const texture of textures ) {
  8914. values.push( texture.id );
  8915. }
  8916. return hashArray( values );
  8917. }
  8918. class RenderContexts {
  8919. constructor() {
  8920. this.chainMaps = {};
  8921. }
  8922. get( scene, camera, renderTarget = null ) {
  8923. const chainKey = [ scene, camera ];
  8924. let attachmentState;
  8925. if ( renderTarget === null ) {
  8926. attachmentState = 'default';
  8927. } else {
  8928. const format = renderTarget.texture.format;
  8929. const count = renderTarget.textures.length;
  8930. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  8931. }
  8932. const chainMap = this.getChainMap( attachmentState );
  8933. let renderState = chainMap.get( chainKey );
  8934. if ( renderState === undefined ) {
  8935. renderState = new RenderContext();
  8936. chainMap.set( chainKey, renderState );
  8937. }
  8938. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8939. return renderState;
  8940. }
  8941. getChainMap( attachmentState ) {
  8942. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  8943. }
  8944. dispose() {
  8945. this.chainMaps = {};
  8946. }
  8947. }
  8948. const _size$3 = /*@__PURE__*/ new Vector3();
  8949. class Textures extends DataMap {
  8950. constructor( renderer, backend, info ) {
  8951. super();
  8952. this.renderer = renderer;
  8953. this.backend = backend;
  8954. this.info = info;
  8955. }
  8956. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  8957. const renderTargetData = this.get( renderTarget );
  8958. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8959. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  8960. const textures = renderTarget.textures;
  8961. const size = this.getSize( textures[ 0 ] );
  8962. const mipWidth = size.width >> activeMipmapLevel;
  8963. const mipHeight = size.height >> activeMipmapLevel;
  8964. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  8965. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  8966. let textureNeedsUpdate = false;
  8967. if ( depthTexture === undefined && useDepthTexture ) {
  8968. depthTexture = new DepthTexture();
  8969. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  8970. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  8971. depthTexture.image.width = mipWidth;
  8972. depthTexture.image.height = mipHeight;
  8973. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  8974. }
  8975. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  8976. textureNeedsUpdate = true;
  8977. if ( depthTexture ) {
  8978. depthTexture.needsUpdate = true;
  8979. depthTexture.image.width = mipWidth;
  8980. depthTexture.image.height = mipHeight;
  8981. }
  8982. }
  8983. renderTargetData.width = size.width;
  8984. renderTargetData.height = size.height;
  8985. renderTargetData.textures = textures;
  8986. renderTargetData.depthTexture = depthTexture || null;
  8987. renderTargetData.depth = renderTarget.depthBuffer;
  8988. renderTargetData.stencil = renderTarget.stencilBuffer;
  8989. renderTargetData.renderTarget = renderTarget;
  8990. if ( renderTargetData.sampleCount !== sampleCount ) {
  8991. textureNeedsUpdate = true;
  8992. if ( depthTexture ) {
  8993. depthTexture.needsUpdate = true;
  8994. }
  8995. renderTargetData.sampleCount = sampleCount;
  8996. }
  8997. //
  8998. const options = { sampleCount };
  8999. for ( let i = 0; i < textures.length; i ++ ) {
  9000. const texture = textures[ i ];
  9001. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  9002. this.updateTexture( texture, options );
  9003. }
  9004. if ( depthTexture ) {
  9005. this.updateTexture( depthTexture, options );
  9006. }
  9007. // dispose handler
  9008. if ( renderTargetData.initialized !== true ) {
  9009. renderTargetData.initialized = true;
  9010. // dispose
  9011. const onDispose = () => {
  9012. renderTarget.removeEventListener( 'dispose', onDispose );
  9013. for ( let i = 0; i < textures.length; i ++ ) {
  9014. this._destroyTexture( textures[ i ] );
  9015. }
  9016. if ( depthTexture ) {
  9017. this._destroyTexture( depthTexture );
  9018. }
  9019. this.delete( renderTarget );
  9020. };
  9021. renderTarget.addEventListener( 'dispose', onDispose );
  9022. }
  9023. }
  9024. updateTexture( texture, options = {} ) {
  9025. const textureData = this.get( texture );
  9026. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  9027. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  9028. const backend = this.backend;
  9029. if ( isRenderTarget && textureData.initialized === true ) {
  9030. // it's an update
  9031. backend.destroySampler( texture );
  9032. backend.destroyTexture( texture );
  9033. }
  9034. //
  9035. if ( texture.isFramebufferTexture ) {
  9036. const renderTarget = this.renderer.getRenderTarget();
  9037. if ( renderTarget ) {
  9038. texture.type = renderTarget.texture.type;
  9039. } else {
  9040. texture.type = UnsignedByteType;
  9041. }
  9042. }
  9043. //
  9044. const { width, height, depth } = this.getSize( texture );
  9045. options.width = width;
  9046. options.height = height;
  9047. options.depth = depth;
  9048. options.needsMipmaps = this.needsMipmaps( texture );
  9049. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  9050. //
  9051. if ( isRenderTarget || texture.isStorageTexture === true ) {
  9052. backend.createSampler( texture );
  9053. backend.createTexture( texture, options );
  9054. textureData.generation = texture.version;
  9055. } else {
  9056. const needsCreate = textureData.initialized !== true;
  9057. if ( needsCreate ) backend.createSampler( texture );
  9058. if ( texture.version > 0 ) {
  9059. const image = texture.image;
  9060. if ( image === undefined ) {
  9061. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  9062. } else if ( image.complete === false ) {
  9063. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  9064. } else {
  9065. if ( texture.images ) {
  9066. const images = [];
  9067. for ( const image of texture.images ) {
  9068. images.push( image );
  9069. }
  9070. options.images = images;
  9071. } else {
  9072. options.image = image;
  9073. }
  9074. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  9075. backend.createTexture( texture, options );
  9076. textureData.isDefaultTexture = false;
  9077. textureData.generation = texture.version;
  9078. }
  9079. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  9080. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  9081. }
  9082. } else {
  9083. // async update
  9084. backend.createDefaultTexture( texture );
  9085. textureData.isDefaultTexture = true;
  9086. textureData.generation = texture.version;
  9087. }
  9088. }
  9089. // dispose handler
  9090. if ( textureData.initialized !== true ) {
  9091. textureData.initialized = true;
  9092. textureData.generation = texture.version;
  9093. //
  9094. this.info.memory.textures ++;
  9095. // dispose
  9096. const onDispose = () => {
  9097. texture.removeEventListener( 'dispose', onDispose );
  9098. this._destroyTexture( texture );
  9099. this.info.memory.textures --;
  9100. };
  9101. texture.addEventListener( 'dispose', onDispose );
  9102. }
  9103. //
  9104. textureData.version = texture.version;
  9105. }
  9106. getSize( texture, target = _size$3 ) {
  9107. let image = texture.images ? texture.images[ 0 ] : texture.image;
  9108. if ( image ) {
  9109. if ( image.image !== undefined ) image = image.image;
  9110. target.width = image.width || 1;
  9111. target.height = image.height || 1;
  9112. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  9113. } else {
  9114. target.width = target.height = target.depth = 1;
  9115. }
  9116. return target;
  9117. }
  9118. getMipLevels( texture, width, height ) {
  9119. let mipLevelCount;
  9120. if ( texture.isCompressedTexture ) {
  9121. if ( texture.mipmaps ) {
  9122. mipLevelCount = texture.mipmaps.length;
  9123. } else {
  9124. mipLevelCount = 1;
  9125. }
  9126. } else {
  9127. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  9128. }
  9129. return mipLevelCount;
  9130. }
  9131. needsMipmaps( texture ) {
  9132. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  9133. }
  9134. isEnvironmentTexture( texture ) {
  9135. const mapping = texture.mapping;
  9136. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9137. }
  9138. _destroyTexture( texture ) {
  9139. this.backend.destroySampler( texture );
  9140. this.backend.destroyTexture( texture );
  9141. this.delete( texture );
  9142. }
  9143. }
  9144. class Color4 extends Color {
  9145. constructor( r, g, b, a = 1 ) {
  9146. super( r, g, b );
  9147. this.a = a;
  9148. }
  9149. set( r, g, b, a = 1 ) {
  9150. this.a = a;
  9151. return super.set( r, g, b );
  9152. }
  9153. copy( color ) {
  9154. if ( color.a !== undefined ) this.a = color.a;
  9155. return super.copy( color );
  9156. }
  9157. clone() {
  9158. return new this.constructor( this.r, this.g, this.b, this.a );
  9159. }
  9160. }
  9161. class ParameterNode extends PropertyNode {
  9162. static get type() {
  9163. return 'ParameterNode';
  9164. }
  9165. constructor( nodeType, name = null ) {
  9166. super( nodeType, name );
  9167. this.isParameterNode = true;
  9168. }
  9169. getHash() {
  9170. return this.uuid;
  9171. }
  9172. generate() {
  9173. return this.name;
  9174. }
  9175. }
  9176. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  9177. class StackNode extends Node {
  9178. static get type() {
  9179. return 'StackNode';
  9180. }
  9181. constructor( parent = null ) {
  9182. super();
  9183. this.nodes = [];
  9184. this.outputNode = null;
  9185. this.parent = parent;
  9186. this._currentCond = null;
  9187. this.isStackNode = true;
  9188. }
  9189. getNodeType( builder ) {
  9190. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  9191. }
  9192. add( node ) {
  9193. this.nodes.push( node );
  9194. return this;
  9195. }
  9196. If( boolNode, method ) {
  9197. const methodNode = new ShaderNode( method );
  9198. this._currentCond = select( boolNode, methodNode );
  9199. return this.add( this._currentCond );
  9200. }
  9201. ElseIf( boolNode, method ) {
  9202. const methodNode = new ShaderNode( method );
  9203. const ifNode = select( boolNode, methodNode );
  9204. this._currentCond.elseNode = ifNode;
  9205. this._currentCond = ifNode;
  9206. return this;
  9207. }
  9208. Else( method ) {
  9209. this._currentCond.elseNode = new ShaderNode( method );
  9210. return this;
  9211. }
  9212. build( builder, ...params ) {
  9213. const previousStack = getCurrentStack();
  9214. setCurrentStack( this );
  9215. for ( const node of this.nodes ) {
  9216. node.build( builder, 'void' );
  9217. }
  9218. setCurrentStack( previousStack );
  9219. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  9220. }
  9221. //
  9222. else( ...params ) { // @deprecated, r168
  9223. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  9224. return this.Else( ...params );
  9225. }
  9226. elseif( ...params ) { // @deprecated, r168
  9227. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  9228. return this.ElseIf( ...params );
  9229. }
  9230. }
  9231. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  9232. class StructTypeNode extends Node {
  9233. static get type() {
  9234. return 'StructTypeNode';
  9235. }
  9236. constructor( types ) {
  9237. super();
  9238. this.types = types;
  9239. this.isStructTypeNode = true;
  9240. }
  9241. getMemberTypes() {
  9242. return this.types;
  9243. }
  9244. }
  9245. class OutputStructNode extends Node {
  9246. static get type() {
  9247. return 'OutputStructNode';
  9248. }
  9249. constructor( ...members ) {
  9250. super();
  9251. this.members = members;
  9252. this.isOutputStructNode = true;
  9253. }
  9254. setup( builder ) {
  9255. super.setup( builder );
  9256. const members = this.members;
  9257. const types = [];
  9258. for ( let i = 0; i < members.length; i ++ ) {
  9259. types.push( members[ i ].getNodeType( builder ) );
  9260. }
  9261. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  9262. }
  9263. generate( builder, output ) {
  9264. const propertyName = builder.getOutputStructName();
  9265. const members = this.members;
  9266. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  9267. for ( let i = 0; i < members.length; i ++ ) {
  9268. const snippet = members[ i ].build( builder, output );
  9269. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  9270. }
  9271. return propertyName;
  9272. }
  9273. }
  9274. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  9275. function getTextureIndex( textures, name ) {
  9276. for ( let i = 0; i < textures.length; i ++ ) {
  9277. if ( textures[ i ].name === name ) {
  9278. return i;
  9279. }
  9280. }
  9281. return - 1;
  9282. }
  9283. class MRTNode extends OutputStructNode {
  9284. static get type() {
  9285. return 'MRTNode';
  9286. }
  9287. constructor( outputNodes ) {
  9288. super();
  9289. this.outputNodes = outputNodes;
  9290. this.isMRTNode = true;
  9291. }
  9292. has( name ) {
  9293. return this.outputNodes[ name ] !== undefined;
  9294. }
  9295. get( name ) {
  9296. return this.outputNodes[ name ];
  9297. }
  9298. merge( mrtNode ) {
  9299. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  9300. return mrt( outputs );
  9301. }
  9302. setup( builder ) {
  9303. const outputNodes = this.outputNodes;
  9304. const mrt = builder.renderer.getRenderTarget();
  9305. const members = [];
  9306. const textures = mrt.textures;
  9307. for ( const name in outputNodes ) {
  9308. const index = getTextureIndex( textures, name );
  9309. members[ index ] = vec4( outputNodes[ name ] );
  9310. }
  9311. this.members = members;
  9312. return super.setup( builder );
  9313. }
  9314. }
  9315. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  9316. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  9317. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  9318. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  9319. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  9320. const result = word.shiftRight( 22 ).bitXor( word );
  9321. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  9322. } );
  9323. // remapping functions https://iquilezles.org/articles/functions/
  9324. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  9325. 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 ) );
  9326. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  9327. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  9328. // https://github.com/cabbibo/glsl-tri-noise-3d
  9329. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  9330. return x.fract().sub( .5 ).abs();
  9331. } ).setLayout( {
  9332. name: 'tri',
  9333. type: 'float',
  9334. inputs: [
  9335. { name: 'x', type: 'float' }
  9336. ]
  9337. } );
  9338. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  9339. 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. ) ) ) ) );
  9340. } ).setLayout( {
  9341. name: 'tri3',
  9342. type: 'vec3',
  9343. inputs: [
  9344. { name: 'p', type: 'vec3' }
  9345. ]
  9346. } );
  9347. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  9348. const p = vec3( p_immutable ).toVar();
  9349. const z = float( 1.4 ).toVar();
  9350. const rz = float( 0.0 ).toVar();
  9351. const bp = vec3( p ).toVar();
  9352. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  9353. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  9354. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  9355. bp.mulAssign( 1.8 );
  9356. z.mulAssign( 1.5 );
  9357. p.mulAssign( 1.2 );
  9358. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  9359. rz.addAssign( t.div( z ) );
  9360. bp.addAssign( 0.14 );
  9361. } );
  9362. return rz;
  9363. } ).setLayout( {
  9364. name: 'triNoise3D',
  9365. type: 'float',
  9366. inputs: [
  9367. { name: 'p', type: 'vec3' },
  9368. { name: 'spd', type: 'float' },
  9369. { name: 'time', type: 'float' }
  9370. ]
  9371. } );
  9372. class FunctionOverloadingNode extends Node {
  9373. static get type() {
  9374. return 'FunctionOverloadingNode';
  9375. }
  9376. constructor( functionNodes = [], ...parametersNodes ) {
  9377. super();
  9378. this.functionNodes = functionNodes;
  9379. this.parametersNodes = parametersNodes;
  9380. this._candidateFnCall = null;
  9381. this.global = true;
  9382. }
  9383. getNodeType() {
  9384. return this.functionNodes[ 0 ].shaderNode.layout.type;
  9385. }
  9386. setup( builder ) {
  9387. const params = this.parametersNodes;
  9388. let candidateFnCall = this._candidateFnCall;
  9389. if ( candidateFnCall === null ) {
  9390. let candidateFn = null;
  9391. let candidateScore = - 1;
  9392. for ( const functionNode of this.functionNodes ) {
  9393. const shaderNode = functionNode.shaderNode;
  9394. const layout = shaderNode.layout;
  9395. if ( layout === null ) {
  9396. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  9397. }
  9398. const inputs = layout.inputs;
  9399. if ( params.length === inputs.length ) {
  9400. let score = 0;
  9401. for ( let i = 0; i < params.length; i ++ ) {
  9402. const param = params[ i ];
  9403. const input = inputs[ i ];
  9404. if ( param.getNodeType( builder ) === input.type ) {
  9405. score ++;
  9406. } else {
  9407. score = 0;
  9408. }
  9409. }
  9410. if ( score > candidateScore ) {
  9411. candidateFn = functionNode;
  9412. candidateScore = score;
  9413. }
  9414. }
  9415. }
  9416. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  9417. }
  9418. return candidateFnCall;
  9419. }
  9420. }
  9421. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  9422. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  9423. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  9424. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  9425. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  9426. // Deprecated
  9427. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  9428. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  9429. return time.mul( timeScale );
  9430. };
  9431. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  9432. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  9433. return time.mul( timeScale );
  9434. };
  9435. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  9436. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  9437. return deltaTime.mul( timeScale );
  9438. };
  9439. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  9440. const oscSquare = ( t = time ) => t.fract().round();
  9441. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  9442. const oscSawtooth = ( t = time ) => t.fract();
  9443. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  9444. return rotate( uv.sub( center ), rotation ).add( center );
  9445. } );
  9446. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  9447. const delta = uv.sub( center );
  9448. const delta2 = delta.dot( delta );
  9449. const delta4 = delta2.mul( delta2 );
  9450. const deltaOffset = delta4.mul( strength );
  9451. return uv.add( delta.mul( deltaOffset ) );
  9452. } );
  9453. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  9454. let worldMatrix;
  9455. if ( position !== null ) {
  9456. worldMatrix = modelWorldMatrix.toVar();
  9457. worldMatrix[ 3 ][ 0 ] = position.x;
  9458. worldMatrix[ 3 ][ 1 ] = position.y;
  9459. worldMatrix[ 3 ][ 2 ] = position.z;
  9460. } else {
  9461. worldMatrix = modelWorldMatrix;
  9462. }
  9463. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  9464. if ( defined( horizontal ) ) {
  9465. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  9466. modelViewMatrix[ 0 ][ 1 ] = 0;
  9467. modelViewMatrix[ 0 ][ 2 ] = 0;
  9468. }
  9469. if ( defined( vertical ) ) {
  9470. modelViewMatrix[ 1 ][ 0 ] = 0;
  9471. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  9472. modelViewMatrix[ 1 ][ 2 ] = 0;
  9473. }
  9474. modelViewMatrix[ 2 ][ 0 ] = 0;
  9475. modelViewMatrix[ 2 ][ 1 ] = 0;
  9476. modelViewMatrix[ 2 ][ 2 ] = 1;
  9477. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  9478. } );
  9479. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  9480. const depth = linearDepth();
  9481. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  9482. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  9483. return finalUV;
  9484. } );
  9485. class SpriteSheetUVNode extends Node {
  9486. static get type() {
  9487. return 'SpriteSheetUVNode';
  9488. }
  9489. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  9490. super( 'vec2' );
  9491. this.countNode = countNode;
  9492. this.uvNode = uvNode;
  9493. this.frameNode = frameNode;
  9494. }
  9495. setup() {
  9496. const { frameNode, uvNode, countNode } = this;
  9497. const { width, height } = countNode;
  9498. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  9499. const column = frameNum.mod( width );
  9500. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  9501. const scale = countNode.reciprocal();
  9502. const uvFrameOffset = vec2( column, row );
  9503. return uvNode.add( uvFrameOffset ).mul( scale );
  9504. }
  9505. }
  9506. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  9507. class TriplanarTexturesNode extends Node {
  9508. static get type() {
  9509. return 'TriplanarTexturesNode';
  9510. }
  9511. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  9512. super( 'vec4' );
  9513. this.textureXNode = textureXNode;
  9514. this.textureYNode = textureYNode;
  9515. this.textureZNode = textureZNode;
  9516. this.scaleNode = scaleNode;
  9517. this.positionNode = positionNode;
  9518. this.normalNode = normalNode;
  9519. }
  9520. setup() {
  9521. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  9522. // Ref: https://github.com/keijiro/StandardTriplanar
  9523. // Blending factor of triplanar mapping
  9524. let bf = normalNode.abs().normalize();
  9525. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  9526. // Triplanar mapping
  9527. const tx = positionNode.yz.mul( scaleNode );
  9528. const ty = positionNode.zx.mul( scaleNode );
  9529. const tz = positionNode.xy.mul( scaleNode );
  9530. // Base color
  9531. const textureX = textureXNode.value;
  9532. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  9533. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  9534. const cx = texture( textureX, tx ).mul( bf.x );
  9535. const cy = texture( textureY, ty ).mul( bf.y );
  9536. const cz = texture( textureZ, tz ).mul( bf.z );
  9537. return add( cx, cy, cz );
  9538. }
  9539. }
  9540. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  9541. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  9542. const _reflectorPlane = new Plane();
  9543. const _normal = new Vector3();
  9544. const _reflectorWorldPosition = new Vector3();
  9545. const _cameraWorldPosition = new Vector3();
  9546. const _rotationMatrix = new Matrix4();
  9547. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  9548. const clipPlane = new Vector4();
  9549. const _view = new Vector3();
  9550. const _target = new Vector3();
  9551. const _q = new Vector4();
  9552. const _size$2 = new Vector2();
  9553. const _defaultRT = new RenderTarget();
  9554. const _defaultUV = screenUV.flipX();
  9555. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  9556. let _inReflector = false;
  9557. class ReflectorNode extends TextureNode {
  9558. static get type() {
  9559. return 'ReflectorNode';
  9560. }
  9561. constructor( parameters = {} ) {
  9562. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  9563. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  9564. this._depthNode = null;
  9565. this.setUpdateMatrix( false );
  9566. }
  9567. get reflector() {
  9568. return this._reflectorBaseNode;
  9569. }
  9570. get target() {
  9571. return this._reflectorBaseNode.target;
  9572. }
  9573. getDepthNode() {
  9574. if ( this._depthNode === null ) {
  9575. if ( this._reflectorBaseNode.depth !== true ) {
  9576. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  9577. }
  9578. this._depthNode = nodeObject( new ReflectorNode( {
  9579. defaultTexture: _defaultRT.depthTexture,
  9580. reflector: this._reflectorBaseNode
  9581. } ) );
  9582. }
  9583. return this._depthNode;
  9584. }
  9585. setup( builder ) {
  9586. // ignore if used in post-processing
  9587. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  9588. return super.setup( builder );
  9589. }
  9590. clone() {
  9591. const texture = new this.constructor( this.reflectorNode );
  9592. texture._reflectorBaseNode = this._reflectorBaseNode;
  9593. return texture;
  9594. }
  9595. }
  9596. class ReflectorBaseNode extends Node {
  9597. static get type() {
  9598. return 'ReflectorBaseNode';
  9599. }
  9600. constructor( textureNode, parameters = {} ) {
  9601. super();
  9602. const {
  9603. target = new Object3D(),
  9604. resolution = 1,
  9605. generateMipmaps = false,
  9606. bounces = true,
  9607. depth = false
  9608. } = parameters;
  9609. //
  9610. this.textureNode = textureNode;
  9611. this.target = target;
  9612. this.resolution = resolution;
  9613. this.generateMipmaps = generateMipmaps;
  9614. this.bounces = bounces;
  9615. this.depth = depth;
  9616. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  9617. this.virtualCameras = new WeakMap();
  9618. this.renderTargets = new WeakMap();
  9619. }
  9620. _updateResolution( renderTarget, renderer ) {
  9621. const resolution = this.resolution;
  9622. renderer.getDrawingBufferSize( _size$2 );
  9623. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  9624. }
  9625. setup( builder ) {
  9626. this._updateResolution( _defaultRT, builder.renderer );
  9627. return super.setup( builder );
  9628. }
  9629. getVirtualCamera( camera ) {
  9630. let virtualCamera = this.virtualCameras.get( camera );
  9631. if ( virtualCamera === undefined ) {
  9632. virtualCamera = camera.clone();
  9633. this.virtualCameras.set( camera, virtualCamera );
  9634. }
  9635. return virtualCamera;
  9636. }
  9637. getRenderTarget( camera ) {
  9638. let renderTarget = this.renderTargets.get( camera );
  9639. if ( renderTarget === undefined ) {
  9640. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  9641. if ( this.generateMipmaps === true ) {
  9642. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  9643. renderTarget.texture.generateMipmaps = true;
  9644. }
  9645. if ( this.depth === true ) {
  9646. renderTarget.depthTexture = new DepthTexture();
  9647. }
  9648. this.renderTargets.set( camera, renderTarget );
  9649. }
  9650. return renderTarget;
  9651. }
  9652. updateBefore( frame ) {
  9653. if ( this.bounces === false && _inReflector ) return;
  9654. _inReflector = true;
  9655. const { scene, camera, renderer, material } = frame;
  9656. const { target } = this;
  9657. const virtualCamera = this.getVirtualCamera( camera );
  9658. const renderTarget = this.getRenderTarget( virtualCamera );
  9659. renderer.getDrawingBufferSize( _size$2 );
  9660. this._updateResolution( renderTarget, renderer );
  9661. //
  9662. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  9663. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  9664. _rotationMatrix.extractRotation( target.matrixWorld );
  9665. _normal.set( 0, 0, 1 );
  9666. _normal.applyMatrix4( _rotationMatrix );
  9667. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  9668. // Avoid rendering when reflector is facing away
  9669. if ( _view.dot( _normal ) > 0 ) return;
  9670. _view.reflect( _normal ).negate();
  9671. _view.add( _reflectorWorldPosition );
  9672. _rotationMatrix.extractRotation( camera.matrixWorld );
  9673. _lookAtPosition.set( 0, 0, - 1 );
  9674. _lookAtPosition.applyMatrix4( _rotationMatrix );
  9675. _lookAtPosition.add( _cameraWorldPosition );
  9676. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  9677. _target.reflect( _normal ).negate();
  9678. _target.add( _reflectorWorldPosition );
  9679. //
  9680. virtualCamera.coordinateSystem = camera.coordinateSystem;
  9681. virtualCamera.position.copy( _view );
  9682. virtualCamera.up.set( 0, 1, 0 );
  9683. virtualCamera.up.applyMatrix4( _rotationMatrix );
  9684. virtualCamera.up.reflect( _normal );
  9685. virtualCamera.lookAt( _target );
  9686. virtualCamera.near = camera.near;
  9687. virtualCamera.far = camera.far;
  9688. virtualCamera.updateMatrixWorld();
  9689. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  9690. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  9691. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  9692. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  9693. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  9694. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  9695. const projectionMatrix = virtualCamera.projectionMatrix;
  9696. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  9697. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  9698. _q.z = - 1.0;
  9699. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  9700. // Calculate the scaled plane vector
  9701. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  9702. const clipBias = 0;
  9703. // Replacing the third row of the projection matrix
  9704. projectionMatrix.elements[ 2 ] = clipPlane.x;
  9705. projectionMatrix.elements[ 6 ] = clipPlane.y;
  9706. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  9707. projectionMatrix.elements[ 14 ] = clipPlane.w;
  9708. //
  9709. this.textureNode.value = renderTarget.texture;
  9710. if ( this.depth === true ) {
  9711. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  9712. }
  9713. material.visible = false;
  9714. const currentRenderTarget = renderer.getRenderTarget();
  9715. const currentMRT = renderer.getMRT();
  9716. renderer.setMRT( null );
  9717. renderer.setRenderTarget( renderTarget );
  9718. renderer.render( scene, virtualCamera );
  9719. renderer.setMRT( currentMRT );
  9720. renderer.setRenderTarget( currentRenderTarget );
  9721. material.visible = true;
  9722. _inReflector = false;
  9723. }
  9724. }
  9725. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  9726. // Helper for passes that need to fill the viewport with a single quad.
  9727. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9728. // https://github.com/mrdoob/three.js/pull/21358
  9729. class QuadGeometry extends BufferGeometry {
  9730. constructor( flipY = false ) {
  9731. super();
  9732. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  9733. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  9734. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  9735. }
  9736. }
  9737. const _geometry = /*@__PURE__*/ new QuadGeometry();
  9738. class QuadMesh extends Mesh {
  9739. constructor( material = null ) {
  9740. super( _geometry, material );
  9741. this.camera = _camera;
  9742. this.isQuadMesh = true;
  9743. }
  9744. renderAsync( renderer ) {
  9745. return renderer.renderAsync( this, _camera );
  9746. }
  9747. render( renderer ) {
  9748. renderer.render( this, _camera );
  9749. }
  9750. }
  9751. const _size$1 = /*@__PURE__*/ new Vector2();
  9752. class RTTNode extends TextureNode {
  9753. static get type() {
  9754. return 'RTTNode';
  9755. }
  9756. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  9757. const renderTarget = new RenderTarget( width, height, options );
  9758. super( renderTarget.texture, uv() );
  9759. this.node = node;
  9760. this.width = width;
  9761. this.height = height;
  9762. this.renderTarget = renderTarget;
  9763. this.textureNeedsUpdate = true;
  9764. this.autoUpdate = true;
  9765. this.updateMap = new WeakMap();
  9766. this._rttNode = null;
  9767. this._quadMesh = new QuadMesh( new NodeMaterial() );
  9768. this.updateBeforeType = NodeUpdateType.RENDER;
  9769. }
  9770. get autoSize() {
  9771. return this.width === null;
  9772. }
  9773. setup( builder ) {
  9774. this._rttNode = this.node.context( builder.getSharedContext() );
  9775. this._quadMesh.material.name = 'RTT';
  9776. this._quadMesh.material.needsUpdate = true;
  9777. return super.setup( builder );
  9778. }
  9779. setSize( width, height ) {
  9780. this.width = width;
  9781. this.height = height;
  9782. const effectiveWidth = width * this.pixelRatio;
  9783. const effectiveHeight = height * this.pixelRatio;
  9784. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  9785. this.textureNeedsUpdate = true;
  9786. }
  9787. setPixelRatio( pixelRatio ) {
  9788. this.pixelRatio = pixelRatio;
  9789. this.setSize( this.width, this.height );
  9790. }
  9791. updateBefore( { renderer } ) {
  9792. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  9793. this.textureNeedsUpdate = false;
  9794. //
  9795. if ( this.autoSize === true ) {
  9796. this.pixelRatio = renderer.getPixelRatio();
  9797. const size = renderer.getSize( _size$1 );
  9798. this.setSize( size.width, size.height );
  9799. }
  9800. //
  9801. this._quadMesh.material.fragmentNode = this._rttNode;
  9802. //
  9803. const currentRenderTarget = renderer.getRenderTarget();
  9804. renderer.setRenderTarget( this.renderTarget );
  9805. this._quadMesh.render( renderer );
  9806. renderer.setRenderTarget( currentRenderTarget );
  9807. }
  9808. clone() {
  9809. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  9810. newNode.sampler = this.sampler;
  9811. newNode.referenceNode = this;
  9812. return newNode;
  9813. }
  9814. }
  9815. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  9816. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  9817. /**
  9818. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  9819. * depth value and the camera's inverse projection matrix.
  9820. *
  9821. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  9822. * @param {float} depth - The fragment's depth value.
  9823. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9824. * @return {vec3} The fragments position in view space.
  9825. */
  9826. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  9827. let clipSpacePosition;
  9828. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  9829. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  9830. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  9831. } else {
  9832. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  9833. }
  9834. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  9835. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  9836. } );
  9837. /**
  9838. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  9839. * and the camera's projection matrix
  9840. *
  9841. * @param {vec3} viewPosition - The fragments position in view space.
  9842. * @param {mat4} projectionMatrix - The camera's projection matrix.
  9843. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  9844. */
  9845. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  9846. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  9847. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  9848. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  9849. } );
  9850. /**
  9851. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  9852. * target is available or if flat surface normals are required.
  9853. *
  9854. * @param {vec2} uv - The texture coordinate.
  9855. * @param {DepthTexture} depthTexture - The depth texture.
  9856. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9857. * @return {vec3} The computed normal vector.
  9858. */
  9859. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  9860. const size = textureSize( textureLoad( depthTexture ) );
  9861. const p = ivec2( uv.mul( size ) ).toVar();
  9862. const c0 = textureLoad( depthTexture, p ).toVar();
  9863. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  9864. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  9865. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  9866. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  9867. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  9868. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  9869. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  9870. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  9871. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  9872. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  9873. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  9874. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  9875. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  9876. 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 ) ) );
  9877. 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 ) ) );
  9878. return normalize( cross( dpdx, dpdy ) );
  9879. } );
  9880. class VertexColorNode extends AttributeNode {
  9881. static get type() {
  9882. return 'VertexColorNode';
  9883. }
  9884. constructor( index = 0 ) {
  9885. super( null, 'vec4' );
  9886. this.isVertexColorNode = true;
  9887. this.index = index;
  9888. }
  9889. getAttributeName( /*builder*/ ) {
  9890. const index = this.index;
  9891. return 'color' + ( index > 0 ? index : '' );
  9892. }
  9893. generate( builder ) {
  9894. const attributeName = this.getAttributeName( builder );
  9895. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  9896. let result;
  9897. if ( geometryAttribute === true ) {
  9898. result = super.generate( builder );
  9899. } else {
  9900. // Vertex color fallback should be white
  9901. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  9902. }
  9903. return result;
  9904. }
  9905. serialize( data ) {
  9906. super.serialize( data );
  9907. data.index = this.index;
  9908. }
  9909. deserialize( data ) {
  9910. super.deserialize( data );
  9911. this.index = data.index;
  9912. }
  9913. }
  9914. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  9915. class PointUVNode extends Node {
  9916. static get type() {
  9917. return 'PointUVNode';
  9918. }
  9919. constructor() {
  9920. super( 'vec2' );
  9921. this.isPointUVNode = true;
  9922. }
  9923. generate( /*builder*/ ) {
  9924. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  9925. }
  9926. }
  9927. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  9928. const _e1 = /*@__PURE__*/ new Euler();
  9929. const _m1 = /*@__PURE__*/ new Matrix4();
  9930. class SceneNode extends Node {
  9931. static get type() {
  9932. return 'SceneNode';
  9933. }
  9934. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  9935. super();
  9936. this.scope = scope;
  9937. this.scene = scene;
  9938. }
  9939. setup( builder ) {
  9940. const scope = this.scope;
  9941. const scene = this.scene !== null ? this.scene : builder.scene;
  9942. let output;
  9943. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  9944. output = reference( 'backgroundBlurriness', 'float', scene );
  9945. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  9946. output = reference( 'backgroundIntensity', 'float', scene );
  9947. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  9948. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  9949. const background = scene.background;
  9950. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  9951. _e1.copy( scene.backgroundRotation );
  9952. // accommodate left-handed frame
  9953. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  9954. _m1.makeRotationFromEuler( _e1 );
  9955. } else {
  9956. _m1.identity();
  9957. }
  9958. return _m1;
  9959. } );
  9960. } else {
  9961. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  9962. }
  9963. return output;
  9964. }
  9965. }
  9966. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  9967. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  9968. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  9969. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  9970. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  9971. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  9972. class StorageArrayElementNode extends ArrayElementNode {
  9973. static get type() {
  9974. return 'StorageArrayElementNode';
  9975. }
  9976. constructor( storageBufferNode, indexNode ) {
  9977. super( storageBufferNode, indexNode );
  9978. this.isStorageArrayElementNode = true;
  9979. }
  9980. set storageBufferNode( value ) {
  9981. this.node = value;
  9982. }
  9983. get storageBufferNode() {
  9984. return this.node;
  9985. }
  9986. setup( builder ) {
  9987. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9988. if ( this.node.bufferObject === true ) {
  9989. builder.setupPBO( this.node );
  9990. }
  9991. }
  9992. return super.setup( builder );
  9993. }
  9994. generate( builder, output ) {
  9995. let snippet;
  9996. const isAssignContext = builder.context.assign;
  9997. //
  9998. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9999. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  10000. snippet = builder.generatePBO( this );
  10001. } else {
  10002. snippet = this.node.build( builder );
  10003. }
  10004. } else {
  10005. snippet = super.generate( builder );
  10006. }
  10007. if ( isAssignContext !== true ) {
  10008. const type = this.getNodeType( builder );
  10009. snippet = builder.format( snippet, type, output );
  10010. }
  10011. return snippet;
  10012. }
  10013. }
  10014. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  10015. const GPUPrimitiveTopology = {
  10016. PointList: 'point-list',
  10017. LineList: 'line-list',
  10018. LineStrip: 'line-strip',
  10019. TriangleList: 'triangle-list',
  10020. TriangleStrip: 'triangle-strip',
  10021. };
  10022. const GPUCompareFunction = {
  10023. Never: 'never',
  10024. Less: 'less',
  10025. Equal: 'equal',
  10026. LessEqual: 'less-equal',
  10027. Greater: 'greater',
  10028. NotEqual: 'not-equal',
  10029. GreaterEqual: 'greater-equal',
  10030. Always: 'always'
  10031. };
  10032. const GPUStoreOp = {
  10033. Store: 'store',
  10034. Discard: 'discard'
  10035. };
  10036. const GPULoadOp = {
  10037. Load: 'load',
  10038. Clear: 'clear'
  10039. };
  10040. const GPUFrontFace = {
  10041. CCW: 'ccw',
  10042. CW: 'cw'
  10043. };
  10044. const GPUCullMode = {
  10045. None: 'none',
  10046. Front: 'front',
  10047. Back: 'back'
  10048. };
  10049. const GPUIndexFormat = {
  10050. Uint16: 'uint16',
  10051. Uint32: 'uint32'
  10052. };
  10053. const GPUTextureFormat = {
  10054. // 8-bit formats
  10055. R8Unorm: 'r8unorm',
  10056. R8Snorm: 'r8snorm',
  10057. R8Uint: 'r8uint',
  10058. R8Sint: 'r8sint',
  10059. // 16-bit formats
  10060. R16Uint: 'r16uint',
  10061. R16Sint: 'r16sint',
  10062. R16Float: 'r16float',
  10063. RG8Unorm: 'rg8unorm',
  10064. RG8Snorm: 'rg8snorm',
  10065. RG8Uint: 'rg8uint',
  10066. RG8Sint: 'rg8sint',
  10067. // 32-bit formats
  10068. R32Uint: 'r32uint',
  10069. R32Sint: 'r32sint',
  10070. R32Float: 'r32float',
  10071. RG16Uint: 'rg16uint',
  10072. RG16Sint: 'rg16sint',
  10073. RG16Float: 'rg16float',
  10074. RGBA8Unorm: 'rgba8unorm',
  10075. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  10076. RGBA8Snorm: 'rgba8snorm',
  10077. RGBA8Uint: 'rgba8uint',
  10078. RGBA8Sint: 'rgba8sint',
  10079. BGRA8Unorm: 'bgra8unorm',
  10080. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  10081. // Packed 32-bit formats
  10082. RGB9E5UFloat: 'rgb9e5ufloat',
  10083. RGB10A2Unorm: 'rgb10a2unorm',
  10084. RG11B10uFloat: 'rgb10a2unorm',
  10085. // 64-bit formats
  10086. RG32Uint: 'rg32uint',
  10087. RG32Sint: 'rg32sint',
  10088. RG32Float: 'rg32float',
  10089. RGBA16Uint: 'rgba16uint',
  10090. RGBA16Sint: 'rgba16sint',
  10091. RGBA16Float: 'rgba16float',
  10092. // 128-bit formats
  10093. RGBA32Uint: 'rgba32uint',
  10094. RGBA32Sint: 'rgba32sint',
  10095. RGBA32Float: 'rgba32float',
  10096. // Depth and stencil formats
  10097. Stencil8: 'stencil8',
  10098. Depth16Unorm: 'depth16unorm',
  10099. Depth24Plus: 'depth24plus',
  10100. Depth24PlusStencil8: 'depth24plus-stencil8',
  10101. Depth32Float: 'depth32float',
  10102. // 'depth32float-stencil8' extension
  10103. Depth32FloatStencil8: 'depth32float-stencil8',
  10104. // BC compressed formats usable if 'texture-compression-bc' is both
  10105. // supported by the device/user agent and enabled in requestDevice.
  10106. BC1RGBAUnorm: 'bc1-rgba-unorm',
  10107. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  10108. BC2RGBAUnorm: 'bc2-rgba-unorm',
  10109. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  10110. BC3RGBAUnorm: 'bc3-rgba-unorm',
  10111. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  10112. BC4RUnorm: 'bc4-r-unorm',
  10113. BC4RSnorm: 'bc4-r-snorm',
  10114. BC5RGUnorm: 'bc5-rg-unorm',
  10115. BC5RGSnorm: 'bc5-rg-snorm',
  10116. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  10117. BC6HRGBFloat: 'bc6h-rgb-float',
  10118. BC7RGBAUnorm: 'bc7-rgba-unorm',
  10119. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  10120. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  10121. // supported by the device/user agent and enabled in requestDevice.
  10122. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  10123. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  10124. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  10125. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  10126. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  10127. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  10128. EACR11Unorm: 'eac-r11unorm',
  10129. EACR11Snorm: 'eac-r11snorm',
  10130. EACRG11Unorm: 'eac-rg11unorm',
  10131. EACRG11Snorm: 'eac-rg11snorm',
  10132. // ASTC compressed formats usable if 'texture-compression-astc' is both
  10133. // supported by the device/user agent and enabled in requestDevice.
  10134. ASTC4x4Unorm: 'astc-4x4-unorm',
  10135. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  10136. ASTC5x4Unorm: 'astc-5x4-unorm',
  10137. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  10138. ASTC5x5Unorm: 'astc-5x5-unorm',
  10139. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  10140. ASTC6x5Unorm: 'astc-6x5-unorm',
  10141. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  10142. ASTC6x6Unorm: 'astc-6x6-unorm',
  10143. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  10144. ASTC8x5Unorm: 'astc-8x5-unorm',
  10145. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  10146. ASTC8x6Unorm: 'astc-8x6-unorm',
  10147. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  10148. ASTC8x8Unorm: 'astc-8x8-unorm',
  10149. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  10150. ASTC10x5Unorm: 'astc-10x5-unorm',
  10151. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  10152. ASTC10x6Unorm: 'astc-10x6-unorm',
  10153. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  10154. ASTC10x8Unorm: 'astc-10x8-unorm',
  10155. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  10156. ASTC10x10Unorm: 'astc-10x10-unorm',
  10157. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  10158. ASTC12x10Unorm: 'astc-12x10-unorm',
  10159. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  10160. ASTC12x12Unorm: 'astc-12x12-unorm',
  10161. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  10162. };
  10163. const GPUAddressMode = {
  10164. ClampToEdge: 'clamp-to-edge',
  10165. Repeat: 'repeat',
  10166. MirrorRepeat: 'mirror-repeat'
  10167. };
  10168. const GPUFilterMode = {
  10169. Linear: 'linear',
  10170. Nearest: 'nearest'
  10171. };
  10172. const GPUBlendFactor = {
  10173. Zero: 'zero',
  10174. One: 'one',
  10175. Src: 'src',
  10176. OneMinusSrc: 'one-minus-src',
  10177. SrcAlpha: 'src-alpha',
  10178. OneMinusSrcAlpha: 'one-minus-src-alpha',
  10179. Dst: 'dst',
  10180. OneMinusDstColor: 'one-minus-dst',
  10181. DstAlpha: 'dst-alpha',
  10182. OneMinusDstAlpha: 'one-minus-dst-alpha',
  10183. SrcAlphaSaturated: 'src-alpha-saturated',
  10184. Constant: 'constant',
  10185. OneMinusConstant: 'one-minus-constant'
  10186. };
  10187. const GPUBlendOperation = {
  10188. Add: 'add',
  10189. Subtract: 'subtract',
  10190. ReverseSubtract: 'reverse-subtract',
  10191. Min: 'min',
  10192. Max: 'max'
  10193. };
  10194. const GPUColorWriteFlags = {
  10195. None: 0,
  10196. Red: 0x1,
  10197. Green: 0x2,
  10198. Blue: 0x4,
  10199. Alpha: 0x8,
  10200. All: 0xF
  10201. };
  10202. const GPUStencilOperation = {
  10203. Keep: 'keep',
  10204. Zero: 'zero',
  10205. Replace: 'replace',
  10206. Invert: 'invert',
  10207. IncrementClamp: 'increment-clamp',
  10208. DecrementClamp: 'decrement-clamp',
  10209. IncrementWrap: 'increment-wrap',
  10210. DecrementWrap: 'decrement-wrap'
  10211. };
  10212. const GPUBufferBindingType = {
  10213. Uniform: 'uniform',
  10214. Storage: 'storage',
  10215. ReadOnlyStorage: 'read-only-storage'
  10216. };
  10217. const GPUStorageTextureAccess = {
  10218. WriteOnly: 'write-only',
  10219. ReadOnly: 'read-only',
  10220. ReadWrite: 'read-write',
  10221. };
  10222. const GPUTextureSampleType = {
  10223. Float: 'float',
  10224. UnfilterableFloat: 'unfilterable-float',
  10225. Depth: 'depth',
  10226. SInt: 'sint',
  10227. UInt: 'uint'
  10228. };
  10229. const GPUTextureDimension = {
  10230. OneD: '1d',
  10231. TwoD: '2d',
  10232. ThreeD: '3d'
  10233. };
  10234. const GPUTextureViewDimension = {
  10235. OneD: '1d',
  10236. TwoD: '2d',
  10237. TwoDArray: '2d-array',
  10238. Cube: 'cube',
  10239. CubeArray: 'cube-array',
  10240. ThreeD: '3d'
  10241. };
  10242. const GPUTextureAspect = {
  10243. All: 'all',
  10244. StencilOnly: 'stencil-only',
  10245. DepthOnly: 'depth-only'
  10246. };
  10247. const GPUInputStepMode = {
  10248. Vertex: 'vertex',
  10249. Instance: 'instance'
  10250. };
  10251. const GPUFeatureName = {
  10252. DepthClipControl: 'depth-clip-control',
  10253. Depth32FloatStencil8: 'depth32float-stencil8',
  10254. TextureCompressionBC: 'texture-compression-bc',
  10255. TextureCompressionETC2: 'texture-compression-etc2',
  10256. TextureCompressionASTC: 'texture-compression-astc',
  10257. TimestampQuery: 'timestamp-query',
  10258. IndirectFirstInstance: 'indirect-first-instance',
  10259. ShaderF16: 'shader-f16',
  10260. RG11B10UFloat: 'rg11b10ufloat-renderable',
  10261. BGRA8UNormStorage: 'bgra8unorm-storage',
  10262. Float32Filterable: 'float32-filterable',
  10263. ClipDistances: 'clip-distances',
  10264. DualSourceBlending: 'dual-source-blending',
  10265. Subgroups: 'subgroups'
  10266. };
  10267. class StorageBufferNode extends BufferNode {
  10268. static get type() {
  10269. return 'StorageBufferNode';
  10270. }
  10271. constructor( value, bufferType, bufferCount = 0 ) {
  10272. super( value, bufferType, bufferCount );
  10273. this.isStorageBufferNode = true;
  10274. this.access = GPUBufferBindingType.Storage;
  10275. this.isAtomic = false;
  10276. this.bufferObject = false;
  10277. this.bufferCount = bufferCount;
  10278. this._attribute = null;
  10279. this._varying = null;
  10280. this.global = true;
  10281. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10282. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10283. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10284. else value.isStorageBufferAttribute = true;
  10285. }
  10286. }
  10287. getHash( builder ) {
  10288. if ( this.bufferCount === 0 ) {
  10289. let bufferData = builder.globalCache.getData( this.value );
  10290. if ( bufferData === undefined ) {
  10291. bufferData = {
  10292. node: this
  10293. };
  10294. builder.globalCache.setData( this.value, bufferData );
  10295. }
  10296. return bufferData.node.uuid;
  10297. }
  10298. return this.uuid;
  10299. }
  10300. getInputType( /*builder*/ ) {
  10301. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10302. }
  10303. element( indexNode ) {
  10304. return storageElement( this, indexNode );
  10305. }
  10306. setBufferObject( value ) {
  10307. this.bufferObject = value;
  10308. return this;
  10309. }
  10310. setAccess( value ) {
  10311. this.access = value;
  10312. return this;
  10313. }
  10314. toReadOnly() {
  10315. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  10316. }
  10317. setAtomic( value ) {
  10318. this.isAtomic = value;
  10319. return this;
  10320. }
  10321. toAtomic() {
  10322. return this.setAtomic( true );
  10323. }
  10324. getAttributeData() {
  10325. if ( this._attribute === null ) {
  10326. this._attribute = bufferAttribute( this.value );
  10327. this._varying = varying( this._attribute );
  10328. }
  10329. return {
  10330. attribute: this._attribute,
  10331. varying: this._varying
  10332. };
  10333. }
  10334. getNodeType( builder ) {
  10335. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10336. return super.getNodeType( builder );
  10337. }
  10338. const { attribute } = this.getAttributeData();
  10339. return attribute.getNodeType( builder );
  10340. }
  10341. generate( builder ) {
  10342. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10343. return super.generate( builder );
  10344. }
  10345. const { attribute, varying } = this.getAttributeData();
  10346. const output = varying.build( builder );
  10347. builder.registerTransform( output, attribute );
  10348. return output;
  10349. }
  10350. }
  10351. // Read-Write Storage
  10352. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10353. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  10354. class StorageTextureNode extends TextureNode {
  10355. static get type() {
  10356. return 'StorageTextureNode';
  10357. }
  10358. constructor( value, uvNode, storeNode = null ) {
  10359. super( value, uvNode );
  10360. this.storeNode = storeNode;
  10361. this.isStorageTextureNode = true;
  10362. this.access = GPUStorageTextureAccess.WriteOnly;
  10363. }
  10364. getInputType( /*builder*/ ) {
  10365. return 'storageTexture';
  10366. }
  10367. setup( builder ) {
  10368. super.setup( builder );
  10369. const properties = builder.getNodeProperties( this );
  10370. properties.storeNode = this.storeNode;
  10371. }
  10372. setAccess( value ) {
  10373. this.access = value;
  10374. return this;
  10375. }
  10376. generate( builder, output ) {
  10377. let snippet;
  10378. if ( this.storeNode !== null ) {
  10379. snippet = this.generateStore( builder );
  10380. } else {
  10381. snippet = super.generate( builder, output );
  10382. }
  10383. return snippet;
  10384. }
  10385. toReadOnly() {
  10386. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  10387. }
  10388. toWriteOnly() {
  10389. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  10390. }
  10391. generateStore( builder ) {
  10392. const properties = builder.getNodeProperties( this );
  10393. const { uvNode, storeNode } = properties;
  10394. const textureProperty = super.generate( builder, 'property' );
  10395. const uvSnippet = uvNode.build( builder, 'uvec2' );
  10396. const storeSnippet = storeNode.build( builder, 'vec4' );
  10397. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  10398. builder.addLineFlowCode( snippet, this );
  10399. }
  10400. }
  10401. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  10402. const textureStore = ( value, uvNode, storeNode ) => {
  10403. const node = storageTexture( value, uvNode, storeNode );
  10404. if ( storeNode !== null ) node.append();
  10405. return node;
  10406. };
  10407. class UserDataNode extends ReferenceNode {
  10408. static get type() {
  10409. return 'UserDataNode';
  10410. }
  10411. constructor( property, inputType, userData = null ) {
  10412. super( property, inputType, userData );
  10413. this.userData = userData;
  10414. }
  10415. updateReference( state ) {
  10416. this.reference = this.userData !== null ? this.userData : state.object.userData;
  10417. return this.reference;
  10418. }
  10419. }
  10420. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  10421. const _objectData = new WeakMap();
  10422. class VelocityNode extends TempNode {
  10423. static get type() {
  10424. return 'VelocityNode';
  10425. }
  10426. constructor() {
  10427. super( 'vec2' );
  10428. this.projectionMatrix = null;
  10429. this.updateType = NodeUpdateType.OBJECT;
  10430. this.updateAfterType = NodeUpdateType.OBJECT;
  10431. this.previousModelWorldMatrix = uniform( new Matrix4() );
  10432. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  10433. this.previousCameraViewMatrix = uniform( new Matrix4() );
  10434. }
  10435. setProjectionMatrix( projectionMatrix ) {
  10436. this.projectionMatrix = projectionMatrix;
  10437. }
  10438. update( { frameId, camera, object } ) {
  10439. const previousModelMatrix = getPreviousMatrix( object );
  10440. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  10441. //
  10442. const cameraData = getData( camera );
  10443. if ( cameraData.frameId !== frameId ) {
  10444. cameraData.frameId = frameId;
  10445. if ( cameraData.previousProjectionMatrix === undefined ) {
  10446. cameraData.previousProjectionMatrix = new Matrix4();
  10447. cameraData.previousCameraViewMatrix = new Matrix4();
  10448. cameraData.currentProjectionMatrix = new Matrix4();
  10449. cameraData.currentCameraViewMatrix = new Matrix4();
  10450. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10451. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  10452. } else {
  10453. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  10454. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  10455. }
  10456. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10457. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  10458. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  10459. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  10460. }
  10461. }
  10462. updateAfter( { object } ) {
  10463. getPreviousMatrix( object ).copy( object.matrixWorld );
  10464. }
  10465. setup( /*builder*/ ) {
  10466. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  10467. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  10468. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10469. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  10470. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  10471. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  10472. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  10473. return velocity;
  10474. }
  10475. }
  10476. function getData( object ) {
  10477. let objectData = _objectData.get( object );
  10478. if ( objectData === undefined ) {
  10479. objectData = {};
  10480. _objectData.set( object, objectData );
  10481. }
  10482. return objectData;
  10483. }
  10484. function getPreviousMatrix( object, index = 0 ) {
  10485. const objectData = getData( object );
  10486. let matrix = objectData[ index ];
  10487. if ( matrix === undefined ) {
  10488. objectData[ index ] = matrix = new Matrix4();
  10489. }
  10490. return matrix;
  10491. }
  10492. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  10493. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10494. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  10495. } ).setLayout( {
  10496. name: 'blendBurn',
  10497. type: 'vec3',
  10498. inputs: [
  10499. { name: 'base', type: 'vec3' },
  10500. { name: 'blend', type: 'vec3' }
  10501. ]
  10502. } );
  10503. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10504. return min$1( base.div( blend.oneMinus() ), 1.0 );
  10505. } ).setLayout( {
  10506. name: 'blendDodge',
  10507. type: 'vec3',
  10508. inputs: [
  10509. { name: 'base', type: 'vec3' },
  10510. { name: 'blend', type: 'vec3' }
  10511. ]
  10512. } );
  10513. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10514. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  10515. } ).setLayout( {
  10516. name: 'blendScreen',
  10517. type: 'vec3',
  10518. inputs: [
  10519. { name: 'base', type: 'vec3' },
  10520. { name: 'blend', type: 'vec3' }
  10521. ]
  10522. } );
  10523. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10524. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  10525. } ).setLayout( {
  10526. name: 'blendOverlay',
  10527. type: 'vec3',
  10528. inputs: [
  10529. { name: 'base', type: 'vec3' },
  10530. { name: 'blend', type: 'vec3' }
  10531. ]
  10532. } );
  10533. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10534. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  10535. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  10536. } ).setLayout( {
  10537. name: 'blendColor',
  10538. type: 'vec4',
  10539. inputs: [
  10540. { name: 'base', type: 'vec4' },
  10541. { name: 'blend', type: 'vec4' }
  10542. ]
  10543. } );
  10544. // deprecated
  10545. const burn = ( ...params ) => { // @deprecated, r171
  10546. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  10547. return blendBurn( params );
  10548. };
  10549. const dodge = ( ...params ) => { // @deprecated, r171
  10550. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  10551. return blendDodge( params );
  10552. };
  10553. const screen = ( ...params ) => { // @deprecated, r171
  10554. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  10555. return blendScreen( params );
  10556. };
  10557. const overlay = ( ...params ) => { // @deprecated, r171
  10558. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  10559. return blendOverlay( params );
  10560. };
  10561. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10562. return luminance( color.rgb );
  10563. } );
  10564. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10565. return adjustment.mix( luminance( color.rgb ), color.rgb );
  10566. } );
  10567. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10568. const average = add( color.r, color.g, color.b ).div( 3.0 );
  10569. const mx = color.r.max( color.g.max( color.b ) );
  10570. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  10571. return mix( color.rgb, mx, amt );
  10572. } );
  10573. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10574. const k = vec3( 0.57735, 0.57735, 0.57735 );
  10575. const cosAngle = adjustment.cos();
  10576. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  10577. } );
  10578. const luminance = (
  10579. color,
  10580. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  10581. ) => dot( color, luminanceCoefficients );
  10582. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  10583. /**
  10584. * Color Decision List (CDL) v1.2
  10585. *
  10586. * Compact representation of color grading information, defined by slope, offset, power, and
  10587. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  10588. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  10589. *
  10590. * @param {vec4} color Input (-Infinity < input < +Infinity)
  10591. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  10592. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  10593. * @param {number | vec3} power Power (0 < power < +Infinity)
  10594. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  10595. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  10596. * @return Output, -Infinity < output < +Infinity
  10597. *
  10598. * References:
  10599. * - ASC CDL v1.2
  10600. * - https://blender.stackexchange.com/a/55239/43930
  10601. * - https://docs.acescentral.com/specifications/acescc/
  10602. */
  10603. const cdl = /*@__PURE__*/ Fn( ( [
  10604. color,
  10605. slope = vec3( 1 ),
  10606. offset = vec3( 0 ),
  10607. power = vec3( 1 ),
  10608. saturation = float( 1 ),
  10609. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  10610. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  10611. ] ) => {
  10612. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  10613. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  10614. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  10615. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  10616. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  10617. const pv = v.pow( power ).toVar();
  10618. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  10619. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  10620. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  10621. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  10622. return vec4( v.rgb, color.a );
  10623. } );
  10624. class PosterizeNode extends TempNode {
  10625. static get type() {
  10626. return 'PosterizeNode';
  10627. }
  10628. constructor( sourceNode, stepsNode ) {
  10629. super();
  10630. this.sourceNode = sourceNode;
  10631. this.stepsNode = stepsNode;
  10632. }
  10633. setup() {
  10634. const { sourceNode, stepsNode } = this;
  10635. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  10636. }
  10637. }
  10638. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  10639. let _sharedFramebuffer = null;
  10640. class ViewportSharedTextureNode extends ViewportTextureNode {
  10641. static get type() {
  10642. return 'ViewportSharedTextureNode';
  10643. }
  10644. constructor( uvNode = screenUV, levelNode = null ) {
  10645. if ( _sharedFramebuffer === null ) {
  10646. _sharedFramebuffer = new FramebufferTexture();
  10647. }
  10648. super( uvNode, levelNode, _sharedFramebuffer );
  10649. }
  10650. updateReference() {
  10651. return this;
  10652. }
  10653. }
  10654. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  10655. const _size = /*@__PURE__*/ new Vector2();
  10656. class PassTextureNode extends TextureNode {
  10657. static get type() {
  10658. return 'PassTextureNode';
  10659. }
  10660. constructor( passNode, texture ) {
  10661. super( texture );
  10662. this.passNode = passNode;
  10663. this.setUpdateMatrix( false );
  10664. }
  10665. setup( builder ) {
  10666. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  10667. return super.setup( builder );
  10668. }
  10669. clone() {
  10670. return new this.constructor( this.passNode, this.value );
  10671. }
  10672. }
  10673. class PassMultipleTextureNode extends PassTextureNode {
  10674. static get type() {
  10675. return 'PassMultipleTextureNode';
  10676. }
  10677. constructor( passNode, textureName, previousTexture = false ) {
  10678. super( passNode, null );
  10679. this.textureName = textureName;
  10680. this.previousTexture = previousTexture;
  10681. }
  10682. updateTexture() {
  10683. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  10684. }
  10685. setup( builder ) {
  10686. this.updateTexture();
  10687. return super.setup( builder );
  10688. }
  10689. clone() {
  10690. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  10691. }
  10692. }
  10693. class PassNode extends TempNode {
  10694. static get type() {
  10695. return 'PassNode';
  10696. }
  10697. constructor( scope, scene, camera, options = {} ) {
  10698. super( 'vec4' );
  10699. this.scope = scope;
  10700. this.scene = scene;
  10701. this.camera = camera;
  10702. this.options = options;
  10703. this._pixelRatio = 1;
  10704. this._width = 1;
  10705. this._height = 1;
  10706. const depthTexture = new DepthTexture();
  10707. depthTexture.isRenderTargetTexture = true;
  10708. //depthTexture.type = FloatType;
  10709. depthTexture.name = 'depth';
  10710. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  10711. renderTarget.texture.name = 'output';
  10712. renderTarget.depthTexture = depthTexture;
  10713. this.renderTarget = renderTarget;
  10714. this.updateBeforeType = NodeUpdateType.FRAME;
  10715. this._textures = {
  10716. output: renderTarget.texture,
  10717. depth: depthTexture
  10718. };
  10719. this._textureNodes = {};
  10720. this._linearDepthNodes = {};
  10721. this._viewZNodes = {};
  10722. this._previousTextures = {};
  10723. this._previousTextureNodes = {};
  10724. this._cameraNear = uniform( 0 );
  10725. this._cameraFar = uniform( 0 );
  10726. this._mrt = null;
  10727. this.isPassNode = true;
  10728. }
  10729. setMRT( mrt ) {
  10730. this._mrt = mrt;
  10731. return this;
  10732. }
  10733. getMRT() {
  10734. return this._mrt;
  10735. }
  10736. isGlobal() {
  10737. return true;
  10738. }
  10739. getTexture( name ) {
  10740. let texture = this._textures[ name ];
  10741. if ( texture === undefined ) {
  10742. const refTexture = this.renderTarget.texture;
  10743. texture = refTexture.clone();
  10744. texture.isRenderTargetTexture = true;
  10745. texture.name = name;
  10746. this._textures[ name ] = texture;
  10747. this.renderTarget.textures.push( texture );
  10748. }
  10749. return texture;
  10750. }
  10751. getPreviousTexture( name ) {
  10752. let texture = this._previousTextures[ name ];
  10753. if ( texture === undefined ) {
  10754. texture = this.getTexture( name ).clone();
  10755. texture.isRenderTargetTexture = true;
  10756. this._previousTextures[ name ] = texture;
  10757. }
  10758. return texture;
  10759. }
  10760. toggleTexture( name ) {
  10761. const prevTexture = this._previousTextures[ name ];
  10762. if ( prevTexture !== undefined ) {
  10763. const texture = this._textures[ name ];
  10764. const index = this.renderTarget.textures.indexOf( texture );
  10765. this.renderTarget.textures[ index ] = prevTexture;
  10766. this._textures[ name ] = prevTexture;
  10767. this._previousTextures[ name ] = texture;
  10768. this._textureNodes[ name ].updateTexture();
  10769. this._previousTextureNodes[ name ].updateTexture();
  10770. }
  10771. }
  10772. getTextureNode( name = 'output' ) {
  10773. let textureNode = this._textureNodes[ name ];
  10774. if ( textureNode === undefined ) {
  10775. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  10776. textureNode.updateTexture();
  10777. this._textureNodes[ name ] = textureNode;
  10778. }
  10779. return textureNode;
  10780. }
  10781. getPreviousTextureNode( name = 'output' ) {
  10782. let textureNode = this._previousTextureNodes[ name ];
  10783. if ( textureNode === undefined ) {
  10784. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  10785. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  10786. textureNode.updateTexture();
  10787. this._previousTextureNodes[ name ] = textureNode;
  10788. }
  10789. return textureNode;
  10790. }
  10791. getViewZNode( name = 'depth' ) {
  10792. let viewZNode = this._viewZNodes[ name ];
  10793. if ( viewZNode === undefined ) {
  10794. const cameraNear = this._cameraNear;
  10795. const cameraFar = this._cameraFar;
  10796. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  10797. }
  10798. return viewZNode;
  10799. }
  10800. getLinearDepthNode( name = 'depth' ) {
  10801. let linearDepthNode = this._linearDepthNodes[ name ];
  10802. if ( linearDepthNode === undefined ) {
  10803. const cameraNear = this._cameraNear;
  10804. const cameraFar = this._cameraFar;
  10805. const viewZNode = this.getViewZNode( name );
  10806. // TODO: just if ( builder.camera.isPerspectiveCamera )
  10807. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  10808. }
  10809. return linearDepthNode;
  10810. }
  10811. setup( { renderer } ) {
  10812. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  10813. // Disable MSAA for WebGL backend for now
  10814. if ( renderer.backend.isWebGLBackend === true ) {
  10815. this.renderTarget.samples = 0;
  10816. }
  10817. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  10818. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  10819. }
  10820. updateBefore( frame ) {
  10821. const { renderer } = frame;
  10822. const { scene, camera } = this;
  10823. this._pixelRatio = renderer.getPixelRatio();
  10824. const size = renderer.getSize( _size );
  10825. this.setSize( size.width, size.height );
  10826. const currentRenderTarget = renderer.getRenderTarget();
  10827. const currentMRT = renderer.getMRT();
  10828. this._cameraNear.value = camera.near;
  10829. this._cameraFar.value = camera.far;
  10830. for ( const name in this._previousTextures ) {
  10831. this.toggleTexture( name );
  10832. }
  10833. renderer.setRenderTarget( this.renderTarget );
  10834. renderer.setMRT( this._mrt );
  10835. renderer.render( scene, camera );
  10836. renderer.setRenderTarget( currentRenderTarget );
  10837. renderer.setMRT( currentMRT );
  10838. }
  10839. setSize( width, height ) {
  10840. this._width = width;
  10841. this._height = height;
  10842. const effectiveWidth = this._width * this._pixelRatio;
  10843. const effectiveHeight = this._height * this._pixelRatio;
  10844. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10845. }
  10846. setPixelRatio( pixelRatio ) {
  10847. this._pixelRatio = pixelRatio;
  10848. this.setSize( this._width, this._height );
  10849. }
  10850. dispose() {
  10851. this.renderTarget.dispose();
  10852. }
  10853. }
  10854. PassNode.COLOR = 'color';
  10855. PassNode.DEPTH = 'depth';
  10856. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  10857. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  10858. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  10859. class ToonOutlinePassNode extends PassNode {
  10860. static get type() {
  10861. return 'ToonOutlinePassNode';
  10862. }
  10863. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  10864. super( PassNode.COLOR, scene, camera );
  10865. this.colorNode = colorNode;
  10866. this.thicknessNode = thicknessNode;
  10867. this.alphaNode = alphaNode;
  10868. this._materialCache = new WeakMap();
  10869. }
  10870. updateBefore( frame ) {
  10871. const { renderer } = frame;
  10872. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  10873. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  10874. // only render outline for supported materials
  10875. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  10876. if ( material.wireframe === false ) {
  10877. const outlineMaterial = this._getOutlineMaterial( material );
  10878. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  10879. }
  10880. }
  10881. // default
  10882. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  10883. } );
  10884. super.updateBefore( frame );
  10885. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  10886. }
  10887. _createMaterial() {
  10888. const material = new NodeMaterial();
  10889. material.isMeshToonOutlineMaterial = true;
  10890. material.name = 'Toon_Outline';
  10891. material.side = BackSide;
  10892. // vertex node
  10893. const outlineNormal = normalLocal.negate();
  10894. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  10895. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  10896. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  10897. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  10898. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  10899. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  10900. // color node
  10901. material.colorNode = vec4( this.colorNode, this.alphaNode );
  10902. return material;
  10903. }
  10904. _getOutlineMaterial( originalMaterial ) {
  10905. let outlineMaterial = this._materialCache.get( originalMaterial );
  10906. if ( outlineMaterial === undefined ) {
  10907. outlineMaterial = this._createMaterial();
  10908. this._materialCache.set( originalMaterial, outlineMaterial );
  10909. }
  10910. return outlineMaterial;
  10911. }
  10912. }
  10913. 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 ) ) );
  10914. // exposure only
  10915. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10916. return color.mul( exposure ).clamp();
  10917. } ).setLayout( {
  10918. name: 'linearToneMapping',
  10919. type: 'vec3',
  10920. inputs: [
  10921. { name: 'color', type: 'vec3' },
  10922. { name: 'exposure', type: 'float' }
  10923. ]
  10924. } );
  10925. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  10926. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10927. color = color.mul( exposure );
  10928. return color.div( color.add( 1.0 ) ).clamp();
  10929. } ).setLayout( {
  10930. name: 'reinhardToneMapping',
  10931. type: 'vec3',
  10932. inputs: [
  10933. { name: 'color', type: 'vec3' },
  10934. { name: 'exposure', type: 'float' }
  10935. ]
  10936. } );
  10937. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  10938. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10939. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  10940. color = color.mul( exposure );
  10941. color = color.sub( 0.004 ).max( 0.0 );
  10942. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  10943. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  10944. return a.div( b ).pow( 2.2 );
  10945. } ).setLayout( {
  10946. name: 'cineonToneMapping',
  10947. type: 'vec3',
  10948. inputs: [
  10949. { name: 'color', type: 'vec3' },
  10950. { name: 'exposure', type: 'float' }
  10951. ]
  10952. } );
  10953. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10954. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10955. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  10956. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  10957. return a.div( b );
  10958. } );
  10959. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10960. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10961. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  10962. const ACESInputMat = mat3(
  10963. 0.59719, 0.35458, 0.04823,
  10964. 0.07600, 0.90834, 0.01566,
  10965. 0.02840, 0.13383, 0.83777
  10966. );
  10967. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  10968. const ACESOutputMat = mat3(
  10969. 1.60475, - 0.53108, - 0.07367,
  10970. - 0.10208, 1.10813, - 0.00605,
  10971. - 0.00327, - 0.07276, 1.07602
  10972. );
  10973. color = color.mul( exposure ).div( 0.6 );
  10974. color = ACESInputMat.mul( color );
  10975. // Apply RRT and ODT
  10976. color = RRTAndODTFit( color );
  10977. color = ACESOutputMat.mul( color );
  10978. // Clamp to [0, 1]
  10979. return color.clamp();
  10980. } ).setLayout( {
  10981. name: 'acesFilmicToneMapping',
  10982. type: 'vec3',
  10983. inputs: [
  10984. { name: 'color', type: 'vec3' },
  10985. { name: 'exposure', type: 'float' }
  10986. ]
  10987. } );
  10988. 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 ) );
  10989. 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 ) );
  10990. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  10991. const x = vec3( x_immutable ).toVar();
  10992. const x2 = vec3( x.mul( x ) ).toVar();
  10993. const x4 = vec3( x2.mul( x2 ) ).toVar();
  10994. 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 ) ) ) );
  10995. } );
  10996. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10997. const colortone = vec3( color ).toVar();
  10998. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  10999. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  11000. const AgxMinEv = float( - 12.47393 );
  11001. const AgxMaxEv = float( 4.026069 );
  11002. colortone.mulAssign( exposure );
  11003. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  11004. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  11005. colortone.assign( max$1( colortone, 1e-10 ) );
  11006. colortone.assign( log2( colortone ) );
  11007. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  11008. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11009. colortone.assign( agxDefaultContrastApprox( colortone ) );
  11010. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  11011. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  11012. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  11013. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11014. return colortone;
  11015. } ).setLayout( {
  11016. name: 'agxToneMapping',
  11017. type: 'vec3',
  11018. inputs: [
  11019. { name: 'color', type: 'vec3' },
  11020. { name: 'exposure', type: 'float' }
  11021. ]
  11022. } );
  11023. // https://modelviewer.dev/examples/tone-mapping
  11024. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11025. const StartCompression = float( 0.8 - 0.04 );
  11026. const Desaturation = float( 0.15 );
  11027. color = color.mul( exposure );
  11028. const x = min$1( color.r, min$1( color.g, color.b ) );
  11029. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  11030. color.subAssign( offset );
  11031. const peak = max$1( color.r, max$1( color.g, color.b ) );
  11032. If( peak.lessThan( StartCompression ), () => {
  11033. return color;
  11034. } );
  11035. const d = sub( 1, StartCompression );
  11036. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  11037. color.mulAssign( newPeak.div( peak ) );
  11038. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  11039. return mix( color, vec3( newPeak ), g );
  11040. } ).setLayout( {
  11041. name: 'neutralToneMapping',
  11042. type: 'vec3',
  11043. inputs: [
  11044. { name: 'color', type: 'vec3' },
  11045. { name: 'exposure', type: 'float' }
  11046. ]
  11047. } );
  11048. class CodeNode extends Node {
  11049. static get type() {
  11050. return 'CodeNode';
  11051. }
  11052. constructor( code = '', includes = [], language = '' ) {
  11053. super( 'code' );
  11054. this.isCodeNode = true;
  11055. this.code = code;
  11056. this.language = language;
  11057. this.includes = includes;
  11058. }
  11059. isGlobal() {
  11060. return true;
  11061. }
  11062. setIncludes( includes ) {
  11063. this.includes = includes;
  11064. return this;
  11065. }
  11066. getIncludes( /*builder*/ ) {
  11067. return this.includes;
  11068. }
  11069. generate( builder ) {
  11070. const includes = this.getIncludes( builder );
  11071. for ( const include of includes ) {
  11072. include.build( builder );
  11073. }
  11074. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  11075. nodeCode.code = this.code;
  11076. return nodeCode.code;
  11077. }
  11078. serialize( data ) {
  11079. super.serialize( data );
  11080. data.code = this.code;
  11081. data.language = this.language;
  11082. }
  11083. deserialize( data ) {
  11084. super.deserialize( data );
  11085. this.code = data.code;
  11086. this.language = data.language;
  11087. }
  11088. }
  11089. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  11090. const js = ( src, includes ) => code( src, includes, 'js' );
  11091. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  11092. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  11093. class FunctionNode extends CodeNode {
  11094. static get type() {
  11095. return 'FunctionNode';
  11096. }
  11097. constructor( code = '', includes = [], language = '' ) {
  11098. super( code, includes, language );
  11099. }
  11100. getNodeType( builder ) {
  11101. return this.getNodeFunction( builder ).type;
  11102. }
  11103. getInputs( builder ) {
  11104. return this.getNodeFunction( builder ).inputs;
  11105. }
  11106. getNodeFunction( builder ) {
  11107. const nodeData = builder.getDataFromNode( this );
  11108. let nodeFunction = nodeData.nodeFunction;
  11109. if ( nodeFunction === undefined ) {
  11110. nodeFunction = builder.parser.parseFunction( this.code );
  11111. nodeData.nodeFunction = nodeFunction;
  11112. }
  11113. return nodeFunction;
  11114. }
  11115. generate( builder, output ) {
  11116. super.generate( builder );
  11117. const nodeFunction = this.getNodeFunction( builder );
  11118. const name = nodeFunction.name;
  11119. const type = nodeFunction.type;
  11120. const nodeCode = builder.getCodeFromNode( this, type );
  11121. if ( name !== '' ) {
  11122. // use a custom property name
  11123. nodeCode.name = name;
  11124. }
  11125. const propertyName = builder.getPropertyName( nodeCode );
  11126. const code = this.getNodeFunction( builder ).getCode( propertyName );
  11127. nodeCode.code = code + '\n';
  11128. if ( output === 'property' ) {
  11129. return propertyName;
  11130. } else {
  11131. return builder.format( `${ propertyName }()`, type, output );
  11132. }
  11133. }
  11134. }
  11135. const nativeFn = ( code, includes = [], language = '' ) => {
  11136. for ( let i = 0; i < includes.length; i ++ ) {
  11137. const include = includes[ i ];
  11138. // TSL Function: glslFn, wgslFn
  11139. if ( typeof include === 'function' ) {
  11140. includes[ i ] = include.functionNode;
  11141. }
  11142. }
  11143. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  11144. const fn = ( ...params ) => functionNode.call( ...params );
  11145. fn.functionNode = functionNode;
  11146. return fn;
  11147. };
  11148. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  11149. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  11150. class ScriptableValueNode extends Node {
  11151. static get type() {
  11152. return 'ScriptableValueNode';
  11153. }
  11154. constructor( value = null ) {
  11155. super();
  11156. this._value = value;
  11157. this._cache = null;
  11158. this.inputType = null;
  11159. this.outpuType = null;
  11160. this.events = new EventDispatcher();
  11161. this.isScriptableValueNode = true;
  11162. }
  11163. get isScriptableOutputNode() {
  11164. return this.outputType !== null;
  11165. }
  11166. set value( val ) {
  11167. if ( this._value === val ) return;
  11168. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  11169. URL.revokeObjectURL( this._cache );
  11170. this._cache = null;
  11171. }
  11172. this._value = val;
  11173. this.events.dispatchEvent( { type: 'change' } );
  11174. this.refresh();
  11175. }
  11176. get value() {
  11177. return this._value;
  11178. }
  11179. refresh() {
  11180. this.events.dispatchEvent( { type: 'refresh' } );
  11181. }
  11182. getValue() {
  11183. const value = this.value;
  11184. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  11185. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  11186. } else if ( value && value.value !== null && value.value !== undefined && (
  11187. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  11188. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  11189. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  11190. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  11191. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  11192. ( this.inputType === 'Color' && value.value.isColor ) ||
  11193. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  11194. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  11195. ) ) {
  11196. return value.value;
  11197. }
  11198. return this._cache || value;
  11199. }
  11200. getNodeType( builder ) {
  11201. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  11202. }
  11203. setup() {
  11204. return this.value && this.value.isNode ? this.value : float();
  11205. }
  11206. serialize( data ) {
  11207. super.serialize( data );
  11208. if ( this.value !== null ) {
  11209. if ( this.inputType === 'ArrayBuffer' ) {
  11210. data.value = arrayBufferToBase64( this.value );
  11211. } else {
  11212. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  11213. }
  11214. } else {
  11215. data.value = null;
  11216. }
  11217. data.inputType = this.inputType;
  11218. data.outputType = this.outputType;
  11219. }
  11220. deserialize( data ) {
  11221. super.deserialize( data );
  11222. let value = null;
  11223. if ( data.value !== null ) {
  11224. if ( data.inputType === 'ArrayBuffer' ) {
  11225. value = base64ToArrayBuffer( data.value );
  11226. } else if ( data.inputType === 'Texture' ) {
  11227. value = data.meta.textures[ data.value ];
  11228. } else {
  11229. value = data.meta.nodes[ data.value ] || null;
  11230. }
  11231. }
  11232. this.value = value;
  11233. this.inputType = data.inputType;
  11234. this.outputType = data.outputType;
  11235. }
  11236. }
  11237. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  11238. class Resources extends Map {
  11239. get( key, callback = null, ...params ) {
  11240. if ( this.has( key ) ) return super.get( key );
  11241. if ( callback !== null ) {
  11242. const value = callback( ...params );
  11243. this.set( key, value );
  11244. return value;
  11245. }
  11246. }
  11247. }
  11248. class Parameters {
  11249. constructor( scriptableNode ) {
  11250. this.scriptableNode = scriptableNode;
  11251. }
  11252. get parameters() {
  11253. return this.scriptableNode.parameters;
  11254. }
  11255. get layout() {
  11256. return this.scriptableNode.getLayout();
  11257. }
  11258. getInputLayout( id ) {
  11259. return this.scriptableNode.getInputLayout( id );
  11260. }
  11261. get( name ) {
  11262. const param = this.parameters[ name ];
  11263. const value = param ? param.getValue() : null;
  11264. return value;
  11265. }
  11266. }
  11267. const ScriptableNodeResources = new Resources();
  11268. class ScriptableNode extends Node {
  11269. static get type() {
  11270. return 'ScriptableNode';
  11271. }
  11272. constructor( codeNode = null, parameters = {} ) {
  11273. super();
  11274. this.codeNode = codeNode;
  11275. this.parameters = parameters;
  11276. this._local = new Resources();
  11277. this._output = scriptableValue();
  11278. this._outputs = {};
  11279. this._source = this.source;
  11280. this._method = null;
  11281. this._object = null;
  11282. this._value = null;
  11283. this._needsOutputUpdate = true;
  11284. this.onRefresh = this.onRefresh.bind( this );
  11285. this.isScriptableNode = true;
  11286. }
  11287. get source() {
  11288. return this.codeNode ? this.codeNode.code : '';
  11289. }
  11290. setLocal( name, value ) {
  11291. return this._local.set( name, value );
  11292. }
  11293. getLocal( name ) {
  11294. return this._local.get( name );
  11295. }
  11296. onRefresh() {
  11297. this._refresh();
  11298. }
  11299. getInputLayout( id ) {
  11300. for ( const element of this.getLayout() ) {
  11301. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  11302. return element;
  11303. }
  11304. }
  11305. }
  11306. getOutputLayout( id ) {
  11307. for ( const element of this.getLayout() ) {
  11308. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  11309. return element;
  11310. }
  11311. }
  11312. }
  11313. setOutput( name, value ) {
  11314. const outputs = this._outputs;
  11315. if ( outputs[ name ] === undefined ) {
  11316. outputs[ name ] = scriptableValue( value );
  11317. } else {
  11318. outputs[ name ].value = value;
  11319. }
  11320. return this;
  11321. }
  11322. getOutput( name ) {
  11323. return this._outputs[ name ];
  11324. }
  11325. getParameter( name ) {
  11326. return this.parameters[ name ];
  11327. }
  11328. setParameter( name, value ) {
  11329. const parameters = this.parameters;
  11330. if ( value && value.isScriptableNode ) {
  11331. this.deleteParameter( name );
  11332. parameters[ name ] = value;
  11333. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  11334. } else if ( value && value.isScriptableValueNode ) {
  11335. this.deleteParameter( name );
  11336. parameters[ name ] = value;
  11337. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11338. } else if ( parameters[ name ] === undefined ) {
  11339. parameters[ name ] = scriptableValue( value );
  11340. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11341. } else {
  11342. parameters[ name ].value = value;
  11343. }
  11344. return this;
  11345. }
  11346. getValue() {
  11347. return this.getDefaultOutput().getValue();
  11348. }
  11349. deleteParameter( name ) {
  11350. let valueNode = this.parameters[ name ];
  11351. if ( valueNode ) {
  11352. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11353. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  11354. }
  11355. return this;
  11356. }
  11357. clearParameters() {
  11358. for ( const name of Object.keys( this.parameters ) ) {
  11359. this.deleteParameter( name );
  11360. }
  11361. this.needsUpdate = true;
  11362. return this;
  11363. }
  11364. call( name, ...params ) {
  11365. const object = this.getObject();
  11366. const method = object[ name ];
  11367. if ( typeof method === 'function' ) {
  11368. return method( ...params );
  11369. }
  11370. }
  11371. async callAsync( name, ...params ) {
  11372. const object = this.getObject();
  11373. const method = object[ name ];
  11374. if ( typeof method === 'function' ) {
  11375. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  11376. }
  11377. }
  11378. getNodeType( builder ) {
  11379. return this.getDefaultOutputNode().getNodeType( builder );
  11380. }
  11381. refresh( output = null ) {
  11382. if ( output !== null ) {
  11383. this.getOutput( output ).refresh();
  11384. } else {
  11385. this._refresh();
  11386. }
  11387. }
  11388. getObject() {
  11389. if ( this.needsUpdate ) this.dispose();
  11390. if ( this._object !== null ) return this._object;
  11391. //
  11392. const refresh = () => this.refresh();
  11393. const setOutput = ( id, value ) => this.setOutput( id, value );
  11394. const parameters = new Parameters( this );
  11395. const THREE = ScriptableNodeResources.get( 'THREE' );
  11396. const TSL = ScriptableNodeResources.get( 'TSL' );
  11397. const method = this.getMethod( this.codeNode );
  11398. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  11399. this._object = method( ...params );
  11400. const layout = this._object.layout;
  11401. if ( layout ) {
  11402. if ( layout.cache === false ) {
  11403. this._local.clear();
  11404. }
  11405. // default output
  11406. this._output.outputType = layout.outputType || null;
  11407. if ( Array.isArray( layout.elements ) ) {
  11408. for ( const element of layout.elements ) {
  11409. const id = element.id || element.name;
  11410. if ( element.inputType ) {
  11411. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  11412. this.getParameter( id ).inputType = element.inputType;
  11413. }
  11414. if ( element.outputType ) {
  11415. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  11416. this.getOutput( id ).outputType = element.outputType;
  11417. }
  11418. }
  11419. }
  11420. }
  11421. return this._object;
  11422. }
  11423. deserialize( data ) {
  11424. super.deserialize( data );
  11425. for ( const name in this.parameters ) {
  11426. let valueNode = this.parameters[ name ];
  11427. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11428. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  11429. }
  11430. }
  11431. getLayout() {
  11432. return this.getObject().layout;
  11433. }
  11434. getDefaultOutputNode() {
  11435. const output = this.getDefaultOutput().value;
  11436. if ( output && output.isNode ) {
  11437. return output;
  11438. }
  11439. return float();
  11440. }
  11441. getDefaultOutput() {
  11442. return this._exec()._output;
  11443. }
  11444. getMethod() {
  11445. if ( this.needsUpdate ) this.dispose();
  11446. if ( this._method !== null ) return this._method;
  11447. //
  11448. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  11449. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  11450. const properties = interfaceProps.join( ', ' );
  11451. const declarations = 'var ' + properties + '; var output = {};\n';
  11452. const returns = '\nreturn { ...output, ' + properties + ' };';
  11453. const code = declarations + this.codeNode.code + returns;
  11454. //
  11455. this._method = new Function( ...parametersProps, code );
  11456. return this._method;
  11457. }
  11458. dispose() {
  11459. if ( this._method === null ) return;
  11460. if ( this._object && typeof this._object.dispose === 'function' ) {
  11461. this._object.dispose();
  11462. }
  11463. this._method = null;
  11464. this._object = null;
  11465. this._source = null;
  11466. this._value = null;
  11467. this._needsOutputUpdate = true;
  11468. this._output.value = null;
  11469. this._outputs = {};
  11470. }
  11471. setup() {
  11472. return this.getDefaultOutputNode();
  11473. }
  11474. getCacheKey( force ) {
  11475. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  11476. for ( const param in this.parameters ) {
  11477. values.push( this.parameters[ param ].getCacheKey( force ) );
  11478. }
  11479. return hashArray( values );
  11480. }
  11481. set needsUpdate( value ) {
  11482. if ( value === true ) this.dispose();
  11483. }
  11484. get needsUpdate() {
  11485. return this.source !== this._source;
  11486. }
  11487. _exec() {
  11488. if ( this.codeNode === null ) return this;
  11489. if ( this._needsOutputUpdate === true ) {
  11490. this._value = this.call( 'main' );
  11491. this._needsOutputUpdate = false;
  11492. }
  11493. this._output.value = this._value;
  11494. return this;
  11495. }
  11496. _refresh() {
  11497. this.needsUpdate = true;
  11498. this._exec();
  11499. this._output.refresh();
  11500. }
  11501. }
  11502. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  11503. class FogNode extends Node {
  11504. static get type() {
  11505. return 'FogNode';
  11506. }
  11507. constructor( colorNode, factorNode ) {
  11508. super( 'float' );
  11509. this.isFogNode = true;
  11510. this.colorNode = colorNode;
  11511. this.factorNode = factorNode;
  11512. }
  11513. getViewZNode( builder ) {
  11514. let viewZ;
  11515. const getViewZ = builder.context.getViewZ;
  11516. if ( getViewZ !== undefined ) {
  11517. viewZ = getViewZ( this );
  11518. }
  11519. return ( viewZ || positionView.z ).negate();
  11520. }
  11521. setup() {
  11522. return this.factorNode;
  11523. }
  11524. }
  11525. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  11526. class FogRangeNode extends FogNode {
  11527. static get type() {
  11528. return 'FogRangeNode';
  11529. }
  11530. constructor( colorNode, nearNode, farNode ) {
  11531. super( colorNode );
  11532. this.isFogRangeNode = true;
  11533. this.nearNode = nearNode;
  11534. this.farNode = farNode;
  11535. }
  11536. setup( builder ) {
  11537. const viewZ = this.getViewZNode( builder );
  11538. return smoothstep( this.nearNode, this.farNode, viewZ );
  11539. }
  11540. }
  11541. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  11542. class FogExp2Node extends FogNode {
  11543. static get type() {
  11544. return 'FogExp2Node';
  11545. }
  11546. constructor( colorNode, densityNode ) {
  11547. super( colorNode );
  11548. this.isFogExp2Node = true;
  11549. this.densityNode = densityNode;
  11550. }
  11551. setup( builder ) {
  11552. const viewZ = this.getViewZNode( builder );
  11553. const density = this.densityNode;
  11554. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  11555. }
  11556. }
  11557. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  11558. let min = null;
  11559. let max = null;
  11560. class RangeNode extends Node {
  11561. static get type() {
  11562. return 'RangeNode';
  11563. }
  11564. constructor( minNode = float(), maxNode = float() ) {
  11565. super();
  11566. this.minNode = minNode;
  11567. this.maxNode = maxNode;
  11568. }
  11569. getVectorLength( builder ) {
  11570. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  11571. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  11572. return minLength > maxLength ? minLength : maxLength;
  11573. }
  11574. getNodeType( builder ) {
  11575. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  11576. }
  11577. setup( builder ) {
  11578. const object = builder.object;
  11579. let output = null;
  11580. if ( object.count > 1 ) {
  11581. const minValue = this.minNode.value;
  11582. const maxValue = this.maxNode.value;
  11583. const minLength = builder.getTypeLength( getValueType( minValue ) );
  11584. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  11585. min = min || new Vector4();
  11586. max = max || new Vector4();
  11587. min.setScalar( 0 );
  11588. max.setScalar( 0 );
  11589. if ( minLength === 1 ) min.setScalar( minValue );
  11590. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  11591. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  11592. if ( maxLength === 1 ) max.setScalar( maxValue );
  11593. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  11594. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  11595. const stride = 4;
  11596. const length = stride * object.count;
  11597. const array = new Float32Array( length );
  11598. for ( let i = 0; i < length; i ++ ) {
  11599. const index = i % stride;
  11600. const minElementValue = min.getComponent( index );
  11601. const maxElementValue = max.getComponent( index );
  11602. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  11603. }
  11604. const nodeType = this.getNodeType( builder );
  11605. if ( object.count <= 4096 ) {
  11606. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  11607. } else {
  11608. // TODO: Improve anonymous buffer attribute creation removing this part
  11609. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  11610. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  11611. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  11612. }
  11613. } else {
  11614. output = float( 0 );
  11615. }
  11616. return output;
  11617. }
  11618. }
  11619. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  11620. class ComputeBuiltinNode extends Node {
  11621. static get type() {
  11622. return 'ComputeBuiltinNode';
  11623. }
  11624. constructor( builtinName, nodeType ) {
  11625. super( nodeType );
  11626. this._builtinName = builtinName;
  11627. }
  11628. getHash( builder ) {
  11629. return this.getBuiltinName( builder );
  11630. }
  11631. getNodeType( /*builder*/ ) {
  11632. return this.nodeType;
  11633. }
  11634. setBuiltinName( builtinName ) {
  11635. this._builtinName = builtinName;
  11636. return this;
  11637. }
  11638. getBuiltinName( /*builder*/ ) {
  11639. return this._builtinName;
  11640. }
  11641. hasBuiltin( builder ) {
  11642. builder.hasBuiltin( this._builtinName );
  11643. }
  11644. generate( builder, output ) {
  11645. const builtinName = this.getBuiltinName( builder );
  11646. const nodeType = this.getNodeType( builder );
  11647. if ( builder.shaderStage === 'compute' ) {
  11648. return builder.format( builtinName, nodeType, output );
  11649. } else {
  11650. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  11651. return builder.generateConst( nodeType );
  11652. }
  11653. }
  11654. serialize( data ) {
  11655. super.serialize( data );
  11656. data.global = this.global;
  11657. data._builtinName = this._builtinName;
  11658. }
  11659. deserialize( data ) {
  11660. super.deserialize( data );
  11661. this.global = data.global;
  11662. this._builtinName = data._builtinName;
  11663. }
  11664. }
  11665. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  11666. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  11667. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  11668. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  11669. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  11670. class BarrierNode extends Node {
  11671. constructor( scope ) {
  11672. super();
  11673. this.scope = scope;
  11674. }
  11675. generate( builder ) {
  11676. const { scope } = this;
  11677. const { renderer } = builder;
  11678. if ( renderer.backend.isWebGLBackend === true ) {
  11679. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  11680. } else {
  11681. builder.addLineFlowCode( `${scope}Barrier()`, this );
  11682. }
  11683. }
  11684. }
  11685. const barrier = nodeProxy( BarrierNode );
  11686. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  11687. const storageBarrier = () => barrier( 'storage' ).append();
  11688. const textureBarrier = () => barrier( 'texture' ).append();
  11689. class WorkgroupInfoElementNode extends ArrayElementNode {
  11690. constructor( workgroupInfoNode, indexNode ) {
  11691. super( workgroupInfoNode, indexNode );
  11692. this.isWorkgroupInfoElementNode = true;
  11693. }
  11694. generate( builder, output ) {
  11695. let snippet;
  11696. const isAssignContext = builder.context.assign;
  11697. snippet = super.generate( builder );
  11698. if ( isAssignContext !== true ) {
  11699. const type = this.getNodeType( builder );
  11700. snippet = builder.format( snippet, type, output );
  11701. }
  11702. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  11703. return snippet;
  11704. }
  11705. }
  11706. class WorkgroupInfoNode extends Node {
  11707. constructor( scope, bufferType, bufferCount = 0 ) {
  11708. super( bufferType );
  11709. this.bufferType = bufferType;
  11710. this.bufferCount = bufferCount;
  11711. this.isWorkgroupInfoNode = true;
  11712. this.scope = scope;
  11713. }
  11714. label( name ) {
  11715. this.name = name;
  11716. return this;
  11717. }
  11718. getHash() {
  11719. return this.uuid;
  11720. }
  11721. setScope( scope ) {
  11722. this.scope = scope;
  11723. return this;
  11724. }
  11725. getInputType( /*builder*/ ) {
  11726. return `${this.scope}Array`;
  11727. }
  11728. element( indexNode ) {
  11729. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  11730. }
  11731. generate( builder ) {
  11732. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  11733. }
  11734. }
  11735. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  11736. class AtomicFunctionNode extends TempNode {
  11737. static get type() {
  11738. return 'AtomicFunctionNode';
  11739. }
  11740. constructor( method, pointerNode, valueNode, storeNode = null ) {
  11741. super( 'uint' );
  11742. this.method = method;
  11743. this.pointerNode = pointerNode;
  11744. this.valueNode = valueNode;
  11745. this.storeNode = storeNode;
  11746. }
  11747. getInputType( builder ) {
  11748. return this.pointerNode.getNodeType( builder );
  11749. }
  11750. getNodeType( builder ) {
  11751. return this.getInputType( builder );
  11752. }
  11753. generate( builder ) {
  11754. const method = this.method;
  11755. const type = this.getNodeType( builder );
  11756. const inputType = this.getInputType( builder );
  11757. const a = this.pointerNode;
  11758. const b = this.valueNode;
  11759. const params = [];
  11760. params.push( `&${ a.build( builder, inputType ) }` );
  11761. params.push( b.build( builder, inputType ) );
  11762. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  11763. if ( this.storeNode !== null ) {
  11764. const varSnippet = this.storeNode.build( builder, inputType );
  11765. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  11766. } else {
  11767. builder.addLineFlowCode( methodSnippet, this );
  11768. }
  11769. }
  11770. }
  11771. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  11772. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  11773. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  11774. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  11775. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  11776. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  11777. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  11778. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  11779. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  11780. const atomicNode = nodeProxy( AtomicFunctionNode );
  11781. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  11782. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  11783. node.append();
  11784. return node;
  11785. };
  11786. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  11787. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  11788. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  11789. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  11790. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  11791. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  11792. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  11793. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  11794. let uniformsLib;
  11795. function getLightData( light ) {
  11796. uniformsLib = uniformsLib || new WeakMap();
  11797. let uniforms = uniformsLib.get( light );
  11798. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  11799. return uniforms;
  11800. }
  11801. function lightPosition( light ) {
  11802. const data = getLightData( light );
  11803. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11804. }
  11805. function lightTargetPosition( light ) {
  11806. const data = getLightData( light );
  11807. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11808. }
  11809. function lightViewPosition( light ) {
  11810. const data = getLightData( light );
  11811. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11812. self.value = self.value || new Vector3();
  11813. self.value.setFromMatrixPosition( light.matrixWorld );
  11814. self.value.applyMatrix4( camera.matrixWorldInverse );
  11815. } ) );
  11816. }
  11817. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11818. const sortLights = ( lights ) => {
  11819. return lights.sort( ( a, b ) => a.id - b.id );
  11820. };
  11821. const getLightNodeById = ( id, lightNodes ) => {
  11822. for ( const lightNode of lightNodes ) {
  11823. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11824. return lightNode;
  11825. }
  11826. }
  11827. return null;
  11828. };
  11829. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11830. class LightsNode extends Node {
  11831. static get type() {
  11832. return 'LightsNode';
  11833. }
  11834. constructor() {
  11835. super( 'vec3' );
  11836. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11837. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11838. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11839. this._lights = [];
  11840. this._lightNodes = null;
  11841. this._lightNodesHash = null;
  11842. this.global = true;
  11843. }
  11844. getHash( builder ) {
  11845. if ( this._lightNodesHash === null ) {
  11846. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11847. const hash = [];
  11848. for ( const lightNode of this._lightNodes ) {
  11849. hash.push( lightNode.getSelf().getHash() );
  11850. }
  11851. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11852. }
  11853. return this._lightNodesHash;
  11854. }
  11855. analyze( builder ) {
  11856. const properties = builder.getDataFromNode( this );
  11857. for ( const node of properties.nodes ) {
  11858. node.build( builder );
  11859. }
  11860. }
  11861. setupLightsNode( builder ) {
  11862. const lightNodes = [];
  11863. const previousLightNodes = this._lightNodes;
  11864. const lights = sortLights( this._lights );
  11865. const nodeLibrary = builder.renderer.library;
  11866. for ( const light of lights ) {
  11867. if ( light.isNode ) {
  11868. lightNodes.push( nodeObject( light ) );
  11869. } else {
  11870. let lightNode = null;
  11871. if ( previousLightNodes !== null ) {
  11872. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11873. }
  11874. if ( lightNode === null ) {
  11875. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11876. if ( lightNodeClass === null ) {
  11877. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11878. continue;
  11879. }
  11880. let lightNode = null;
  11881. if ( ! _lightsNodeRef.has( light ) ) {
  11882. lightNode = nodeObject( new lightNodeClass( light ) );
  11883. _lightsNodeRef.set( light, lightNode );
  11884. } else {
  11885. lightNode = _lightsNodeRef.get( light );
  11886. }
  11887. lightNodes.push( lightNode );
  11888. }
  11889. }
  11890. }
  11891. this._lightNodes = lightNodes;
  11892. }
  11893. setupLights( builder, lightNodes ) {
  11894. for ( const lightNode of lightNodes ) {
  11895. lightNode.build( builder );
  11896. }
  11897. }
  11898. setup( builder ) {
  11899. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11900. const context = builder.context;
  11901. const lightingModel = context.lightingModel;
  11902. let outgoingLightNode = this.outgoingLightNode;
  11903. if ( lightingModel ) {
  11904. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11905. context.outgoingLight = outgoingLightNode;
  11906. const stack = builder.addStack();
  11907. //
  11908. const properties = builder.getDataFromNode( this );
  11909. properties.nodes = stack.nodes;
  11910. //
  11911. lightingModel.start( context, stack, builder );
  11912. // lights
  11913. this.setupLights( builder, _lightNodes );
  11914. //
  11915. lightingModel.indirect( context, stack, builder );
  11916. //
  11917. const { backdrop, backdropAlpha } = context;
  11918. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11919. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11920. if ( backdrop !== null ) {
  11921. if ( backdropAlpha !== null ) {
  11922. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11923. } else {
  11924. totalDiffuse = vec3( backdrop );
  11925. }
  11926. context.material.transparent = true;
  11927. }
  11928. totalDiffuseNode.assign( totalDiffuse );
  11929. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11930. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11931. //
  11932. lightingModel.finish( context, stack, builder );
  11933. //
  11934. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11935. }
  11936. return outgoingLightNode;
  11937. }
  11938. setLights( lights ) {
  11939. this._lights = lights;
  11940. this._lightNodes = null;
  11941. this._lightNodesHash = null;
  11942. return this;
  11943. }
  11944. getLights() {
  11945. return this._lights;
  11946. }
  11947. get hasLights() {
  11948. return this._lights.length > 0;
  11949. }
  11950. }
  11951. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11952. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  11953. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  11954. let dist = positionWorld.sub( position ).length();
  11955. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  11956. dist = dist.saturate(); // clamp to [ 0, 1 ]
  11957. return dist;
  11958. } );
  11959. const linearShadowDistance = ( light ) => {
  11960. const camera = light.shadow.camera;
  11961. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  11962. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  11963. const referencePosition = objectPosition( light );
  11964. return linearDistance( referencePosition, nearDistance, farDistance );
  11965. };
  11966. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11967. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11968. } );
  11969. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11970. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11971. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11972. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11973. const texelSize = vec2( 1 ).div( mapSize );
  11974. const dx0 = texelSize.x.negate().mul( radius );
  11975. const dy0 = texelSize.y.negate().mul( radius );
  11976. const dx1 = texelSize.x.mul( radius );
  11977. const dy1 = texelSize.y.mul( radius );
  11978. const dx2 = dx0.div( 2 );
  11979. const dy2 = dy0.div( 2 );
  11980. const dx3 = dx1.div( 2 );
  11981. const dy3 = dy1.div( 2 );
  11982. return add(
  11983. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11984. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11985. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11986. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11987. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11988. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11989. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11990. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11991. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11992. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11993. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11994. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11995. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11996. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11997. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11998. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11999. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  12000. ).mul( 1 / 17 );
  12001. } );
  12002. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  12003. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  12004. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12005. const texelSize = vec2( 1 ).div( mapSize );
  12006. const dx = texelSize.x;
  12007. const dy = texelSize.y;
  12008. const uv = shadowCoord.xy;
  12009. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  12010. uv.subAssign( f.mul( texelSize ) );
  12011. return add(
  12012. depthCompare( uv, shadowCoord.z ),
  12013. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  12014. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  12015. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  12016. mix(
  12017. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  12018. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  12019. f.x
  12020. ),
  12021. mix(
  12022. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  12023. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  12024. f.x
  12025. ),
  12026. mix(
  12027. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  12028. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  12029. f.y
  12030. ),
  12031. mix(
  12032. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  12033. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  12034. f.y
  12035. ),
  12036. mix(
  12037. mix(
  12038. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  12039. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  12040. f.x
  12041. ),
  12042. mix(
  12043. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  12044. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  12045. f.x
  12046. ),
  12047. f.y
  12048. )
  12049. ).mul( 1 / 9 );
  12050. } );
  12051. // VSM
  12052. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  12053. const occlusion = float( 1 ).toVar();
  12054. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  12055. const hardShadow = step( shadowCoord.z, distribution.x );
  12056. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  12057. const distance = shadowCoord.z.sub( distribution.x );
  12058. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  12059. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  12060. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  12061. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  12062. } );
  12063. return occlusion;
  12064. } );
  12065. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  12066. const mean = float( 0 ).toVar();
  12067. const squaredMean = float( 0 ).toVar();
  12068. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12069. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12070. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12071. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12072. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  12073. mean.addAssign( depth );
  12074. squaredMean.addAssign( depth.mul( depth ) );
  12075. } );
  12076. mean.divAssign( samples );
  12077. squaredMean.divAssign( samples );
  12078. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12079. return vec2( mean, std_dev );
  12080. } );
  12081. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  12082. const mean = float( 0 ).toVar();
  12083. const squaredMean = float( 0 ).toVar();
  12084. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12085. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12086. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12087. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12088. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  12089. mean.addAssign( distribution.x );
  12090. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  12091. } );
  12092. mean.divAssign( samples );
  12093. squaredMean.divAssign( samples );
  12094. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12095. return vec2( mean, std_dev );
  12096. } );
  12097. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  12098. //
  12099. let _overrideMaterial = null;
  12100. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  12101. class ShadowNode extends Node {
  12102. static get type() {
  12103. return 'ShadowNode';
  12104. }
  12105. constructor( light, shadow = null ) {
  12106. super();
  12107. this.light = light;
  12108. this.shadow = shadow || light.shadow;
  12109. this.shadowMap = null;
  12110. this.vsmShadowMapVertical = null;
  12111. this.vsmShadowMapHorizontal = null;
  12112. this.vsmMaterialVertical = null;
  12113. this.vsmMaterialHorizontal = null;
  12114. this.updateBeforeType = NodeUpdateType.RENDER;
  12115. this._node = null;
  12116. this.isShadowNode = true;
  12117. }
  12118. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  12119. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  12120. .and( shadowCoord.x.lessThanEqual( 1 ) )
  12121. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  12122. .and( shadowCoord.y.lessThanEqual( 1 ) )
  12123. .and( shadowCoord.z.lessThanEqual( 1 ) );
  12124. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  12125. return frustumTest.select( shadowNode, float( 1 ) );
  12126. }
  12127. setupShadowCoord( builder, shadowPosition ) {
  12128. const { shadow } = this;
  12129. const { renderer } = builder;
  12130. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12131. let shadowCoord = shadowPosition;
  12132. let coordZ;
  12133. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  12134. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  12135. coordZ = shadowCoord.z;
  12136. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  12137. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  12138. }
  12139. } else {
  12140. const w = shadowCoord.w;
  12141. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  12142. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  12143. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  12144. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  12145. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  12146. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  12147. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  12148. }
  12149. shadowCoord = vec3(
  12150. shadowCoord.x,
  12151. shadowCoord.y.oneMinus(), // follow webgpu standards
  12152. coordZ.add( bias )
  12153. );
  12154. return shadowCoord;
  12155. }
  12156. getShadowFilterFn( type ) {
  12157. return _shadowFilterLib[ type ];
  12158. }
  12159. setupShadow( builder ) {
  12160. const { renderer } = builder;
  12161. const { light, shadow } = this;
  12162. const shadowMapType = renderer.shadowMap.type;
  12163. if ( _overrideMaterial === null ) {
  12164. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  12165. _overrideMaterial = new NodeMaterial();
  12166. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  12167. _overrideMaterial.depthNode = depthNode;
  12168. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  12169. _overrideMaterial.name = 'ShadowMaterial';
  12170. }
  12171. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12172. depthTexture.compareFunction = LessCompare;
  12173. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12174. shadowMap.depthTexture = depthTexture;
  12175. shadow.camera.updateProjectionMatrix();
  12176. // VSM
  12177. if ( shadowMapType === VSMShadowMap ) {
  12178. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12179. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12180. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12181. const shadowPassVertical = texture( depthTexture );
  12182. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12183. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12184. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12185. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12186. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12187. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12188. material.name = 'VSMVertical';
  12189. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12190. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12191. material.name = 'VSMHorizontal';
  12192. }
  12193. //
  12194. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12195. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12196. const shadowPosition = uniform( shadow.matrix ).setGroup( renderGroup ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  12197. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  12198. //
  12199. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  12200. if ( filterFn === null ) {
  12201. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12202. }
  12203. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  12204. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  12205. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12206. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12207. this.shadowMap = shadowMap;
  12208. this.shadow.map = shadowMap;
  12209. return shadowOutput;
  12210. }
  12211. setup( builder ) {
  12212. if ( builder.renderer.shadowMap.enabled === false ) return;
  12213. return Fn( ( { material } ) => {
  12214. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  12215. let node = this._node;
  12216. if ( node === null ) {
  12217. this._node = node = this.setupShadow( builder );
  12218. }
  12219. if ( builder.material.shadowNode ) { // @deprecated, r171
  12220. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12221. }
  12222. if ( builder.material.receivedShadowNode ) {
  12223. node = builder.material.receivedShadowNode( node );
  12224. }
  12225. return node;
  12226. } )();
  12227. }
  12228. renderShadow( frame ) {
  12229. const { shadow, shadowMap, light } = this;
  12230. const { renderer, scene } = frame;
  12231. shadow.updateMatrices( light );
  12232. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12233. renderer.render( scene, shadow.camera );
  12234. }
  12235. updateShadow( frame ) {
  12236. const { shadowMap, light, shadow } = this;
  12237. const { renderer, scene, camera } = frame;
  12238. const shadowType = renderer.shadowMap.type;
  12239. const depthVersion = shadowMap.depthTexture.version;
  12240. this._depthVersionCached = depthVersion;
  12241. const currentOverrideMaterial = scene.overrideMaterial;
  12242. scene.overrideMaterial = _overrideMaterial;
  12243. shadow.camera.layers.mask = camera.layers.mask;
  12244. const currentRenderTarget = renderer.getRenderTarget();
  12245. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12246. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12247. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12248. renderer.renderObject( object, ...params );
  12249. }
  12250. } );
  12251. renderer.setRenderTarget( shadowMap );
  12252. this.renderShadow( frame );
  12253. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12254. // vsm blur pass
  12255. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12256. this.vsmPass( renderer );
  12257. }
  12258. renderer.setRenderTarget( currentRenderTarget );
  12259. scene.overrideMaterial = currentOverrideMaterial;
  12260. }
  12261. vsmPass( renderer ) {
  12262. const { shadow } = this;
  12263. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12264. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12265. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12266. _quadMesh$1.material = this.vsmMaterialVertical;
  12267. _quadMesh$1.render( renderer );
  12268. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12269. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12270. _quadMesh$1.render( renderer );
  12271. }
  12272. dispose() {
  12273. this.shadowMap.dispose();
  12274. this.shadowMap = null;
  12275. if ( this.vsmShadowMapVertical !== null ) {
  12276. this.vsmShadowMapVertical.dispose();
  12277. this.vsmShadowMapVertical = null;
  12278. this.vsmMaterialVertical.dispose();
  12279. this.vsmMaterialVertical = null;
  12280. }
  12281. if ( this.vsmShadowMapHorizontal !== null ) {
  12282. this.vsmShadowMapHorizontal.dispose();
  12283. this.vsmShadowMapHorizontal = null;
  12284. this.vsmMaterialHorizontal.dispose();
  12285. this.vsmMaterialHorizontal = null;
  12286. }
  12287. this.updateBeforeType = NodeUpdateType.NONE;
  12288. }
  12289. updateBefore( frame ) {
  12290. const { shadow } = this;
  12291. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12292. if ( needsUpdate ) {
  12293. this.updateShadow( frame );
  12294. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12295. shadow.needsUpdate = false;
  12296. }
  12297. }
  12298. }
  12299. }
  12300. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12301. class AnalyticLightNode extends LightingNode {
  12302. static get type() {
  12303. return 'AnalyticLightNode';
  12304. }
  12305. constructor( light = null ) {
  12306. super();
  12307. this.updateType = NodeUpdateType.FRAME;
  12308. this.light = light;
  12309. this.color = new Color();
  12310. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  12311. this.baseColorNode = null;
  12312. this.shadowNode = null;
  12313. this.shadowColorNode = null;
  12314. this.isAnalyticLightNode = true;
  12315. }
  12316. getCacheKey() {
  12317. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12318. }
  12319. getHash() {
  12320. return this.light.uuid;
  12321. }
  12322. setupShadowNode() {
  12323. return shadow( this.light );
  12324. }
  12325. setupShadow( builder ) {
  12326. const { renderer } = builder;
  12327. if ( renderer.shadowMap.enabled === false ) return;
  12328. let shadowColorNode = this.shadowColorNode;
  12329. if ( shadowColorNode === null ) {
  12330. const customShadowNode = this.light.shadow.shadowNode;
  12331. let shadowNode;
  12332. if ( customShadowNode !== undefined ) {
  12333. shadowNode = nodeObject( customShadowNode );
  12334. } else {
  12335. shadowNode = this.setupShadowNode( builder );
  12336. }
  12337. this.shadowNode = shadowNode;
  12338. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12339. this.baseColorNode = this.colorNode;
  12340. }
  12341. //
  12342. this.colorNode = shadowColorNode;
  12343. }
  12344. setup( builder ) {
  12345. this.colorNode = this.baseColorNode || this.colorNode;
  12346. if ( this.light.castShadow ) {
  12347. if ( builder.object.receiveShadow ) {
  12348. this.setupShadow( builder );
  12349. }
  12350. } else if ( this.shadowNode !== null ) {
  12351. this.shadowNode.dispose();
  12352. this.shadowNode = null;
  12353. this.shadowColorNode = null;
  12354. }
  12355. }
  12356. update( /*frame*/ ) {
  12357. const { light } = this;
  12358. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12359. }
  12360. }
  12361. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12362. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12363. // based upon Frostbite 3 Moving to Physically-based Rendering
  12364. // page 32, equation 26: E[window1]
  12365. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12366. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12367. return cutoffDistance.greaterThan( 0 ).select(
  12368. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12369. distanceFalloff
  12370. );
  12371. } ); // validated
  12372. const _clearColor$2 = /*@__PURE__*/ new Color();
  12373. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  12374. // vector suitable for 2D texture mapping. This code uses the following layout for the
  12375. // 2D texture:
  12376. //
  12377. // xzXZ
  12378. // y Y
  12379. //
  12380. // Y - Positive y direction
  12381. // y - Negative y direction
  12382. // X - Positive x direction
  12383. // x - Negative x direction
  12384. // Z - Positive z direction
  12385. // z - Negative z direction
  12386. //
  12387. // Source and test bed:
  12388. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  12389. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  12390. const v = pos.toVar();
  12391. // Number of texels to avoid at the edge of each square
  12392. const absV = abs( v );
  12393. // Intersect unit cube
  12394. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  12395. absV.mulAssign( scaleToCube );
  12396. // Apply scale to avoid seams
  12397. // two texels less per square (one texel will do for NEAREST)
  12398. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  12399. // Unwrap
  12400. // space: -1 ... 1 range for each square
  12401. //
  12402. // #X## dim := ( 4 , 2 )
  12403. // # # center := ( 1 , 1 )
  12404. const planar = vec2( v.xy ).toVar();
  12405. const almostATexel = texelSizeY.mul( 1.5 );
  12406. const almostOne = almostATexel.oneMinus();
  12407. If( absV.z.greaterThanEqual( almostOne ), () => {
  12408. If( v.z.greaterThan( 0.0 ), () => {
  12409. planar.x.assign( sub( 4.0, v.x ) );
  12410. } );
  12411. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  12412. const signX = sign( v.x );
  12413. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  12414. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  12415. const signY = sign( v.y );
  12416. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  12417. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  12418. } );
  12419. // Transform to UV space
  12420. // scale := 0.5 / dim
  12421. // translate := ( center + 0.5 ) / dim
  12422. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  12423. } ).setLayout( {
  12424. name: 'cubeToUV',
  12425. type: 'vec2',
  12426. inputs: [
  12427. { name: 'pos', type: 'vec3' },
  12428. { name: 'texelSizeY', type: 'float' }
  12429. ]
  12430. } );
  12431. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  12432. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  12433. } );
  12434. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  12435. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12436. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  12437. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  12438. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  12439. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  12440. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  12441. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  12442. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  12443. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  12444. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  12445. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  12446. .mul( 1.0 / 9.0 );
  12447. } );
  12448. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  12449. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  12450. // the vector from the light to the world-space position of the fragment.
  12451. const lightToPosition = shadowCoord.xyz.toVar();
  12452. const lightToPositionLength = lightToPosition.length();
  12453. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  12454. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  12455. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12456. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  12457. const result = float( 1.0 ).toVar();
  12458. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  12459. // dp = normalized distance from light to fragment position
  12460. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  12461. dp.addAssign( bias );
  12462. // bd3D = base direction 3D
  12463. const bd3D = lightToPosition.normalize();
  12464. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  12465. // percentage-closer filtering
  12466. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  12467. } );
  12468. return result;
  12469. } );
  12470. const _viewport = /*@__PURE__*/ new Vector4();
  12471. const _viewportSize = /*@__PURE__*/ new Vector2();
  12472. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  12473. //
  12474. class PointShadowNode extends ShadowNode {
  12475. static get type() {
  12476. return 'PointShadowNode';
  12477. }
  12478. constructor( light, shadow = null ) {
  12479. super( light, shadow );
  12480. }
  12481. getShadowFilterFn( type ) {
  12482. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  12483. }
  12484. setupShadowCoord( builder, shadowPosition ) {
  12485. return shadowPosition;
  12486. }
  12487. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  12488. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  12489. }
  12490. renderShadow( frame ) {
  12491. const { shadow, shadowMap, light } = this;
  12492. const { renderer, scene } = frame;
  12493. const shadowFrameExtents = shadow.getFrameExtents();
  12494. _shadowMapSize.copy( shadow.mapSize );
  12495. _shadowMapSize.multiply( shadowFrameExtents );
  12496. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  12497. _viewportSize.copy( shadow.mapSize );
  12498. //
  12499. const previousAutoClear = renderer.autoClear;
  12500. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  12501. const previousClearAlpha = renderer.getClearAlpha();
  12502. renderer.autoClear = false;
  12503. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  12504. renderer.clear();
  12505. const viewportCount = shadow.getViewportCount();
  12506. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12507. const viewport = shadow.getViewport( vp );
  12508. const x = _viewportSize.x * viewport.x;
  12509. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  12510. _viewport.set(
  12511. x,
  12512. y,
  12513. _viewportSize.x * viewport.z,
  12514. _viewportSize.y * viewport.w
  12515. );
  12516. shadowMap.viewport.copy( _viewport );
  12517. shadow.updateMatrices( light, vp );
  12518. renderer.render( scene, shadow.camera );
  12519. }
  12520. //
  12521. renderer.autoClear = previousAutoClear;
  12522. renderer.setClearColor( previousClearColor, previousClearAlpha );
  12523. }
  12524. }
  12525. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  12526. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12527. const lightingModel = builder.context.lightingModel;
  12528. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12529. const lightDirection = lVector.normalize();
  12530. const lightDistance = lVector.length();
  12531. const lightAttenuation = getDistanceAttenuation( {
  12532. lightDistance,
  12533. cutoffDistance,
  12534. decayExponent
  12535. } );
  12536. const lightColor = color.mul( lightAttenuation );
  12537. const reflectedLight = builder.context.reflectedLight;
  12538. lightingModel.direct( {
  12539. lightDirection,
  12540. lightColor,
  12541. reflectedLight
  12542. }, builder.stack, builder );
  12543. } );
  12544. class PointLightNode extends AnalyticLightNode {
  12545. static get type() {
  12546. return 'PointLightNode';
  12547. }
  12548. constructor( light = null ) {
  12549. super( light );
  12550. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12551. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12552. }
  12553. update( frame ) {
  12554. const { light } = this;
  12555. super.update( frame );
  12556. this.cutoffDistanceNode.value = light.distance;
  12557. this.decayExponentNode.value = light.decay;
  12558. }
  12559. setupShadowNode() {
  12560. return pointShadow( this.light );
  12561. }
  12562. setup( builder ) {
  12563. super.setup( builder );
  12564. directPointLight( {
  12565. color: this.colorNode,
  12566. lightViewPosition: lightViewPosition( this.light ),
  12567. cutoffDistance: this.cutoffDistanceNode,
  12568. decayExponent: this.decayExponentNode
  12569. } ).append();
  12570. }
  12571. }
  12572. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12573. const uv = coord.mul( 2.0 );
  12574. const cx = uv.x.floor();
  12575. const cy = uv.y.floor();
  12576. const result = cx.add( cy ).mod( 2.0 );
  12577. return result.sign();
  12578. } );
  12579. // Three.js Transpiler
  12580. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12581. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12582. const f = float( f_immutable ).toVar();
  12583. const t = float( t_immutable ).toVar();
  12584. const b = bool( b_immutable ).toVar();
  12585. return select( b, t, f );
  12586. } ).setLayout( {
  12587. name: 'mx_select',
  12588. type: 'float',
  12589. inputs: [
  12590. { name: 'b', type: 'bool' },
  12591. { name: 't', type: 'float' },
  12592. { name: 'f', type: 'float' }
  12593. ]
  12594. } );
  12595. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12596. const b = bool( b_immutable ).toVar();
  12597. const val = float( val_immutable ).toVar();
  12598. return select( b, val.negate(), val );
  12599. } ).setLayout( {
  12600. name: 'mx_negate_if',
  12601. type: 'float',
  12602. inputs: [
  12603. { name: 'val', type: 'float' },
  12604. { name: 'b', type: 'bool' }
  12605. ]
  12606. } );
  12607. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12608. const x = float( x_immutable ).toVar();
  12609. return int( floor( x ) );
  12610. } ).setLayout( {
  12611. name: 'mx_floor',
  12612. type: 'int',
  12613. inputs: [
  12614. { name: 'x', type: 'float' }
  12615. ]
  12616. } );
  12617. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12618. const x = float( x_immutable ).toVar();
  12619. i.assign( mx_floor( x ) );
  12620. return x.sub( float( i ) );
  12621. } );
  12622. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12623. const t = float( t_immutable ).toVar();
  12624. const s = float( s_immutable ).toVar();
  12625. const v3 = float( v3_immutable ).toVar();
  12626. const v2 = float( v2_immutable ).toVar();
  12627. const v1 = float( v1_immutable ).toVar();
  12628. const v0 = float( v0_immutable ).toVar();
  12629. const s1 = float( sub( 1.0, s ) ).toVar();
  12630. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12631. } ).setLayout( {
  12632. name: 'mx_bilerp_0',
  12633. type: 'float',
  12634. inputs: [
  12635. { name: 'v0', type: 'float' },
  12636. { name: 'v1', type: 'float' },
  12637. { name: 'v2', type: 'float' },
  12638. { name: 'v3', type: 'float' },
  12639. { name: 's', type: 'float' },
  12640. { name: 't', type: 'float' }
  12641. ]
  12642. } );
  12643. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12644. const t = float( t_immutable ).toVar();
  12645. const s = float( s_immutable ).toVar();
  12646. const v3 = vec3( v3_immutable ).toVar();
  12647. const v2 = vec3( v2_immutable ).toVar();
  12648. const v1 = vec3( v1_immutable ).toVar();
  12649. const v0 = vec3( v0_immutable ).toVar();
  12650. const s1 = float( sub( 1.0, s ) ).toVar();
  12651. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12652. } ).setLayout( {
  12653. name: 'mx_bilerp_1',
  12654. type: 'vec3',
  12655. inputs: [
  12656. { name: 'v0', type: 'vec3' },
  12657. { name: 'v1', type: 'vec3' },
  12658. { name: 'v2', type: 'vec3' },
  12659. { name: 'v3', type: 'vec3' },
  12660. { name: 's', type: 'float' },
  12661. { name: 't', type: 'float' }
  12662. ]
  12663. } );
  12664. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12665. 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 ] ) => {
  12666. const r = float( r_immutable ).toVar();
  12667. const t = float( t_immutable ).toVar();
  12668. const s = float( s_immutable ).toVar();
  12669. const v7 = float( v7_immutable ).toVar();
  12670. const v6 = float( v6_immutable ).toVar();
  12671. const v5 = float( v5_immutable ).toVar();
  12672. const v4 = float( v4_immutable ).toVar();
  12673. const v3 = float( v3_immutable ).toVar();
  12674. const v2 = float( v2_immutable ).toVar();
  12675. const v1 = float( v1_immutable ).toVar();
  12676. const v0 = float( v0_immutable ).toVar();
  12677. const s1 = float( sub( 1.0, s ) ).toVar();
  12678. const t1 = float( sub( 1.0, t ) ).toVar();
  12679. const r1 = float( sub( 1.0, r ) ).toVar();
  12680. 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 ) ) ) ) ) );
  12681. } ).setLayout( {
  12682. name: 'mx_trilerp_0',
  12683. type: 'float',
  12684. inputs: [
  12685. { name: 'v0', type: 'float' },
  12686. { name: 'v1', type: 'float' },
  12687. { name: 'v2', type: 'float' },
  12688. { name: 'v3', type: 'float' },
  12689. { name: 'v4', type: 'float' },
  12690. { name: 'v5', type: 'float' },
  12691. { name: 'v6', type: 'float' },
  12692. { name: 'v7', type: 'float' },
  12693. { name: 's', type: 'float' },
  12694. { name: 't', type: 'float' },
  12695. { name: 'r', type: 'float' }
  12696. ]
  12697. } );
  12698. 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 ] ) => {
  12699. const r = float( r_immutable ).toVar();
  12700. const t = float( t_immutable ).toVar();
  12701. const s = float( s_immutable ).toVar();
  12702. const v7 = vec3( v7_immutable ).toVar();
  12703. const v6 = vec3( v6_immutable ).toVar();
  12704. const v5 = vec3( v5_immutable ).toVar();
  12705. const v4 = vec3( v4_immutable ).toVar();
  12706. const v3 = vec3( v3_immutable ).toVar();
  12707. const v2 = vec3( v2_immutable ).toVar();
  12708. const v1 = vec3( v1_immutable ).toVar();
  12709. const v0 = vec3( v0_immutable ).toVar();
  12710. const s1 = float( sub( 1.0, s ) ).toVar();
  12711. const t1 = float( sub( 1.0, t ) ).toVar();
  12712. const r1 = float( sub( 1.0, r ) ).toVar();
  12713. 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 ) ) ) ) ) );
  12714. } ).setLayout( {
  12715. name: 'mx_trilerp_1',
  12716. type: 'vec3',
  12717. inputs: [
  12718. { name: 'v0', type: 'vec3' },
  12719. { name: 'v1', type: 'vec3' },
  12720. { name: 'v2', type: 'vec3' },
  12721. { name: 'v3', type: 'vec3' },
  12722. { name: 'v4', type: 'vec3' },
  12723. { name: 'v5', type: 'vec3' },
  12724. { name: 'v6', type: 'vec3' },
  12725. { name: 'v7', type: 'vec3' },
  12726. { name: 's', type: 'float' },
  12727. { name: 't', type: 'float' },
  12728. { name: 'r', type: 'float' }
  12729. ]
  12730. } );
  12731. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12732. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12733. const y = float( y_immutable ).toVar();
  12734. const x = float( x_immutable ).toVar();
  12735. const hash = uint( hash_immutable ).toVar();
  12736. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12737. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12738. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12739. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12740. } ).setLayout( {
  12741. name: 'mx_gradient_float_0',
  12742. type: 'float',
  12743. inputs: [
  12744. { name: 'hash', type: 'uint' },
  12745. { name: 'x', type: 'float' },
  12746. { name: 'y', type: 'float' }
  12747. ]
  12748. } );
  12749. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12750. const z = float( z_immutable ).toVar();
  12751. const y = float( y_immutable ).toVar();
  12752. const x = float( x_immutable ).toVar();
  12753. const hash = uint( hash_immutable ).toVar();
  12754. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12755. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12756. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12757. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12758. } ).setLayout( {
  12759. name: 'mx_gradient_float_1',
  12760. type: 'float',
  12761. inputs: [
  12762. { name: 'hash', type: 'uint' },
  12763. { name: 'x', type: 'float' },
  12764. { name: 'y', type: 'float' },
  12765. { name: 'z', type: 'float' }
  12766. ]
  12767. } );
  12768. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12769. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12770. const y = float( y_immutable ).toVar();
  12771. const x = float( x_immutable ).toVar();
  12772. const hash = uvec3( hash_immutable ).toVar();
  12773. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12774. } ).setLayout( {
  12775. name: 'mx_gradient_vec3_0',
  12776. type: 'vec3',
  12777. inputs: [
  12778. { name: 'hash', type: 'uvec3' },
  12779. { name: 'x', type: 'float' },
  12780. { name: 'y', type: 'float' }
  12781. ]
  12782. } );
  12783. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12784. const z = float( z_immutable ).toVar();
  12785. const y = float( y_immutable ).toVar();
  12786. const x = float( x_immutable ).toVar();
  12787. const hash = uvec3( hash_immutable ).toVar();
  12788. 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 ) );
  12789. } ).setLayout( {
  12790. name: 'mx_gradient_vec3_1',
  12791. type: 'vec3',
  12792. inputs: [
  12793. { name: 'hash', type: 'uvec3' },
  12794. { name: 'x', type: 'float' },
  12795. { name: 'y', type: 'float' },
  12796. { name: 'z', type: 'float' }
  12797. ]
  12798. } );
  12799. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12800. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12801. const v = float( v_immutable ).toVar();
  12802. return mul( 0.6616, v );
  12803. } ).setLayout( {
  12804. name: 'mx_gradient_scale2d_0',
  12805. type: 'float',
  12806. inputs: [
  12807. { name: 'v', type: 'float' }
  12808. ]
  12809. } );
  12810. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12811. const v = float( v_immutable ).toVar();
  12812. return mul( 0.9820, v );
  12813. } ).setLayout( {
  12814. name: 'mx_gradient_scale3d_0',
  12815. type: 'float',
  12816. inputs: [
  12817. { name: 'v', type: 'float' }
  12818. ]
  12819. } );
  12820. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12821. const v = vec3( v_immutable ).toVar();
  12822. return mul( 0.6616, v );
  12823. } ).setLayout( {
  12824. name: 'mx_gradient_scale2d_1',
  12825. type: 'vec3',
  12826. inputs: [
  12827. { name: 'v', type: 'vec3' }
  12828. ]
  12829. } );
  12830. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12831. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12832. const v = vec3( v_immutable ).toVar();
  12833. return mul( 0.9820, v );
  12834. } ).setLayout( {
  12835. name: 'mx_gradient_scale3d_1',
  12836. type: 'vec3',
  12837. inputs: [
  12838. { name: 'v', type: 'vec3' }
  12839. ]
  12840. } );
  12841. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12842. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12843. const k = int( k_immutable ).toVar();
  12844. const x = uint( x_immutable ).toVar();
  12845. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12846. } ).setLayout( {
  12847. name: 'mx_rotl32',
  12848. type: 'uint',
  12849. inputs: [
  12850. { name: 'x', type: 'uint' },
  12851. { name: 'k', type: 'int' }
  12852. ]
  12853. } );
  12854. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12855. a.subAssign( c );
  12856. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12857. c.addAssign( b );
  12858. b.subAssign( a );
  12859. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12860. a.addAssign( c );
  12861. c.subAssign( b );
  12862. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12863. b.addAssign( a );
  12864. a.subAssign( c );
  12865. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12866. c.addAssign( b );
  12867. b.subAssign( a );
  12868. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12869. a.addAssign( c );
  12870. c.subAssign( b );
  12871. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12872. b.addAssign( a );
  12873. } );
  12874. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12875. const c = uint( c_immutable ).toVar();
  12876. const b = uint( b_immutable ).toVar();
  12877. const a = uint( a_immutable ).toVar();
  12878. c.bitXorAssign( b );
  12879. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12880. a.bitXorAssign( c );
  12881. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12882. b.bitXorAssign( a );
  12883. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12884. c.bitXorAssign( b );
  12885. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12886. a.bitXorAssign( c );
  12887. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12888. b.bitXorAssign( a );
  12889. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12890. c.bitXorAssign( b );
  12891. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12892. return c;
  12893. } ).setLayout( {
  12894. name: 'mx_bjfinal',
  12895. type: 'uint',
  12896. inputs: [
  12897. { name: 'a', type: 'uint' },
  12898. { name: 'b', type: 'uint' },
  12899. { name: 'c', type: 'uint' }
  12900. ]
  12901. } );
  12902. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12903. const bits = uint( bits_immutable ).toVar();
  12904. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12905. } ).setLayout( {
  12906. name: 'mx_bits_to_01',
  12907. type: 'float',
  12908. inputs: [
  12909. { name: 'bits', type: 'uint' }
  12910. ]
  12911. } );
  12912. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12913. const t = float( t_immutable ).toVar();
  12914. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12915. } ).setLayout( {
  12916. name: 'mx_fade',
  12917. type: 'float',
  12918. inputs: [
  12919. { name: 't', type: 'float' }
  12920. ]
  12921. } );
  12922. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12923. const x = int( x_immutable ).toVar();
  12924. const len = uint( uint( 1 ) ).toVar();
  12925. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12926. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12927. } ).setLayout( {
  12928. name: 'mx_hash_int_0',
  12929. type: 'uint',
  12930. inputs: [
  12931. { name: 'x', type: 'int' }
  12932. ]
  12933. } );
  12934. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12935. const y = int( y_immutable ).toVar();
  12936. const x = int( x_immutable ).toVar();
  12937. const len = uint( uint( 2 ) ).toVar();
  12938. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12939. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12940. a.addAssign( uint( x ) );
  12941. b.addAssign( uint( y ) );
  12942. return mx_bjfinal( a, b, c );
  12943. } ).setLayout( {
  12944. name: 'mx_hash_int_1',
  12945. type: 'uint',
  12946. inputs: [
  12947. { name: 'x', type: 'int' },
  12948. { name: 'y', type: 'int' }
  12949. ]
  12950. } );
  12951. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12952. const z = int( z_immutable ).toVar();
  12953. const y = int( y_immutable ).toVar();
  12954. const x = int( x_immutable ).toVar();
  12955. const len = uint( uint( 3 ) ).toVar();
  12956. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12957. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12958. a.addAssign( uint( x ) );
  12959. b.addAssign( uint( y ) );
  12960. c.addAssign( uint( z ) );
  12961. return mx_bjfinal( a, b, c );
  12962. } ).setLayout( {
  12963. name: 'mx_hash_int_2',
  12964. type: 'uint',
  12965. inputs: [
  12966. { name: 'x', type: 'int' },
  12967. { name: 'y', type: 'int' },
  12968. { name: 'z', type: 'int' }
  12969. ]
  12970. } );
  12971. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12972. const xx = int( xx_immutable ).toVar();
  12973. const z = int( z_immutable ).toVar();
  12974. const y = int( y_immutable ).toVar();
  12975. const x = int( x_immutable ).toVar();
  12976. const len = uint( uint( 4 ) ).toVar();
  12977. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12978. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12979. a.addAssign( uint( x ) );
  12980. b.addAssign( uint( y ) );
  12981. c.addAssign( uint( z ) );
  12982. mx_bjmix( a, b, c );
  12983. a.addAssign( uint( xx ) );
  12984. return mx_bjfinal( a, b, c );
  12985. } ).setLayout( {
  12986. name: 'mx_hash_int_3',
  12987. type: 'uint',
  12988. inputs: [
  12989. { name: 'x', type: 'int' },
  12990. { name: 'y', type: 'int' },
  12991. { name: 'z', type: 'int' },
  12992. { name: 'xx', type: 'int' }
  12993. ]
  12994. } );
  12995. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12996. const yy = int( yy_immutable ).toVar();
  12997. const xx = int( xx_immutable ).toVar();
  12998. const z = int( z_immutable ).toVar();
  12999. const y = int( y_immutable ).toVar();
  13000. const x = int( x_immutable ).toVar();
  13001. const len = uint( uint( 5 ) ).toVar();
  13002. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13003. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13004. a.addAssign( uint( x ) );
  13005. b.addAssign( uint( y ) );
  13006. c.addAssign( uint( z ) );
  13007. mx_bjmix( a, b, c );
  13008. a.addAssign( uint( xx ) );
  13009. b.addAssign( uint( yy ) );
  13010. return mx_bjfinal( a, b, c );
  13011. } ).setLayout( {
  13012. name: 'mx_hash_int_4',
  13013. type: 'uint',
  13014. inputs: [
  13015. { name: 'x', type: 'int' },
  13016. { name: 'y', type: 'int' },
  13017. { name: 'z', type: 'int' },
  13018. { name: 'xx', type: 'int' },
  13019. { name: 'yy', type: 'int' }
  13020. ]
  13021. } );
  13022. 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 ] );
  13023. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  13024. const y = int( y_immutable ).toVar();
  13025. const x = int( x_immutable ).toVar();
  13026. const h = uint( mx_hash_int( x, y ) ).toVar();
  13027. const result = uvec3().toVar();
  13028. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  13029. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  13030. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  13031. return result;
  13032. } ).setLayout( {
  13033. name: 'mx_hash_vec3_0',
  13034. type: 'uvec3',
  13035. inputs: [
  13036. { name: 'x', type: 'int' },
  13037. { name: 'y', type: 'int' }
  13038. ]
  13039. } );
  13040. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  13041. const z = int( z_immutable ).toVar();
  13042. const y = int( y_immutable ).toVar();
  13043. const x = int( x_immutable ).toVar();
  13044. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  13045. const result = uvec3().toVar();
  13046. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  13047. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  13048. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  13049. return result;
  13050. } ).setLayout( {
  13051. name: 'mx_hash_vec3_1',
  13052. type: 'uvec3',
  13053. inputs: [
  13054. { name: 'x', type: 'int' },
  13055. { name: 'y', type: 'int' },
  13056. { name: 'z', type: 'int' }
  13057. ]
  13058. } );
  13059. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  13060. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13061. const p = vec2( p_immutable ).toVar();
  13062. const X = int().toVar(), Y = int().toVar();
  13063. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13064. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13065. const u = float( mx_fade( fx ) ).toVar();
  13066. const v = float( mx_fade( fy ) ).toVar();
  13067. 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();
  13068. return mx_gradient_scale2d( result );
  13069. } ).setLayout( {
  13070. name: 'mx_perlin_noise_float_0',
  13071. type: 'float',
  13072. inputs: [
  13073. { name: 'p', type: 'vec2' }
  13074. ]
  13075. } );
  13076. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13077. const p = vec3( p_immutable ).toVar();
  13078. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13079. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13080. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13081. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  13082. const u = float( mx_fade( fx ) ).toVar();
  13083. const v = float( mx_fade( fy ) ).toVar();
  13084. const w = float( mx_fade( fz ) ).toVar();
  13085. 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();
  13086. return mx_gradient_scale3d( result );
  13087. } ).setLayout( {
  13088. name: 'mx_perlin_noise_float_1',
  13089. type: 'float',
  13090. inputs: [
  13091. { name: 'p', type: 'vec3' }
  13092. ]
  13093. } );
  13094. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  13095. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13096. const p = vec2( p_immutable ).toVar();
  13097. const X = int().toVar(), Y = int().toVar();
  13098. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13099. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13100. const u = float( mx_fade( fx ) ).toVar();
  13101. const v = float( mx_fade( fy ) ).toVar();
  13102. 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();
  13103. return mx_gradient_scale2d( result );
  13104. } ).setLayout( {
  13105. name: 'mx_perlin_noise_vec3_0',
  13106. type: 'vec3',
  13107. inputs: [
  13108. { name: 'p', type: 'vec2' }
  13109. ]
  13110. } );
  13111. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13112. const p = vec3( p_immutable ).toVar();
  13113. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13114. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13115. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13116. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  13117. const u = float( mx_fade( fx ) ).toVar();
  13118. const v = float( mx_fade( fy ) ).toVar();
  13119. const w = float( mx_fade( fz ) ).toVar();
  13120. 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();
  13121. return mx_gradient_scale3d( result );
  13122. } ).setLayout( {
  13123. name: 'mx_perlin_noise_vec3_1',
  13124. type: 'vec3',
  13125. inputs: [
  13126. { name: 'p', type: 'vec3' }
  13127. ]
  13128. } );
  13129. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  13130. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13131. const p = float( p_immutable ).toVar();
  13132. const ix = int( mx_floor( p ) ).toVar();
  13133. return mx_bits_to_01( mx_hash_int( ix ) );
  13134. } ).setLayout( {
  13135. name: 'mx_cell_noise_float_0',
  13136. type: 'float',
  13137. inputs: [
  13138. { name: 'p', type: 'float' }
  13139. ]
  13140. } );
  13141. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13142. const p = vec2( p_immutable ).toVar();
  13143. const ix = int( mx_floor( p.x ) ).toVar();
  13144. const iy = int( mx_floor( p.y ) ).toVar();
  13145. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  13146. } ).setLayout( {
  13147. name: 'mx_cell_noise_float_1',
  13148. type: 'float',
  13149. inputs: [
  13150. { name: 'p', type: 'vec2' }
  13151. ]
  13152. } );
  13153. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13154. const p = vec3( p_immutable ).toVar();
  13155. const ix = int( mx_floor( p.x ) ).toVar();
  13156. const iy = int( mx_floor( p.y ) ).toVar();
  13157. const iz = int( mx_floor( p.z ) ).toVar();
  13158. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  13159. } ).setLayout( {
  13160. name: 'mx_cell_noise_float_2',
  13161. type: 'float',
  13162. inputs: [
  13163. { name: 'p', type: 'vec3' }
  13164. ]
  13165. } );
  13166. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13167. const p = vec4( p_immutable ).toVar();
  13168. const ix = int( mx_floor( p.x ) ).toVar();
  13169. const iy = int( mx_floor( p.y ) ).toVar();
  13170. const iz = int( mx_floor( p.z ) ).toVar();
  13171. const iw = int( mx_floor( p.w ) ).toVar();
  13172. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  13173. } ).setLayout( {
  13174. name: 'mx_cell_noise_float_3',
  13175. type: 'float',
  13176. inputs: [
  13177. { name: 'p', type: 'vec4' }
  13178. ]
  13179. } );
  13180. 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 ] );
  13181. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13182. const p = float( p_immutable ).toVar();
  13183. const ix = int( mx_floor( p ) ).toVar();
  13184. 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 ) ) ) );
  13185. } ).setLayout( {
  13186. name: 'mx_cell_noise_vec3_0',
  13187. type: 'vec3',
  13188. inputs: [
  13189. { name: 'p', type: 'float' }
  13190. ]
  13191. } );
  13192. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13193. const p = vec2( p_immutable ).toVar();
  13194. const ix = int( mx_floor( p.x ) ).toVar();
  13195. const iy = int( mx_floor( p.y ) ).toVar();
  13196. 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 ) ) ) );
  13197. } ).setLayout( {
  13198. name: 'mx_cell_noise_vec3_1',
  13199. type: 'vec3',
  13200. inputs: [
  13201. { name: 'p', type: 'vec2' }
  13202. ]
  13203. } );
  13204. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13205. const p = vec3( p_immutable ).toVar();
  13206. const ix = int( mx_floor( p.x ) ).toVar();
  13207. const iy = int( mx_floor( p.y ) ).toVar();
  13208. const iz = int( mx_floor( p.z ) ).toVar();
  13209. 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 ) ) ) );
  13210. } ).setLayout( {
  13211. name: 'mx_cell_noise_vec3_2',
  13212. type: 'vec3',
  13213. inputs: [
  13214. { name: 'p', type: 'vec3' }
  13215. ]
  13216. } );
  13217. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13218. const p = vec4( p_immutable ).toVar();
  13219. const ix = int( mx_floor( p.x ) ).toVar();
  13220. const iy = int( mx_floor( p.y ) ).toVar();
  13221. const iz = int( mx_floor( p.z ) ).toVar();
  13222. const iw = int( mx_floor( p.w ) ).toVar();
  13223. 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 ) ) ) );
  13224. } ).setLayout( {
  13225. name: 'mx_cell_noise_vec3_3',
  13226. type: 'vec3',
  13227. inputs: [
  13228. { name: 'p', type: 'vec4' }
  13229. ]
  13230. } );
  13231. 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 ] );
  13232. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13233. const diminish = float( diminish_immutable ).toVar();
  13234. const lacunarity = float( lacunarity_immutable ).toVar();
  13235. const octaves = int( octaves_immutable ).toVar();
  13236. const p = vec3( p_immutable ).toVar();
  13237. const result = float( 0.0 ).toVar();
  13238. const amplitude = float( 1.0 ).toVar();
  13239. Loop( octaves, () => {
  13240. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13241. amplitude.mulAssign( diminish );
  13242. p.mulAssign( lacunarity );
  13243. } );
  13244. return result;
  13245. } ).setLayout( {
  13246. name: 'mx_fractal_noise_float',
  13247. type: 'float',
  13248. inputs: [
  13249. { name: 'p', type: 'vec3' },
  13250. { name: 'octaves', type: 'int' },
  13251. { name: 'lacunarity', type: 'float' },
  13252. { name: 'diminish', type: 'float' }
  13253. ]
  13254. } );
  13255. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13256. const diminish = float( diminish_immutable ).toVar();
  13257. const lacunarity = float( lacunarity_immutable ).toVar();
  13258. const octaves = int( octaves_immutable ).toVar();
  13259. const p = vec3( p_immutable ).toVar();
  13260. const result = vec3( 0.0 ).toVar();
  13261. const amplitude = float( 1.0 ).toVar();
  13262. Loop( octaves, () => {
  13263. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13264. amplitude.mulAssign( diminish );
  13265. p.mulAssign( lacunarity );
  13266. } );
  13267. return result;
  13268. } ).setLayout( {
  13269. name: 'mx_fractal_noise_vec3',
  13270. type: 'vec3',
  13271. inputs: [
  13272. { name: 'p', type: 'vec3' },
  13273. { name: 'octaves', type: 'int' },
  13274. { name: 'lacunarity', type: 'float' },
  13275. { name: 'diminish', type: 'float' }
  13276. ]
  13277. } );
  13278. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13279. const diminish = float( diminish_immutable ).toVar();
  13280. const lacunarity = float( lacunarity_immutable ).toVar();
  13281. const octaves = int( octaves_immutable ).toVar();
  13282. const p = vec3( p_immutable ).toVar();
  13283. 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 ) );
  13284. } ).setLayout( {
  13285. name: 'mx_fractal_noise_vec2',
  13286. type: 'vec2',
  13287. inputs: [
  13288. { name: 'p', type: 'vec3' },
  13289. { name: 'octaves', type: 'int' },
  13290. { name: 'lacunarity', type: 'float' },
  13291. { name: 'diminish', type: 'float' }
  13292. ]
  13293. } );
  13294. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13295. const diminish = float( diminish_immutable ).toVar();
  13296. const lacunarity = float( lacunarity_immutable ).toVar();
  13297. const octaves = int( octaves_immutable ).toVar();
  13298. const p = vec3( p_immutable ).toVar();
  13299. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13300. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13301. return vec4( c, f );
  13302. } ).setLayout( {
  13303. name: 'mx_fractal_noise_vec4',
  13304. type: 'vec4',
  13305. inputs: [
  13306. { name: 'p', type: 'vec3' },
  13307. { name: 'octaves', type: 'int' },
  13308. { name: 'lacunarity', type: 'float' },
  13309. { name: 'diminish', type: 'float' }
  13310. ]
  13311. } );
  13312. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13313. const metric = int( metric_immutable ).toVar();
  13314. const jitter = float( jitter_immutable ).toVar();
  13315. const yoff = int( yoff_immutable ).toVar();
  13316. const xoff = int( xoff_immutable ).toVar();
  13317. const y = int( y_immutable ).toVar();
  13318. const x = int( x_immutable ).toVar();
  13319. const p = vec2( p_immutable ).toVar();
  13320. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13321. const off = vec2( tmp.x, tmp.y ).toVar();
  13322. off.subAssign( 0.5 );
  13323. off.mulAssign( jitter );
  13324. off.addAssign( 0.5 );
  13325. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13326. const diff = vec2( cellpos.sub( p ) ).toVar();
  13327. If( metric.equal( int( 2 ) ), () => {
  13328. return abs( diff.x ).add( abs( diff.y ) );
  13329. } );
  13330. If( metric.equal( int( 3 ) ), () => {
  13331. return max$1( abs( diff.x ), abs( diff.y ) );
  13332. } );
  13333. return dot( diff, diff );
  13334. } ).setLayout( {
  13335. name: 'mx_worley_distance_0',
  13336. type: 'float',
  13337. inputs: [
  13338. { name: 'p', type: 'vec2' },
  13339. { name: 'x', type: 'int' },
  13340. { name: 'y', type: 'int' },
  13341. { name: 'xoff', type: 'int' },
  13342. { name: 'yoff', type: 'int' },
  13343. { name: 'jitter', type: 'float' },
  13344. { name: 'metric', type: 'int' }
  13345. ]
  13346. } );
  13347. 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 ] ) => {
  13348. const metric = int( metric_immutable ).toVar();
  13349. const jitter = float( jitter_immutable ).toVar();
  13350. const zoff = int( zoff_immutable ).toVar();
  13351. const yoff = int( yoff_immutable ).toVar();
  13352. const xoff = int( xoff_immutable ).toVar();
  13353. const z = int( z_immutable ).toVar();
  13354. const y = int( y_immutable ).toVar();
  13355. const x = int( x_immutable ).toVar();
  13356. const p = vec3( p_immutable ).toVar();
  13357. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13358. off.subAssign( 0.5 );
  13359. off.mulAssign( jitter );
  13360. off.addAssign( 0.5 );
  13361. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13362. const diff = vec3( cellpos.sub( p ) ).toVar();
  13363. If( metric.equal( int( 2 ) ), () => {
  13364. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13365. } );
  13366. If( metric.equal( int( 3 ) ), () => {
  13367. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13368. } );
  13369. return dot( diff, diff );
  13370. } ).setLayout( {
  13371. name: 'mx_worley_distance_1',
  13372. type: 'float',
  13373. inputs: [
  13374. { name: 'p', type: 'vec3' },
  13375. { name: 'x', type: 'int' },
  13376. { name: 'y', type: 'int' },
  13377. { name: 'z', type: 'int' },
  13378. { name: 'xoff', type: 'int' },
  13379. { name: 'yoff', type: 'int' },
  13380. { name: 'zoff', type: 'int' },
  13381. { name: 'jitter', type: 'float' },
  13382. { name: 'metric', type: 'int' }
  13383. ]
  13384. } );
  13385. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13386. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13387. const metric = int( metric_immutable ).toVar();
  13388. const jitter = float( jitter_immutable ).toVar();
  13389. const p = vec2( p_immutable ).toVar();
  13390. const X = int().toVar(), Y = int().toVar();
  13391. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13392. const sqdist = float( 1e6 ).toVar();
  13393. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13394. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13395. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13396. sqdist.assign( min$1( sqdist, dist ) );
  13397. } );
  13398. } );
  13399. If( metric.equal( int( 0 ) ), () => {
  13400. sqdist.assign( sqrt( sqdist ) );
  13401. } );
  13402. return sqdist;
  13403. } ).setLayout( {
  13404. name: 'mx_worley_noise_float_0',
  13405. type: 'float',
  13406. inputs: [
  13407. { name: 'p', type: 'vec2' },
  13408. { name: 'jitter', type: 'float' },
  13409. { name: 'metric', type: 'int' }
  13410. ]
  13411. } );
  13412. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13413. const metric = int( metric_immutable ).toVar();
  13414. const jitter = float( jitter_immutable ).toVar();
  13415. const p = vec2( p_immutable ).toVar();
  13416. const X = int().toVar(), Y = int().toVar();
  13417. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13418. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13419. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13420. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13421. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13422. If( dist.lessThan( sqdist.x ), () => {
  13423. sqdist.y.assign( sqdist.x );
  13424. sqdist.x.assign( dist );
  13425. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13426. sqdist.y.assign( dist );
  13427. } );
  13428. } );
  13429. } );
  13430. If( metric.equal( int( 0 ) ), () => {
  13431. sqdist.assign( sqrt( sqdist ) );
  13432. } );
  13433. return sqdist;
  13434. } ).setLayout( {
  13435. name: 'mx_worley_noise_vec2_0',
  13436. type: 'vec2',
  13437. inputs: [
  13438. { name: 'p', type: 'vec2' },
  13439. { name: 'jitter', type: 'float' },
  13440. { name: 'metric', type: 'int' }
  13441. ]
  13442. } );
  13443. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13444. const metric = int( metric_immutable ).toVar();
  13445. const jitter = float( jitter_immutable ).toVar();
  13446. const p = vec2( p_immutable ).toVar();
  13447. const X = int().toVar(), Y = int().toVar();
  13448. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13449. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13450. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13451. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13452. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13453. If( dist.lessThan( sqdist.x ), () => {
  13454. sqdist.z.assign( sqdist.y );
  13455. sqdist.y.assign( sqdist.x );
  13456. sqdist.x.assign( dist );
  13457. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13458. sqdist.z.assign( sqdist.y );
  13459. sqdist.y.assign( dist );
  13460. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13461. sqdist.z.assign( dist );
  13462. } );
  13463. } );
  13464. } );
  13465. If( metric.equal( int( 0 ) ), () => {
  13466. sqdist.assign( sqrt( sqdist ) );
  13467. } );
  13468. return sqdist;
  13469. } ).setLayout( {
  13470. name: 'mx_worley_noise_vec3_0',
  13471. type: 'vec3',
  13472. inputs: [
  13473. { name: 'p', type: 'vec2' },
  13474. { name: 'jitter', type: 'float' },
  13475. { name: 'metric', type: 'int' }
  13476. ]
  13477. } );
  13478. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13479. const metric = int( metric_immutable ).toVar();
  13480. const jitter = float( jitter_immutable ).toVar();
  13481. const p = vec3( p_immutable ).toVar();
  13482. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13483. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13484. const sqdist = float( 1e6 ).toVar();
  13485. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13486. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13487. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13488. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13489. sqdist.assign( min$1( sqdist, dist ) );
  13490. } );
  13491. } );
  13492. } );
  13493. If( metric.equal( int( 0 ) ), () => {
  13494. sqdist.assign( sqrt( sqdist ) );
  13495. } );
  13496. return sqdist;
  13497. } ).setLayout( {
  13498. name: 'mx_worley_noise_float_1',
  13499. type: 'float',
  13500. inputs: [
  13501. { name: 'p', type: 'vec3' },
  13502. { name: 'jitter', type: 'float' },
  13503. { name: 'metric', type: 'int' }
  13504. ]
  13505. } );
  13506. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13507. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13508. const metric = int( metric_immutable ).toVar();
  13509. const jitter = float( jitter_immutable ).toVar();
  13510. const p = vec3( p_immutable ).toVar();
  13511. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13512. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13513. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13514. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13515. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13516. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13517. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13518. If( dist.lessThan( sqdist.x ), () => {
  13519. sqdist.y.assign( sqdist.x );
  13520. sqdist.x.assign( dist );
  13521. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13522. sqdist.y.assign( dist );
  13523. } );
  13524. } );
  13525. } );
  13526. } );
  13527. If( metric.equal( int( 0 ) ), () => {
  13528. sqdist.assign( sqrt( sqdist ) );
  13529. } );
  13530. return sqdist;
  13531. } ).setLayout( {
  13532. name: 'mx_worley_noise_vec2_1',
  13533. type: 'vec2',
  13534. inputs: [
  13535. { name: 'p', type: 'vec3' },
  13536. { name: 'jitter', type: 'float' },
  13537. { name: 'metric', type: 'int' }
  13538. ]
  13539. } );
  13540. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13541. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13542. const metric = int( metric_immutable ).toVar();
  13543. const jitter = float( jitter_immutable ).toVar();
  13544. const p = vec3( p_immutable ).toVar();
  13545. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13546. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13547. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13548. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13549. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13550. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13551. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13552. If( dist.lessThan( sqdist.x ), () => {
  13553. sqdist.z.assign( sqdist.y );
  13554. sqdist.y.assign( sqdist.x );
  13555. sqdist.x.assign( dist );
  13556. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13557. sqdist.z.assign( sqdist.y );
  13558. sqdist.y.assign( dist );
  13559. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13560. sqdist.z.assign( dist );
  13561. } );
  13562. } );
  13563. } );
  13564. } );
  13565. If( metric.equal( int( 0 ) ), () => {
  13566. sqdist.assign( sqrt( sqdist ) );
  13567. } );
  13568. return sqdist;
  13569. } ).setLayout( {
  13570. name: 'mx_worley_noise_vec3_1',
  13571. type: 'vec3',
  13572. inputs: [
  13573. { name: 'p', type: 'vec3' },
  13574. { name: 'jitter', type: 'float' },
  13575. { name: 'metric', type: 'int' }
  13576. ]
  13577. } );
  13578. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13579. // Three.js Transpiler
  13580. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13581. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13582. const s = hsv.y;
  13583. const v = hsv.z;
  13584. const result = vec3().toVar();
  13585. If( s.lessThan( 0.0001 ), () => {
  13586. result.assign( vec3( v, v, v ) );
  13587. } ).Else( () => {
  13588. let h = hsv.x;
  13589. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13590. const hi = int( trunc( h ) );
  13591. const f = h.sub( float( hi ) );
  13592. const p = v.mul( s.oneMinus() );
  13593. const q = v.mul( s.mul( f ).oneMinus() );
  13594. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13595. If( hi.equal( int( 0 ) ), () => {
  13596. result.assign( vec3( v, t, p ) );
  13597. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13598. result.assign( vec3( q, v, p ) );
  13599. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13600. result.assign( vec3( p, v, t ) );
  13601. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13602. result.assign( vec3( p, q, v ) );
  13603. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13604. result.assign( vec3( t, p, v ) );
  13605. } ).Else( () => {
  13606. result.assign( vec3( v, p, q ) );
  13607. } );
  13608. } );
  13609. return result;
  13610. } ).setLayout( {
  13611. name: 'mx_hsvtorgb',
  13612. type: 'vec3',
  13613. inputs: [
  13614. { name: 'hsv', type: 'vec3' }
  13615. ]
  13616. } );
  13617. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13618. const c = vec3( c_immutable ).toVar();
  13619. const r = float( c.x ).toVar();
  13620. const g = float( c.y ).toVar();
  13621. const b = float( c.z ).toVar();
  13622. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13623. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13624. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13625. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13626. v.assign( maxcomp );
  13627. If( maxcomp.greaterThan( 0.0 ), () => {
  13628. s.assign( delta.div( maxcomp ) );
  13629. } ).Else( () => {
  13630. s.assign( 0.0 );
  13631. } );
  13632. If( s.lessThanEqual( 0.0 ), () => {
  13633. h.assign( 0.0 );
  13634. } ).Else( () => {
  13635. If( r.greaterThanEqual( maxcomp ), () => {
  13636. h.assign( g.sub( b ).div( delta ) );
  13637. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13638. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13639. } ).Else( () => {
  13640. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13641. } );
  13642. h.mulAssign( 1.0 / 6.0 );
  13643. If( h.lessThan( 0.0 ), () => {
  13644. h.addAssign( 1.0 );
  13645. } );
  13646. } );
  13647. return vec3( h, s, v );
  13648. } ).setLayout( {
  13649. name: 'mx_rgbtohsv',
  13650. type: 'vec3',
  13651. inputs: [
  13652. { name: 'c', type: 'vec3' }
  13653. ]
  13654. } );
  13655. // Three.js Transpiler
  13656. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13657. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13658. const color = vec3( color_immutable ).toVar();
  13659. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13660. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13661. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13662. return mix( linSeg, powSeg, isAbove );
  13663. } ).setLayout( {
  13664. name: 'mx_srgb_texture_to_lin_rec709',
  13665. type: 'vec3',
  13666. inputs: [
  13667. { name: 'color', type: 'vec3' }
  13668. ]
  13669. } );
  13670. const mx_aastep = ( threshold, value ) => {
  13671. threshold = float( threshold );
  13672. value = float( value );
  13673. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13674. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13675. };
  13676. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13677. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13678. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13679. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13680. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13681. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13682. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13683. const mx_safepower = ( in1, in2 = 1 ) => {
  13684. in1 = float( in1 );
  13685. return in1.abs().pow( in2 ).mul( in1.sign() );
  13686. };
  13687. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13688. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13689. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13690. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13691. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13692. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13693. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13694. return noise_vec4.mul( amplitude ).add( pivot );
  13695. };
  13696. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13697. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13698. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13699. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13700. 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 );
  13701. 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 );
  13702. 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 );
  13703. 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 );
  13704. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13705. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13706. const nDir = normalize( normal ).toVar( 'nDir' );
  13707. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13708. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13709. const rbminmax = vec3().toVar( 'rbminmax' );
  13710. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13711. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13712. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13713. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13714. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13715. return boxIntersection.sub( cubePos );
  13716. } );
  13717. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13718. // normal is assumed to have unit length
  13719. const x = normal.x, y = normal.y, z = normal.z;
  13720. // band 0
  13721. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13722. // band 1
  13723. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13724. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13725. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13726. // band 2
  13727. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13728. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13729. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13730. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13731. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13732. return result;
  13733. } );
  13734. const _clearColor$1 = /*@__PURE__*/ new Color4();
  13735. class Background extends DataMap {
  13736. constructor( renderer, nodes ) {
  13737. super();
  13738. this.renderer = renderer;
  13739. this.nodes = nodes;
  13740. }
  13741. update( scene, renderList, renderContext ) {
  13742. const renderer = this.renderer;
  13743. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  13744. let forceClear = false;
  13745. if ( background === null ) {
  13746. // no background settings, use clear color configuration from the renderer
  13747. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13748. _clearColor$1.a = renderer._clearColor.a;
  13749. } else if ( background.isColor === true ) {
  13750. // background is an opaque color
  13751. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13752. _clearColor$1.a = 1;
  13753. forceClear = true;
  13754. } else if ( background.isNode === true ) {
  13755. const sceneData = this.get( scene );
  13756. const backgroundNode = background;
  13757. _clearColor$1.copy( renderer._clearColor );
  13758. let backgroundMesh = sceneData.backgroundMesh;
  13759. if ( backgroundMesh === undefined ) {
  13760. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  13761. // @TODO: Add Texture2D support using node context
  13762. getUV: () => backgroundRotation.mul( normalWorld ),
  13763. getTextureLevel: () => backgroundBlurriness
  13764. } );
  13765. let viewProj = modelViewProjection();
  13766. viewProj = viewProj.setZ( viewProj.w );
  13767. const nodeMaterial = new NodeMaterial();
  13768. nodeMaterial.name = 'Background.material';
  13769. nodeMaterial.side = BackSide;
  13770. nodeMaterial.depthTest = false;
  13771. nodeMaterial.depthWrite = false;
  13772. nodeMaterial.fog = false;
  13773. nodeMaterial.lights = false;
  13774. nodeMaterial.vertexNode = viewProj;
  13775. nodeMaterial.colorNode = backgroundMeshNode;
  13776. sceneData.backgroundMeshNode = backgroundMeshNode;
  13777. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  13778. backgroundMesh.frustumCulled = false;
  13779. backgroundMesh.name = 'Background.mesh';
  13780. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13781. this.matrixWorld.copyPosition( camera.matrixWorld );
  13782. };
  13783. }
  13784. const backgroundCacheKey = backgroundNode.getCacheKey();
  13785. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  13786. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  13787. sceneData.backgroundMeshNode.needsUpdate = true;
  13788. backgroundMesh.material.needsUpdate = true;
  13789. sceneData.backgroundCacheKey = backgroundCacheKey;
  13790. }
  13791. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  13792. } else {
  13793. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  13794. }
  13795. //
  13796. if ( renderer.autoClear === true || forceClear === true ) {
  13797. const clearColorValue = renderContext.clearColorValue;
  13798. clearColorValue.r = _clearColor$1.r;
  13799. clearColorValue.g = _clearColor$1.g;
  13800. clearColorValue.b = _clearColor$1.b;
  13801. clearColorValue.a = _clearColor$1.a;
  13802. // premultiply alpha
  13803. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  13804. clearColorValue.r *= clearColorValue.a;
  13805. clearColorValue.g *= clearColorValue.a;
  13806. clearColorValue.b *= clearColorValue.a;
  13807. }
  13808. //
  13809. renderContext.depthClearValue = renderer._clearDepth;
  13810. renderContext.stencilClearValue = renderer._clearStencil;
  13811. renderContext.clearColor = renderer.autoClearColor === true;
  13812. renderContext.clearDepth = renderer.autoClearDepth === true;
  13813. renderContext.clearStencil = renderer.autoClearStencil === true;
  13814. } else {
  13815. renderContext.clearColor = false;
  13816. renderContext.clearDepth = false;
  13817. renderContext.clearStencil = false;
  13818. }
  13819. }
  13820. }
  13821. let _id$5 = 0;
  13822. class BindGroup {
  13823. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  13824. this.name = name;
  13825. this.bindings = bindings;
  13826. this.index = index;
  13827. this.bindingsReference = bindingsReference;
  13828. this.id = _id$5 ++;
  13829. }
  13830. }
  13831. class NodeBuilderState {
  13832. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  13833. this.vertexShader = vertexShader;
  13834. this.fragmentShader = fragmentShader;
  13835. this.computeShader = computeShader;
  13836. this.transforms = transforms;
  13837. this.nodeAttributes = nodeAttributes;
  13838. this.bindings = bindings;
  13839. this.updateNodes = updateNodes;
  13840. this.updateBeforeNodes = updateBeforeNodes;
  13841. this.updateAfterNodes = updateAfterNodes;
  13842. this.monitor = monitor;
  13843. this.usedTimes = 0;
  13844. }
  13845. createBindings() {
  13846. const bindings = [];
  13847. for ( const instanceGroup of this.bindings ) {
  13848. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  13849. if ( shared !== true ) {
  13850. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  13851. bindings.push( bindingsGroup );
  13852. for ( const instanceBinding of instanceGroup.bindings ) {
  13853. bindingsGroup.bindings.push( instanceBinding.clone() );
  13854. }
  13855. } else {
  13856. bindings.push( instanceGroup );
  13857. }
  13858. }
  13859. return bindings;
  13860. }
  13861. }
  13862. class NodeAttribute {
  13863. constructor( name, type, node = null ) {
  13864. this.isNodeAttribute = true;
  13865. this.name = name;
  13866. this.type = type;
  13867. this.node = node;
  13868. }
  13869. }
  13870. class NodeUniform {
  13871. constructor( name, type, node ) {
  13872. this.isNodeUniform = true;
  13873. this.name = name;
  13874. this.type = type;
  13875. this.node = node.getSelf();
  13876. }
  13877. get value() {
  13878. return this.node.value;
  13879. }
  13880. set value( val ) {
  13881. this.node.value = val;
  13882. }
  13883. get id() {
  13884. return this.node.id;
  13885. }
  13886. get groupNode() {
  13887. return this.node.groupNode;
  13888. }
  13889. }
  13890. class NodeVar {
  13891. constructor( name, type ) {
  13892. this.isNodeVar = true;
  13893. this.name = name;
  13894. this.type = type;
  13895. }
  13896. }
  13897. class NodeVarying extends NodeVar {
  13898. constructor( name, type ) {
  13899. super( name, type );
  13900. this.needsInterpolation = false;
  13901. this.isNodeVarying = true;
  13902. }
  13903. }
  13904. class NodeCode {
  13905. constructor( name, type, code = '' ) {
  13906. this.name = name;
  13907. this.type = type;
  13908. this.code = code;
  13909. Object.defineProperty( this, 'isNodeCode', { value: true } );
  13910. }
  13911. }
  13912. let id = 0;
  13913. class NodeCache {
  13914. constructor( parent = null ) {
  13915. this.id = id ++;
  13916. this.nodesData = new WeakMap();
  13917. this.parent = parent;
  13918. }
  13919. getData( node ) {
  13920. let data = this.nodesData.get( node );
  13921. if ( data === undefined && this.parent !== null ) {
  13922. data = this.parent.getData( node );
  13923. }
  13924. return data;
  13925. }
  13926. setData( node, data ) {
  13927. this.nodesData.set( node, data );
  13928. }
  13929. }
  13930. class Uniform {
  13931. constructor( name, value ) {
  13932. this.name = name;
  13933. this.value = value;
  13934. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  13935. this.itemSize = 0;
  13936. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  13937. }
  13938. setValue( value ) {
  13939. this.value = value;
  13940. }
  13941. getValue() {
  13942. return this.value;
  13943. }
  13944. }
  13945. class NumberUniform extends Uniform {
  13946. constructor( name, value = 0 ) {
  13947. super( name, value );
  13948. this.isNumberUniform = true;
  13949. this.boundary = 4;
  13950. this.itemSize = 1;
  13951. }
  13952. }
  13953. class Vector2Uniform extends Uniform {
  13954. constructor( name, value = new Vector2() ) {
  13955. super( name, value );
  13956. this.isVector2Uniform = true;
  13957. this.boundary = 8;
  13958. this.itemSize = 2;
  13959. }
  13960. }
  13961. class Vector3Uniform extends Uniform {
  13962. constructor( name, value = new Vector3() ) {
  13963. super( name, value );
  13964. this.isVector3Uniform = true;
  13965. this.boundary = 16;
  13966. this.itemSize = 3;
  13967. }
  13968. }
  13969. class Vector4Uniform extends Uniform {
  13970. constructor( name, value = new Vector4() ) {
  13971. super( name, value );
  13972. this.isVector4Uniform = true;
  13973. this.boundary = 16;
  13974. this.itemSize = 4;
  13975. }
  13976. }
  13977. class ColorUniform extends Uniform {
  13978. constructor( name, value = new Color() ) {
  13979. super( name, value );
  13980. this.isColorUniform = true;
  13981. this.boundary = 16;
  13982. this.itemSize = 3;
  13983. }
  13984. }
  13985. class Matrix3Uniform extends Uniform {
  13986. constructor( name, value = new Matrix3() ) {
  13987. super( name, value );
  13988. this.isMatrix3Uniform = true;
  13989. this.boundary = 48;
  13990. this.itemSize = 12;
  13991. }
  13992. }
  13993. class Matrix4Uniform extends Uniform {
  13994. constructor( name, value = new Matrix4() ) {
  13995. super( name, value );
  13996. this.isMatrix4Uniform = true;
  13997. this.boundary = 64;
  13998. this.itemSize = 16;
  13999. }
  14000. }
  14001. class NumberNodeUniform extends NumberUniform {
  14002. constructor( nodeUniform ) {
  14003. super( nodeUniform.name, nodeUniform.value );
  14004. this.nodeUniform = nodeUniform;
  14005. }
  14006. getValue() {
  14007. return this.nodeUniform.value;
  14008. }
  14009. }
  14010. class Vector2NodeUniform extends Vector2Uniform {
  14011. constructor( nodeUniform ) {
  14012. super( nodeUniform.name, nodeUniform.value );
  14013. this.nodeUniform = nodeUniform;
  14014. }
  14015. getValue() {
  14016. return this.nodeUniform.value;
  14017. }
  14018. }
  14019. class Vector3NodeUniform extends Vector3Uniform {
  14020. constructor( nodeUniform ) {
  14021. super( nodeUniform.name, nodeUniform.value );
  14022. this.nodeUniform = nodeUniform;
  14023. }
  14024. getValue() {
  14025. return this.nodeUniform.value;
  14026. }
  14027. }
  14028. class Vector4NodeUniform extends Vector4Uniform {
  14029. constructor( nodeUniform ) {
  14030. super( nodeUniform.name, nodeUniform.value );
  14031. this.nodeUniform = nodeUniform;
  14032. }
  14033. getValue() {
  14034. return this.nodeUniform.value;
  14035. }
  14036. }
  14037. class ColorNodeUniform extends ColorUniform {
  14038. constructor( nodeUniform ) {
  14039. super( nodeUniform.name, nodeUniform.value );
  14040. this.nodeUniform = nodeUniform;
  14041. }
  14042. getValue() {
  14043. return this.nodeUniform.value;
  14044. }
  14045. }
  14046. class Matrix3NodeUniform extends Matrix3Uniform {
  14047. constructor( nodeUniform ) {
  14048. super( nodeUniform.name, nodeUniform.value );
  14049. this.nodeUniform = nodeUniform;
  14050. }
  14051. getValue() {
  14052. return this.nodeUniform.value;
  14053. }
  14054. }
  14055. class Matrix4NodeUniform extends Matrix4Uniform {
  14056. constructor( nodeUniform ) {
  14057. super( nodeUniform.name, nodeUniform.value );
  14058. this.nodeUniform = nodeUniform;
  14059. }
  14060. getValue() {
  14061. return this.nodeUniform.value;
  14062. }
  14063. }
  14064. const LOD_MIN = 4;
  14065. // The standard deviations (radians) associated with the extra mips. These are
  14066. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14067. // geometric shadowing function. These sigma values squared must match the
  14068. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14069. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14070. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14071. // samples and exit early, but not recompile the shader.
  14072. const MAX_SAMPLES = 20;
  14073. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14074. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14075. const _clearColor = /*@__PURE__*/ new Color();
  14076. let _oldTarget = null;
  14077. let _oldActiveCubeFace = 0;
  14078. let _oldActiveMipmapLevel = 0;
  14079. // Golden Ratio
  14080. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14081. const INV_PHI = 1 / PHI;
  14082. // Vertices of a dodecahedron (except the opposites, which represent the
  14083. // same axis), used as axis directions evenly spread on a sphere.
  14084. const _axisDirections = [
  14085. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14086. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14087. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14088. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14089. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14090. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14091. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14092. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14093. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14094. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14095. ];
  14096. //
  14097. // WebGPU Face indices
  14098. const _faceLib = [
  14099. 3, 1, 5,
  14100. 0, 4, 2
  14101. ];
  14102. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14103. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  14104. /**
  14105. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14106. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14107. * blur to be quickly accessed based on material roughness. It is packed into a
  14108. * special CubeUV format that allows us to perform custom interpolation so that
  14109. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14110. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14111. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14112. * higher roughness levels. In this way we maintain resolution to smoothly
  14113. * interpolate diffuse lighting while limiting sampling computation.
  14114. *
  14115. * Paper: Fast, Accurate Image-Based Lighting
  14116. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  14117. */
  14118. class PMREMGenerator {
  14119. constructor( renderer ) {
  14120. this._renderer = renderer;
  14121. this._pingPongRenderTarget = null;
  14122. this._lodMax = 0;
  14123. this._cubeSize = 0;
  14124. this._lodPlanes = [];
  14125. this._sizeLods = [];
  14126. this._sigmas = [];
  14127. this._lodMeshes = [];
  14128. this._blurMaterial = null;
  14129. this._cubemapMaterial = null;
  14130. this._equirectMaterial = null;
  14131. this._backgroundBox = null;
  14132. }
  14133. /**
  14134. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14135. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14136. * in radians to be applied to the scene before PMREM generation. Optional near
  14137. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14138. * is placed at the origin).
  14139. */
  14140. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  14141. _oldTarget = this._renderer.getRenderTarget();
  14142. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14143. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14144. this._setSize( 256 );
  14145. const cubeUVRenderTarget = this._allocateTargets();
  14146. cubeUVRenderTarget.depthBuffer = true;
  14147. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  14148. if ( sigma > 0 ) {
  14149. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14150. }
  14151. this._applyPMREM( cubeUVRenderTarget );
  14152. this._cleanup( cubeUVRenderTarget );
  14153. return cubeUVRenderTarget;
  14154. }
  14155. /**
  14156. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14157. * or HDR. The ideal input image size is 1k (1024 x 512),
  14158. * as this matches best with the 256 x 256 cubemap output.
  14159. */
  14160. fromEquirectangular( equirectangular, renderTarget = null ) {
  14161. return this._fromTexture( equirectangular, renderTarget );
  14162. }
  14163. /**
  14164. * Generates a PMREM from an cubemap texture, which can be either LDR
  14165. * or HDR. The ideal input cube size is 256 x 256,
  14166. * as this matches best with the 256 x 256 cubemap output.
  14167. */
  14168. fromCubemap( cubemap, renderTarget = null ) {
  14169. return this._fromTexture( cubemap, renderTarget );
  14170. }
  14171. /**
  14172. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  14173. * your texture's network fetch for increased concurrency.
  14174. */
  14175. async compileCubemapShader() {
  14176. if ( this._cubemapMaterial === null ) {
  14177. this._cubemapMaterial = _getCubemapMaterial();
  14178. await this._compileMaterial( this._cubemapMaterial );
  14179. }
  14180. }
  14181. /**
  14182. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  14183. * your texture's network fetch for increased concurrency.
  14184. */
  14185. async compileEquirectangularShader() {
  14186. if ( this._equirectMaterial === null ) {
  14187. this._equirectMaterial = _getEquirectMaterial();
  14188. await this._compileMaterial( this._equirectMaterial );
  14189. }
  14190. }
  14191. /**
  14192. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  14193. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  14194. * one of them will cause any others to also become unusable.
  14195. */
  14196. dispose() {
  14197. this._dispose();
  14198. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  14199. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  14200. if ( this._backgroundBox !== null ) {
  14201. this._backgroundBox.geometry.dispose();
  14202. this._backgroundBox.material.dispose();
  14203. }
  14204. }
  14205. // private interface
  14206. _setSize( cubeSize ) {
  14207. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  14208. this._cubeSize = Math.pow( 2, this._lodMax );
  14209. }
  14210. _dispose() {
  14211. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  14212. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  14213. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  14214. this._lodPlanes[ i ].dispose();
  14215. }
  14216. }
  14217. _cleanup( outputTarget ) {
  14218. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  14219. outputTarget.scissorTest = false;
  14220. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14221. }
  14222. _fromTexture( texture, renderTarget ) {
  14223. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14224. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14225. } else { // Equirectangular
  14226. this._setSize( texture.image.width / 4 );
  14227. }
  14228. _oldTarget = this._renderer.getRenderTarget();
  14229. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14230. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14231. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14232. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14233. this._applyPMREM( cubeUVRenderTarget );
  14234. this._cleanup( cubeUVRenderTarget );
  14235. return cubeUVRenderTarget;
  14236. }
  14237. _allocateTargets() {
  14238. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14239. const height = 4 * this._cubeSize;
  14240. const params = {
  14241. magFilter: LinearFilter,
  14242. minFilter: LinearFilter,
  14243. generateMipmaps: false,
  14244. type: HalfFloatType,
  14245. format: RGBAFormat,
  14246. colorSpace: LinearSRGBColorSpace,
  14247. //depthBuffer: false
  14248. };
  14249. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14250. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14251. if ( this._pingPongRenderTarget !== null ) {
  14252. this._dispose();
  14253. }
  14254. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14255. const { _lodMax } = this;
  14256. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14257. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14258. }
  14259. return cubeUVRenderTarget;
  14260. }
  14261. async _compileMaterial( material ) {
  14262. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14263. await this._renderer.compile( tmpMesh, _flatCamera );
  14264. }
  14265. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14266. const cubeCamera = _cubeCamera;
  14267. cubeCamera.near = near;
  14268. cubeCamera.far = far;
  14269. // px, py, pz, nx, ny, nz
  14270. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14271. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14272. const renderer = this._renderer;
  14273. const originalAutoClear = renderer.autoClear;
  14274. renderer.getClearColor( _clearColor );
  14275. renderer.autoClear = false;
  14276. let backgroundBox = this._backgroundBox;
  14277. if ( backgroundBox === null ) {
  14278. const backgroundMaterial = new MeshBasicMaterial( {
  14279. name: 'PMREM.Background',
  14280. side: BackSide,
  14281. depthWrite: false,
  14282. depthTest: false
  14283. } );
  14284. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14285. }
  14286. let useSolidColor = false;
  14287. const background = scene.background;
  14288. if ( background ) {
  14289. if ( background.isColor ) {
  14290. backgroundBox.material.color.copy( background );
  14291. scene.background = null;
  14292. useSolidColor = true;
  14293. }
  14294. } else {
  14295. backgroundBox.material.color.copy( _clearColor );
  14296. useSolidColor = true;
  14297. }
  14298. renderer.setRenderTarget( cubeUVRenderTarget );
  14299. renderer.clear();
  14300. if ( useSolidColor ) {
  14301. renderer.render( backgroundBox, cubeCamera );
  14302. }
  14303. for ( let i = 0; i < 6; i ++ ) {
  14304. const col = i % 3;
  14305. if ( col === 0 ) {
  14306. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14307. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14308. } else if ( col === 1 ) {
  14309. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14310. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14311. } else {
  14312. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14313. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14314. }
  14315. const size = this._cubeSize;
  14316. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14317. renderer.render( scene, cubeCamera );
  14318. }
  14319. renderer.autoClear = originalAutoClear;
  14320. scene.background = background;
  14321. }
  14322. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14323. const renderer = this._renderer;
  14324. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14325. if ( isCubeTexture ) {
  14326. if ( this._cubemapMaterial === null ) {
  14327. this._cubemapMaterial = _getCubemapMaterial( texture );
  14328. }
  14329. } else {
  14330. if ( this._equirectMaterial === null ) {
  14331. this._equirectMaterial = _getEquirectMaterial( texture );
  14332. }
  14333. }
  14334. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14335. material.fragmentNode.value = texture;
  14336. const mesh = this._lodMeshes[ 0 ];
  14337. mesh.material = material;
  14338. const size = this._cubeSize;
  14339. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14340. renderer.setRenderTarget( cubeUVRenderTarget );
  14341. renderer.render( mesh, _flatCamera );
  14342. }
  14343. _applyPMREM( cubeUVRenderTarget ) {
  14344. const renderer = this._renderer;
  14345. const autoClear = renderer.autoClear;
  14346. renderer.autoClear = false;
  14347. const n = this._lodPlanes.length;
  14348. for ( let i = 1; i < n; i ++ ) {
  14349. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14350. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14351. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14352. }
  14353. renderer.autoClear = autoClear;
  14354. }
  14355. /**
  14356. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14357. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14358. * the blur latitudinally (around the poles), and then longitudinally (towards
  14359. * the poles) to approximate the orthogonally-separable blur. It is least
  14360. * accurate at the poles, but still does a decent job.
  14361. */
  14362. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14363. const pingPongRenderTarget = this._pingPongRenderTarget;
  14364. this._halfBlur(
  14365. cubeUVRenderTarget,
  14366. pingPongRenderTarget,
  14367. lodIn,
  14368. lodOut,
  14369. sigma,
  14370. 'latitudinal',
  14371. poleAxis );
  14372. this._halfBlur(
  14373. pingPongRenderTarget,
  14374. cubeUVRenderTarget,
  14375. lodOut,
  14376. lodOut,
  14377. sigma,
  14378. 'longitudinal',
  14379. poleAxis );
  14380. }
  14381. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14382. const renderer = this._renderer;
  14383. const blurMaterial = this._blurMaterial;
  14384. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14385. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14386. }
  14387. // Number of standard deviations at which to cut off the discrete approximation.
  14388. const STANDARD_DEVIATIONS = 3;
  14389. const blurMesh = this._lodMeshes[ lodOut ];
  14390. blurMesh.material = blurMaterial;
  14391. const blurUniforms = blurMaterial.uniforms;
  14392. const pixels = this._sizeLods[ lodIn ] - 1;
  14393. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14394. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14395. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14396. if ( samples > MAX_SAMPLES ) {
  14397. console.warn( `sigmaRadians, ${
  14398. sigmaRadians}, is too large and will clip, as it requested ${
  14399. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14400. }
  14401. const weights = [];
  14402. let sum = 0;
  14403. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14404. const x = i / sigmaPixels;
  14405. const weight = Math.exp( - x * x / 2 );
  14406. weights.push( weight );
  14407. if ( i === 0 ) {
  14408. sum += weight;
  14409. } else if ( i < samples ) {
  14410. sum += 2 * weight;
  14411. }
  14412. }
  14413. for ( let i = 0; i < weights.length; i ++ ) {
  14414. weights[ i ] = weights[ i ] / sum;
  14415. }
  14416. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14417. blurUniforms.envMap.value = targetIn.texture;
  14418. blurUniforms.samples.value = samples;
  14419. blurUniforms.weights.array = weights;
  14420. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14421. if ( poleAxis ) {
  14422. blurUniforms.poleAxis.value = poleAxis;
  14423. }
  14424. const { _lodMax } = this;
  14425. blurUniforms.dTheta.value = radiansPerPixel;
  14426. blurUniforms.mipInt.value = _lodMax - lodIn;
  14427. const outputSize = this._sizeLods[ lodOut ];
  14428. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14429. const y = 4 * ( this._cubeSize - outputSize );
  14430. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14431. renderer.setRenderTarget( targetOut );
  14432. renderer.render( blurMesh, _flatCamera );
  14433. }
  14434. }
  14435. function _createPlanes( lodMax ) {
  14436. const lodPlanes = [];
  14437. const sizeLods = [];
  14438. const sigmas = [];
  14439. const lodMeshes = [];
  14440. let lod = lodMax;
  14441. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14442. for ( let i = 0; i < totalLods; i ++ ) {
  14443. const sizeLod = Math.pow( 2, lod );
  14444. sizeLods.push( sizeLod );
  14445. let sigma = 1.0 / sizeLod;
  14446. if ( i > lodMax - LOD_MIN ) {
  14447. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14448. } else if ( i === 0 ) {
  14449. sigma = 0;
  14450. }
  14451. sigmas.push( sigma );
  14452. const texelSize = 1.0 / ( sizeLod - 2 );
  14453. const min = - texelSize;
  14454. const max = 1 + texelSize;
  14455. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14456. const cubeFaces = 6;
  14457. const vertices = 6;
  14458. const positionSize = 3;
  14459. const uvSize = 2;
  14460. const faceIndexSize = 1;
  14461. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14462. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14463. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14464. for ( let face = 0; face < cubeFaces; face ++ ) {
  14465. const x = ( face % 3 ) * 2 / 3 - 1;
  14466. const y = face > 2 ? 0 : - 1;
  14467. const coordinates = [
  14468. x, y, 0,
  14469. x + 2 / 3, y, 0,
  14470. x + 2 / 3, y + 1, 0,
  14471. x, y, 0,
  14472. x + 2 / 3, y + 1, 0,
  14473. x, y + 1, 0
  14474. ];
  14475. const faceIdx = _faceLib[ face ];
  14476. position.set( coordinates, positionSize * vertices * faceIdx );
  14477. uv.set( uv1, uvSize * vertices * faceIdx );
  14478. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14479. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14480. }
  14481. const planes = new BufferGeometry();
  14482. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14483. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14484. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14485. lodPlanes.push( planes );
  14486. lodMeshes.push( new Mesh( planes, null ) );
  14487. if ( lod > LOD_MIN ) {
  14488. lod --;
  14489. }
  14490. }
  14491. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14492. }
  14493. function _createRenderTarget( width, height, params ) {
  14494. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14495. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14496. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14497. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14498. cubeUVRenderTarget.scissorTest = true;
  14499. return cubeUVRenderTarget;
  14500. }
  14501. function _setViewport( target, x, y, width, height ) {
  14502. target.viewport.set( x, y, width, height );
  14503. target.scissor.set( x, y, width, height );
  14504. }
  14505. function _getMaterial( type ) {
  14506. const material = new NodeMaterial();
  14507. material.depthTest = false;
  14508. material.depthWrite = false;
  14509. material.blending = NoBlending;
  14510. material.name = `PMREM_${ type }`;
  14511. return material;
  14512. }
  14513. function _getBlurShader( lodMax, width, height ) {
  14514. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14515. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14516. const dTheta = uniform( 0 );
  14517. const n = float( MAX_SAMPLES );
  14518. const latitudinal = uniform( 0 ); // false, bool
  14519. const samples = uniform( 1 ); // int
  14520. const envMap = texture( null );
  14521. const mipInt = uniform( 0 ); // int
  14522. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14523. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14524. const CUBEUV_MAX_MIP = float( lodMax );
  14525. const materialUniforms = {
  14526. n,
  14527. latitudinal,
  14528. weights,
  14529. poleAxis,
  14530. outputDirection,
  14531. dTheta,
  14532. samples,
  14533. envMap,
  14534. mipInt,
  14535. CUBEUV_TEXEL_WIDTH,
  14536. CUBEUV_TEXEL_HEIGHT,
  14537. CUBEUV_MAX_MIP
  14538. };
  14539. const material = _getMaterial( 'blur' );
  14540. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14541. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14542. return material;
  14543. }
  14544. function _getCubemapMaterial( envTexture ) {
  14545. const material = _getMaterial( 'cubemap' );
  14546. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14547. return material;
  14548. }
  14549. function _getEquirectMaterial( envTexture ) {
  14550. const material = _getMaterial( 'equirect' );
  14551. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14552. return material;
  14553. }
  14554. const rendererCache = new WeakMap();
  14555. const typeFromLength = new Map( [
  14556. [ 2, 'vec2' ],
  14557. [ 3, 'vec3' ],
  14558. [ 4, 'vec4' ],
  14559. [ 9, 'mat3' ],
  14560. [ 16, 'mat4' ]
  14561. ] );
  14562. const typeFromArray = new Map( [
  14563. [ Int8Array, 'int' ],
  14564. [ Int16Array, 'int' ],
  14565. [ Int32Array, 'int' ],
  14566. [ Uint8Array, 'uint' ],
  14567. [ Uint16Array, 'uint' ],
  14568. [ Uint32Array, 'uint' ],
  14569. [ Float32Array, 'float' ]
  14570. ] );
  14571. const toFloat = ( value ) => {
  14572. if ( /e/g.test( value ) ) {
  14573. return String( value ).replace( /\+/g, '' );
  14574. } else {
  14575. value = Number( value );
  14576. return value + ( value % 1 ? '' : '.0' );
  14577. }
  14578. };
  14579. class NodeBuilder {
  14580. constructor( object, renderer, parser ) {
  14581. this.object = object;
  14582. this.material = ( object && object.material ) || null;
  14583. this.geometry = ( object && object.geometry ) || null;
  14584. this.renderer = renderer;
  14585. this.parser = parser;
  14586. this.scene = null;
  14587. this.camera = null;
  14588. this.nodes = [];
  14589. this.sequentialNodes = [];
  14590. this.updateNodes = [];
  14591. this.updateBeforeNodes = [];
  14592. this.updateAfterNodes = [];
  14593. this.hashNodes = {};
  14594. this.monitor = null;
  14595. this.lightsNode = null;
  14596. this.environmentNode = null;
  14597. this.fogNode = null;
  14598. this.clippingContext = null;
  14599. this.vertexShader = null;
  14600. this.fragmentShader = null;
  14601. this.computeShader = null;
  14602. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  14603. this.flowCode = { vertex: '', fragment: '', compute: '' };
  14604. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  14605. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  14606. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  14607. this.bindingsIndexes = {};
  14608. this.bindGroups = null;
  14609. this.attributes = [];
  14610. this.bufferAttributes = [];
  14611. this.varyings = [];
  14612. this.codes = {};
  14613. this.vars = {};
  14614. this.flow = { code: '' };
  14615. this.chaining = [];
  14616. this.stack = stack();
  14617. this.stacks = [];
  14618. this.tab = '\t';
  14619. this.currentFunctionNode = null;
  14620. this.context = {
  14621. material: this.material
  14622. };
  14623. this.cache = new NodeCache();
  14624. this.globalCache = this.cache;
  14625. this.flowsData = new WeakMap();
  14626. this.shaderStage = null;
  14627. this.buildStage = null;
  14628. this.useComparisonMethod = false;
  14629. }
  14630. getBindGroupsCache() {
  14631. let bindGroupsCache = rendererCache.get( this.renderer );
  14632. if ( bindGroupsCache === undefined ) {
  14633. bindGroupsCache = new ChainMap();
  14634. rendererCache.set( this.renderer, bindGroupsCache );
  14635. }
  14636. return bindGroupsCache;
  14637. }
  14638. createRenderTarget( width, height, options ) {
  14639. return new RenderTarget( width, height, options );
  14640. }
  14641. createCubeRenderTarget( size, options ) {
  14642. return new CubeRenderTarget( size, options );
  14643. }
  14644. createPMREMGenerator() {
  14645. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  14646. return new PMREMGenerator( this.renderer );
  14647. }
  14648. includes( node ) {
  14649. return this.nodes.includes( node );
  14650. }
  14651. _getBindGroup( groupName, bindings ) {
  14652. const bindGroupsCache = this.getBindGroupsCache();
  14653. //
  14654. const bindingsArray = [];
  14655. let sharedGroup = true;
  14656. for ( const binding of bindings ) {
  14657. bindingsArray.push( binding );
  14658. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  14659. }
  14660. //
  14661. let bindGroup;
  14662. if ( sharedGroup ) {
  14663. bindGroup = bindGroupsCache.get( bindingsArray );
  14664. if ( bindGroup === undefined ) {
  14665. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14666. bindGroupsCache.set( bindingsArray, bindGroup );
  14667. }
  14668. } else {
  14669. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14670. }
  14671. return bindGroup;
  14672. }
  14673. getBindGroupArray( groupName, shaderStage ) {
  14674. const bindings = this.bindings[ shaderStage ];
  14675. let bindGroup = bindings[ groupName ];
  14676. if ( bindGroup === undefined ) {
  14677. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  14678. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  14679. }
  14680. bindings[ groupName ] = bindGroup = [];
  14681. }
  14682. return bindGroup;
  14683. }
  14684. getBindings() {
  14685. let bindingsGroups = this.bindGroups;
  14686. if ( bindingsGroups === null ) {
  14687. const groups = {};
  14688. const bindings = this.bindings;
  14689. for ( const shaderStage of shaderStages ) {
  14690. for ( const groupName in bindings[ shaderStage ] ) {
  14691. const uniforms = bindings[ shaderStage ][ groupName ];
  14692. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  14693. groupUniforms.push( ...uniforms );
  14694. }
  14695. }
  14696. bindingsGroups = [];
  14697. for ( const groupName in groups ) {
  14698. const group = groups[ groupName ];
  14699. const bindingsGroup = this._getBindGroup( groupName, group );
  14700. bindingsGroups.push( bindingsGroup );
  14701. }
  14702. this.bindGroups = bindingsGroups;
  14703. }
  14704. return bindingsGroups;
  14705. }
  14706. sortBindingGroups() {
  14707. const bindingsGroups = this.getBindings();
  14708. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  14709. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  14710. const bindingGroup = bindingsGroups[ i ];
  14711. this.bindingsIndexes[ bindingGroup.name ].group = i;
  14712. bindingGroup.index = i;
  14713. }
  14714. }
  14715. setHashNode( node, hash ) {
  14716. this.hashNodes[ hash ] = node;
  14717. }
  14718. addNode( node ) {
  14719. if ( this.nodes.includes( node ) === false ) {
  14720. this.nodes.push( node );
  14721. this.setHashNode( node, node.getHash( this ) );
  14722. }
  14723. }
  14724. addSequentialNode( node ) {
  14725. if ( this.sequentialNodes.includes( node ) === false ) {
  14726. this.sequentialNodes.push( node );
  14727. }
  14728. }
  14729. buildUpdateNodes() {
  14730. for ( const node of this.nodes ) {
  14731. const updateType = node.getUpdateType();
  14732. if ( updateType !== NodeUpdateType.NONE ) {
  14733. this.updateNodes.push( node.getSelf() );
  14734. }
  14735. }
  14736. for ( const node of this.sequentialNodes ) {
  14737. const updateBeforeType = node.getUpdateBeforeType();
  14738. const updateAfterType = node.getUpdateAfterType();
  14739. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  14740. this.updateBeforeNodes.push( node.getSelf() );
  14741. }
  14742. if ( updateAfterType !== NodeUpdateType.NONE ) {
  14743. this.updateAfterNodes.push( node.getSelf() );
  14744. }
  14745. }
  14746. }
  14747. get currentNode() {
  14748. return this.chaining[ this.chaining.length - 1 ];
  14749. }
  14750. isFilteredTexture( texture ) {
  14751. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14752. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  14753. }
  14754. addChain( node ) {
  14755. /*
  14756. if ( this.chaining.indexOf( node ) !== - 1 ) {
  14757. console.warn( 'Recursive node: ', node );
  14758. }
  14759. */
  14760. this.chaining.push( node );
  14761. }
  14762. removeChain( node ) {
  14763. const lastChain = this.chaining.pop();
  14764. if ( lastChain !== node ) {
  14765. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  14766. }
  14767. }
  14768. getMethod( method ) {
  14769. return method;
  14770. }
  14771. getNodeFromHash( hash ) {
  14772. return this.hashNodes[ hash ];
  14773. }
  14774. addFlow( shaderStage, node ) {
  14775. this.flowNodes[ shaderStage ].push( node );
  14776. return node;
  14777. }
  14778. setContext( context ) {
  14779. this.context = context;
  14780. }
  14781. getContext() {
  14782. return this.context;
  14783. }
  14784. getSharedContext() {
  14785. ({ ...this.context });
  14786. return this.context;
  14787. }
  14788. setCache( cache ) {
  14789. this.cache = cache;
  14790. }
  14791. getCache() {
  14792. return this.cache;
  14793. }
  14794. getCacheFromNode( node, parent = true ) {
  14795. const data = this.getDataFromNode( node );
  14796. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  14797. return data.cache;
  14798. }
  14799. isAvailable( /*name*/ ) {
  14800. return false;
  14801. }
  14802. getVertexIndex() {
  14803. console.warn( 'Abstract function.' );
  14804. }
  14805. getInstanceIndex() {
  14806. console.warn( 'Abstract function.' );
  14807. }
  14808. getDrawIndex() {
  14809. console.warn( 'Abstract function.' );
  14810. }
  14811. getFrontFacing() {
  14812. console.warn( 'Abstract function.' );
  14813. }
  14814. getFragCoord() {
  14815. console.warn( 'Abstract function.' );
  14816. }
  14817. isFlipY() {
  14818. return false;
  14819. }
  14820. increaseUsage( node ) {
  14821. const nodeData = this.getDataFromNode( node );
  14822. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  14823. return nodeData.usageCount;
  14824. }
  14825. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  14826. console.warn( 'Abstract function.' );
  14827. }
  14828. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  14829. console.warn( 'Abstract function.' );
  14830. }
  14831. generateConst( type, value = null ) {
  14832. if ( value === null ) {
  14833. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  14834. else if ( type === 'bool' ) value = false;
  14835. else if ( type === 'color' ) value = new Color();
  14836. else if ( type === 'vec2' ) value = new Vector2();
  14837. else if ( type === 'vec3' ) value = new Vector3();
  14838. else if ( type === 'vec4' ) value = new Vector4();
  14839. }
  14840. if ( type === 'float' ) return toFloat( value );
  14841. if ( type === 'int' ) return `${ Math.round( value ) }`;
  14842. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  14843. if ( type === 'bool' ) return value ? 'true' : 'false';
  14844. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  14845. const typeLength = this.getTypeLength( type );
  14846. const componentType = this.getComponentType( type );
  14847. const generateConst = value => this.generateConst( componentType, value );
  14848. if ( typeLength === 2 ) {
  14849. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  14850. } else if ( typeLength === 3 ) {
  14851. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  14852. } else if ( typeLength === 4 ) {
  14853. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  14854. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  14855. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  14856. } else if ( typeLength > 4 ) {
  14857. return `${ this.getType( type ) }()`;
  14858. }
  14859. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  14860. }
  14861. getType( type ) {
  14862. if ( type === 'color' ) return 'vec3';
  14863. return type;
  14864. }
  14865. hasGeometryAttribute( name ) {
  14866. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  14867. }
  14868. getAttribute( name, type ) {
  14869. const attributes = this.attributes;
  14870. // find attribute
  14871. for ( const attribute of attributes ) {
  14872. if ( attribute.name === name ) {
  14873. return attribute;
  14874. }
  14875. }
  14876. // create a new if no exist
  14877. const attribute = new NodeAttribute( name, type );
  14878. attributes.push( attribute );
  14879. return attribute;
  14880. }
  14881. getPropertyName( node/*, shaderStage*/ ) {
  14882. return node.name;
  14883. }
  14884. isVector( type ) {
  14885. return /vec\d/.test( type );
  14886. }
  14887. isMatrix( type ) {
  14888. return /mat\d/.test( type );
  14889. }
  14890. isReference( type ) {
  14891. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  14892. }
  14893. needsToWorkingColorSpace( /*texture*/ ) {
  14894. return false;
  14895. }
  14896. getComponentTypeFromTexture( texture ) {
  14897. const type = texture.type;
  14898. if ( texture.isDataTexture ) {
  14899. if ( type === IntType ) return 'int';
  14900. if ( type === UnsignedIntType ) return 'uint';
  14901. }
  14902. return 'float';
  14903. }
  14904. getElementType( type ) {
  14905. if ( type === 'mat2' ) return 'vec2';
  14906. if ( type === 'mat3' ) return 'vec3';
  14907. if ( type === 'mat4' ) return 'vec4';
  14908. return this.getComponentType( type );
  14909. }
  14910. getComponentType( type ) {
  14911. type = this.getVectorType( type );
  14912. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  14913. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  14914. if ( componentType === null ) return null;
  14915. if ( componentType[ 1 ] === 'b' ) return 'bool';
  14916. if ( componentType[ 1 ] === 'i' ) return 'int';
  14917. if ( componentType[ 1 ] === 'u' ) return 'uint';
  14918. return 'float';
  14919. }
  14920. getVectorType( type ) {
  14921. if ( type === 'color' ) return 'vec3';
  14922. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  14923. return type;
  14924. }
  14925. getTypeFromLength( length, componentType = 'float' ) {
  14926. if ( length === 1 ) return componentType;
  14927. const baseType = typeFromLength.get( length );
  14928. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  14929. return prefix + baseType;
  14930. }
  14931. getTypeFromArray( array ) {
  14932. return typeFromArray.get( array.constructor );
  14933. }
  14934. getTypeFromAttribute( attribute ) {
  14935. let dataAttribute = attribute;
  14936. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  14937. const array = dataAttribute.array;
  14938. const itemSize = attribute.itemSize;
  14939. const normalized = attribute.normalized;
  14940. let arrayType;
  14941. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  14942. arrayType = this.getTypeFromArray( array );
  14943. }
  14944. return this.getTypeFromLength( itemSize, arrayType );
  14945. }
  14946. getTypeLength( type ) {
  14947. const vecType = this.getVectorType( type );
  14948. const vecNum = /vec([2-4])/.exec( vecType );
  14949. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  14950. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  14951. if ( /mat2/.test( type ) === true ) return 4;
  14952. if ( /mat3/.test( type ) === true ) return 9;
  14953. if ( /mat4/.test( type ) === true ) return 16;
  14954. return 0;
  14955. }
  14956. getVectorFromMatrix( type ) {
  14957. return type.replace( 'mat', 'vec' );
  14958. }
  14959. changeComponentType( type, newComponentType ) {
  14960. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  14961. }
  14962. getIntegerType( type ) {
  14963. const componentType = this.getComponentType( type );
  14964. if ( componentType === 'int' || componentType === 'uint' ) return type;
  14965. return this.changeComponentType( type, 'int' );
  14966. }
  14967. addStack() {
  14968. this.stack = stack( this.stack );
  14969. this.stacks.push( getCurrentStack() || this.stack );
  14970. setCurrentStack( this.stack );
  14971. return this.stack;
  14972. }
  14973. removeStack() {
  14974. const lastStack = this.stack;
  14975. this.stack = lastStack.parent;
  14976. setCurrentStack( this.stacks.pop() );
  14977. return lastStack;
  14978. }
  14979. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  14980. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  14981. let nodeData = cache.getData( node );
  14982. if ( nodeData === undefined ) {
  14983. nodeData = {};
  14984. cache.setData( node, nodeData );
  14985. }
  14986. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  14987. return nodeData[ shaderStage ];
  14988. }
  14989. getNodeProperties( node, shaderStage = 'any' ) {
  14990. const nodeData = this.getDataFromNode( node, shaderStage );
  14991. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  14992. }
  14993. getBufferAttributeFromNode( node, type ) {
  14994. const nodeData = this.getDataFromNode( node );
  14995. let bufferAttribute = nodeData.bufferAttribute;
  14996. if ( bufferAttribute === undefined ) {
  14997. const index = this.uniforms.index ++;
  14998. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  14999. this.bufferAttributes.push( bufferAttribute );
  15000. nodeData.bufferAttribute = bufferAttribute;
  15001. }
  15002. return bufferAttribute;
  15003. }
  15004. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  15005. const nodeData = this.getDataFromNode( node, shaderStage );
  15006. if ( nodeData.structType === undefined ) {
  15007. const index = this.structs.index ++;
  15008. node.name = `StructType${ index }`;
  15009. this.structs[ shaderStage ].push( node );
  15010. nodeData.structType = node;
  15011. }
  15012. return node;
  15013. }
  15014. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  15015. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  15016. let nodeUniform = nodeData.uniform;
  15017. if ( nodeUniform === undefined ) {
  15018. const index = this.uniforms.index ++;
  15019. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  15020. this.uniforms[ shaderStage ].push( nodeUniform );
  15021. nodeData.uniform = nodeUniform;
  15022. }
  15023. return nodeUniform;
  15024. }
  15025. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  15026. const nodeData = this.getDataFromNode( node, shaderStage );
  15027. let nodeVar = nodeData.variable;
  15028. if ( nodeVar === undefined ) {
  15029. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  15030. if ( name === null ) name = 'nodeVar' + vars.length;
  15031. nodeVar = new NodeVar( name, type );
  15032. vars.push( nodeVar );
  15033. nodeData.variable = nodeVar;
  15034. }
  15035. return nodeVar;
  15036. }
  15037. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  15038. const nodeData = this.getDataFromNode( node, 'any' );
  15039. let nodeVarying = nodeData.varying;
  15040. if ( nodeVarying === undefined ) {
  15041. const varyings = this.varyings;
  15042. const index = varyings.length;
  15043. if ( name === null ) name = 'nodeVarying' + index;
  15044. nodeVarying = new NodeVarying( name, type );
  15045. varyings.push( nodeVarying );
  15046. nodeData.varying = nodeVarying;
  15047. }
  15048. return nodeVarying;
  15049. }
  15050. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  15051. const nodeData = this.getDataFromNode( node );
  15052. let nodeCode = nodeData.code;
  15053. if ( nodeCode === undefined ) {
  15054. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  15055. const index = codes.length;
  15056. nodeCode = new NodeCode( 'nodeCode' + index, type );
  15057. codes.push( nodeCode );
  15058. nodeData.code = nodeCode;
  15059. }
  15060. return nodeCode;
  15061. }
  15062. addFlowCodeHierarchy( node, nodeBlock ) {
  15063. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  15064. let needsFlowCode = true;
  15065. let nodeBlockHierarchy = nodeBlock;
  15066. while ( nodeBlockHierarchy ) {
  15067. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  15068. needsFlowCode = false;
  15069. break;
  15070. }
  15071. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  15072. }
  15073. if ( needsFlowCode ) {
  15074. for ( const flowCode of flowCodes ) {
  15075. this.addLineFlowCode( flowCode );
  15076. }
  15077. }
  15078. }
  15079. addLineFlowCodeBlock( node, code, nodeBlock ) {
  15080. const nodeData = this.getDataFromNode( node );
  15081. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  15082. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  15083. flowCodes.push( code );
  15084. codeBlock.set( nodeBlock, true );
  15085. }
  15086. addLineFlowCode( code, node = null ) {
  15087. if ( code === '' ) return this;
  15088. if ( node !== null && this.context.nodeBlock ) {
  15089. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  15090. }
  15091. code = this.tab + code;
  15092. if ( ! /;\s*$/.test( code ) ) {
  15093. code = code + ';\n';
  15094. }
  15095. this.flow.code += code;
  15096. return this;
  15097. }
  15098. addFlowCode( code ) {
  15099. this.flow.code += code;
  15100. return this;
  15101. }
  15102. addFlowTab() {
  15103. this.tab += '\t';
  15104. return this;
  15105. }
  15106. removeFlowTab() {
  15107. this.tab = this.tab.slice( 0, - 1 );
  15108. return this;
  15109. }
  15110. getFlowData( node/*, shaderStage*/ ) {
  15111. return this.flowsData.get( node );
  15112. }
  15113. flowNode( node ) {
  15114. const output = node.getNodeType( this );
  15115. const flowData = this.flowChildNode( node, output );
  15116. this.flowsData.set( node, flowData );
  15117. return flowData;
  15118. }
  15119. buildFunctionNode( shaderNode ) {
  15120. const fn = new FunctionNode();
  15121. const previous = this.currentFunctionNode;
  15122. this.currentFunctionNode = fn;
  15123. fn.code = this.buildFunctionCode( shaderNode );
  15124. this.currentFunctionNode = previous;
  15125. return fn;
  15126. }
  15127. flowShaderNode( shaderNode ) {
  15128. const layout = shaderNode.layout;
  15129. const inputs = {
  15130. [ Symbol.iterator ]() {
  15131. let index = 0;
  15132. const values = Object.values( this );
  15133. return {
  15134. next: () => ( {
  15135. value: values[ index ],
  15136. done: index ++ >= values.length
  15137. } )
  15138. };
  15139. }
  15140. };
  15141. for ( const input of layout.inputs ) {
  15142. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  15143. }
  15144. //
  15145. shaderNode.layout = null;
  15146. const callNode = shaderNode.call( inputs );
  15147. const flowData = this.flowStagesNode( callNode, layout.type );
  15148. shaderNode.layout = layout;
  15149. return flowData;
  15150. }
  15151. flowStagesNode( node, output = null ) {
  15152. const previousFlow = this.flow;
  15153. const previousVars = this.vars;
  15154. const previousCache = this.cache;
  15155. const previousBuildStage = this.buildStage;
  15156. const previousStack = this.stack;
  15157. const flow = {
  15158. code: ''
  15159. };
  15160. this.flow = flow;
  15161. this.vars = {};
  15162. this.cache = new NodeCache();
  15163. this.stack = stack();
  15164. for ( const buildStage of defaultBuildStages ) {
  15165. this.setBuildStage( buildStage );
  15166. flow.result = node.build( this, output );
  15167. }
  15168. flow.vars = this.getVars( this.shaderStage );
  15169. this.flow = previousFlow;
  15170. this.vars = previousVars;
  15171. this.cache = previousCache;
  15172. this.stack = previousStack;
  15173. this.setBuildStage( previousBuildStage );
  15174. return flow;
  15175. }
  15176. getFunctionOperator() {
  15177. return null;
  15178. }
  15179. flowChildNode( node, output = null ) {
  15180. const previousFlow = this.flow;
  15181. const flow = {
  15182. code: ''
  15183. };
  15184. this.flow = flow;
  15185. flow.result = node.build( this, output );
  15186. this.flow = previousFlow;
  15187. return flow;
  15188. }
  15189. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  15190. const previousShaderStage = this.shaderStage;
  15191. this.setShaderStage( shaderStage );
  15192. const flowData = this.flowChildNode( node, output );
  15193. if ( propertyName !== null ) {
  15194. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  15195. }
  15196. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  15197. this.setShaderStage( previousShaderStage );
  15198. return flowData;
  15199. }
  15200. getAttributesArray() {
  15201. return this.attributes.concat( this.bufferAttributes );
  15202. }
  15203. getAttributes( /*shaderStage*/ ) {
  15204. console.warn( 'Abstract function.' );
  15205. }
  15206. getVaryings( /*shaderStage*/ ) {
  15207. console.warn( 'Abstract function.' );
  15208. }
  15209. getVar( type, name ) {
  15210. return `${ this.getType( type ) } ${ name }`;
  15211. }
  15212. getVars( shaderStage ) {
  15213. let snippet = '';
  15214. const vars = this.vars[ shaderStage ];
  15215. if ( vars !== undefined ) {
  15216. for ( const variable of vars ) {
  15217. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  15218. }
  15219. }
  15220. return snippet;
  15221. }
  15222. getUniforms( /*shaderStage*/ ) {
  15223. console.warn( 'Abstract function.' );
  15224. }
  15225. getCodes( shaderStage ) {
  15226. const codes = this.codes[ shaderStage ];
  15227. let code = '';
  15228. if ( codes !== undefined ) {
  15229. for ( const nodeCode of codes ) {
  15230. code += nodeCode.code + '\n';
  15231. }
  15232. }
  15233. return code;
  15234. }
  15235. getHash() {
  15236. return this.vertexShader + this.fragmentShader + this.computeShader;
  15237. }
  15238. setShaderStage( shaderStage ) {
  15239. this.shaderStage = shaderStage;
  15240. }
  15241. getShaderStage() {
  15242. return this.shaderStage;
  15243. }
  15244. setBuildStage( buildStage ) {
  15245. this.buildStage = buildStage;
  15246. }
  15247. getBuildStage() {
  15248. return this.buildStage;
  15249. }
  15250. buildCode() {
  15251. console.warn( 'Abstract function.' );
  15252. }
  15253. build() {
  15254. const { object, material, renderer } = this;
  15255. if ( material !== null ) {
  15256. let nodeMaterial = renderer.library.fromMaterial( material );
  15257. if ( nodeMaterial === null ) {
  15258. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15259. nodeMaterial = new NodeMaterial();
  15260. }
  15261. nodeMaterial.build( this );
  15262. } else {
  15263. this.addFlow( 'compute', object );
  15264. }
  15265. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15266. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15267. // generate() -> stage 3: generate shader
  15268. for ( const buildStage of defaultBuildStages ) {
  15269. this.setBuildStage( buildStage );
  15270. if ( this.context.vertex && this.context.vertex.isNode ) {
  15271. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15272. }
  15273. for ( const shaderStage of shaderStages ) {
  15274. this.setShaderStage( shaderStage );
  15275. const flowNodes = this.flowNodes[ shaderStage ];
  15276. for ( const node of flowNodes ) {
  15277. if ( buildStage === 'generate' ) {
  15278. this.flowNode( node );
  15279. } else {
  15280. node.build( this );
  15281. }
  15282. }
  15283. }
  15284. }
  15285. this.setBuildStage( null );
  15286. this.setShaderStage( null );
  15287. // stage 4: build code for a specific output
  15288. this.buildCode();
  15289. this.buildUpdateNodes();
  15290. return this;
  15291. }
  15292. getNodeUniform( uniformNode, type ) {
  15293. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15294. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15295. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15296. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15297. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15298. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15299. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15300. throw new Error( `Uniform "${type}" not declared.` );
  15301. }
  15302. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15303. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15304. }
  15305. format( snippet, fromType, toType ) {
  15306. fromType = this.getVectorType( fromType );
  15307. toType = this.getVectorType( toType );
  15308. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15309. return snippet;
  15310. }
  15311. const fromTypeLength = this.getTypeLength( fromType );
  15312. const toTypeLength = this.getTypeLength( toType );
  15313. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15314. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15315. }
  15316. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15317. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15318. }
  15319. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15320. // @TODO: ignore for now
  15321. return snippet;
  15322. }
  15323. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15324. // @TODO: ignore for now
  15325. return snippet;
  15326. }
  15327. if ( fromTypeLength === toTypeLength ) {
  15328. return `${ this.getType( toType ) }( ${ snippet } )`;
  15329. }
  15330. if ( fromTypeLength > toTypeLength ) {
  15331. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15332. }
  15333. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15334. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15335. }
  15336. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15337. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15338. }
  15339. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15340. // convert a number value to vector type, e.g:
  15341. // vec3( 1u ) -> vec3( float( 1u ) )
  15342. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15343. }
  15344. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15345. }
  15346. getSignature() {
  15347. return `// Three.js r${ REVISION } - Node System\n`;
  15348. }
  15349. }
  15350. class NodeFrame {
  15351. constructor() {
  15352. this.time = 0;
  15353. this.deltaTime = 0;
  15354. this.frameId = 0;
  15355. this.renderId = 0;
  15356. this.startTime = null;
  15357. this.updateMap = new WeakMap();
  15358. this.updateBeforeMap = new WeakMap();
  15359. this.updateAfterMap = new WeakMap();
  15360. this.renderer = null;
  15361. this.material = null;
  15362. this.camera = null;
  15363. this.object = null;
  15364. this.scene = null;
  15365. }
  15366. _getMaps( referenceMap, nodeRef ) {
  15367. let maps = referenceMap.get( nodeRef );
  15368. if ( maps === undefined ) {
  15369. maps = {
  15370. renderMap: new WeakMap(),
  15371. frameMap: new WeakMap()
  15372. };
  15373. referenceMap.set( nodeRef, maps );
  15374. }
  15375. return maps;
  15376. }
  15377. updateBeforeNode( node ) {
  15378. const updateType = node.getUpdateBeforeType();
  15379. const reference = node.updateReference( this );
  15380. if ( updateType === NodeUpdateType.FRAME ) {
  15381. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15382. if ( frameMap.get( reference ) !== this.frameId ) {
  15383. if ( node.updateBefore( this ) !== false ) {
  15384. frameMap.set( reference, this.frameId );
  15385. }
  15386. }
  15387. } else if ( updateType === NodeUpdateType.RENDER ) {
  15388. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15389. if ( renderMap.get( reference ) !== this.renderId ) {
  15390. if ( node.updateBefore( this ) !== false ) {
  15391. renderMap.set( reference, this.renderId );
  15392. }
  15393. }
  15394. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15395. node.updateBefore( this );
  15396. }
  15397. }
  15398. updateAfterNode( node ) {
  15399. const updateType = node.getUpdateAfterType();
  15400. const reference = node.updateReference( this );
  15401. if ( updateType === NodeUpdateType.FRAME ) {
  15402. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15403. if ( frameMap.get( reference ) !== this.frameId ) {
  15404. if ( node.updateAfter( this ) !== false ) {
  15405. frameMap.set( reference, this.frameId );
  15406. }
  15407. }
  15408. } else if ( updateType === NodeUpdateType.RENDER ) {
  15409. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15410. if ( renderMap.get( reference ) !== this.renderId ) {
  15411. if ( node.updateAfter( this ) !== false ) {
  15412. renderMap.set( reference, this.renderId );
  15413. }
  15414. }
  15415. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15416. node.updateAfter( this );
  15417. }
  15418. }
  15419. updateNode( node ) {
  15420. const updateType = node.getUpdateType();
  15421. const reference = node.updateReference( this );
  15422. if ( updateType === NodeUpdateType.FRAME ) {
  15423. const { frameMap } = this._getMaps( this.updateMap, reference );
  15424. if ( frameMap.get( reference ) !== this.frameId ) {
  15425. if ( node.update( this ) !== false ) {
  15426. frameMap.set( reference, this.frameId );
  15427. }
  15428. }
  15429. } else if ( updateType === NodeUpdateType.RENDER ) {
  15430. const { renderMap } = this._getMaps( this.updateMap, reference );
  15431. if ( renderMap.get( reference ) !== this.renderId ) {
  15432. if ( node.update( this ) !== false ) {
  15433. renderMap.set( reference, this.renderId );
  15434. }
  15435. }
  15436. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15437. node.update( this );
  15438. }
  15439. }
  15440. update() {
  15441. this.frameId ++;
  15442. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15443. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15444. this.lastTime = performance.now();
  15445. this.time += this.deltaTime;
  15446. }
  15447. }
  15448. class NodeFunctionInput {
  15449. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15450. this.type = type;
  15451. this.name = name;
  15452. this.count = count;
  15453. this.qualifier = qualifier;
  15454. this.isConst = isConst;
  15455. }
  15456. }
  15457. NodeFunctionInput.isNodeFunctionInput = true;
  15458. class DirectionalLightNode extends AnalyticLightNode {
  15459. static get type() {
  15460. return 'DirectionalLightNode';
  15461. }
  15462. constructor( light = null ) {
  15463. super( light );
  15464. }
  15465. setup( builder ) {
  15466. super.setup( builder );
  15467. const lightingModel = builder.context.lightingModel;
  15468. const lightColor = this.colorNode;
  15469. const lightDirection = lightTargetDirection( this.light );
  15470. const reflectedLight = builder.context.reflectedLight;
  15471. lightingModel.direct( {
  15472. lightDirection,
  15473. lightColor,
  15474. reflectedLight
  15475. }, builder.stack, builder );
  15476. }
  15477. }
  15478. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15479. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15480. let ltcLib = null;
  15481. class RectAreaLightNode extends AnalyticLightNode {
  15482. static get type() {
  15483. return 'RectAreaLightNode';
  15484. }
  15485. constructor( light = null ) {
  15486. super( light );
  15487. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15488. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15489. this.updateType = NodeUpdateType.RENDER;
  15490. }
  15491. update( frame ) {
  15492. super.update( frame );
  15493. const { light } = this;
  15494. const viewMatrix = frame.camera.matrixWorldInverse;
  15495. _matrix42.identity();
  15496. _matrix41.copy( light.matrixWorld );
  15497. _matrix41.premultiply( viewMatrix );
  15498. _matrix42.extractRotation( _matrix41 );
  15499. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15500. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15501. this.halfWidth.value.applyMatrix4( _matrix42 );
  15502. this.halfHeight.value.applyMatrix4( _matrix42 );
  15503. }
  15504. setup( builder ) {
  15505. super.setup( builder );
  15506. let ltc_1, ltc_2;
  15507. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15508. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15509. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15510. } else {
  15511. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15512. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15513. }
  15514. const { colorNode, light } = this;
  15515. const lightingModel = builder.context.lightingModel;
  15516. const lightPosition = lightViewPosition( light );
  15517. const reflectedLight = builder.context.reflectedLight;
  15518. lightingModel.directRectArea( {
  15519. lightColor: colorNode,
  15520. lightPosition,
  15521. halfWidth: this.halfWidth,
  15522. halfHeight: this.halfHeight,
  15523. reflectedLight,
  15524. ltc_1,
  15525. ltc_2
  15526. }, builder.stack, builder );
  15527. }
  15528. static setLTC( ltc ) {
  15529. ltcLib = ltc;
  15530. }
  15531. }
  15532. class SpotLightNode extends AnalyticLightNode {
  15533. static get type() {
  15534. return 'SpotLightNode';
  15535. }
  15536. constructor( light = null ) {
  15537. super( light );
  15538. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15539. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15540. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15541. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15542. }
  15543. update( frame ) {
  15544. super.update( frame );
  15545. const { light } = this;
  15546. this.coneCosNode.value = Math.cos( light.angle );
  15547. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15548. this.cutoffDistanceNode.value = light.distance;
  15549. this.decayExponentNode.value = light.decay;
  15550. }
  15551. getSpotAttenuation( angleCosine ) {
  15552. const { coneCosNode, penumbraCosNode } = this;
  15553. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15554. }
  15555. setup( builder ) {
  15556. super.setup( builder );
  15557. const lightingModel = builder.context.lightingModel;
  15558. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15559. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15560. const lightDirection = lVector.normalize();
  15561. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15562. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15563. const lightDistance = lVector.length();
  15564. const lightAttenuation = getDistanceAttenuation( {
  15565. lightDistance,
  15566. cutoffDistance: cutoffDistanceNode,
  15567. decayExponent: decayExponentNode
  15568. } );
  15569. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  15570. const reflectedLight = builder.context.reflectedLight;
  15571. lightingModel.direct( {
  15572. lightDirection,
  15573. lightColor,
  15574. reflectedLight
  15575. }, builder.stack, builder );
  15576. }
  15577. }
  15578. class IESSpotLightNode extends SpotLightNode {
  15579. static get type() {
  15580. return 'IESSpotLightNode';
  15581. }
  15582. getSpotAttenuation( angleCosine ) {
  15583. const iesMap = this.light.iesMap;
  15584. let spotAttenuation = null;
  15585. if ( iesMap && iesMap.isTexture === true ) {
  15586. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  15587. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  15588. } else {
  15589. spotAttenuation = super.getSpotAttenuation( angleCosine );
  15590. }
  15591. return spotAttenuation;
  15592. }
  15593. }
  15594. class AmbientLightNode extends AnalyticLightNode {
  15595. static get type() {
  15596. return 'AmbientLightNode';
  15597. }
  15598. constructor( light = null ) {
  15599. super( light );
  15600. }
  15601. setup( { context } ) {
  15602. context.irradiance.addAssign( this.colorNode );
  15603. }
  15604. }
  15605. class HemisphereLightNode extends AnalyticLightNode {
  15606. static get type() {
  15607. return 'HemisphereLightNode';
  15608. }
  15609. constructor( light = null ) {
  15610. super( light );
  15611. this.lightPositionNode = lightPosition( light );
  15612. this.lightDirectionNode = this.lightPositionNode.normalize();
  15613. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  15614. }
  15615. update( frame ) {
  15616. const { light } = this;
  15617. super.update( frame );
  15618. this.lightPositionNode.object3d = light;
  15619. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  15620. }
  15621. setup( builder ) {
  15622. const { colorNode, groundColorNode, lightDirectionNode } = this;
  15623. const dotNL = normalView.dot( lightDirectionNode );
  15624. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  15625. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  15626. builder.context.irradiance.addAssign( irradiance );
  15627. }
  15628. }
  15629. class LightProbeNode extends AnalyticLightNode {
  15630. static get type() {
  15631. return 'LightProbeNode';
  15632. }
  15633. constructor( light = null ) {
  15634. super( light );
  15635. const array = [];
  15636. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  15637. this.lightProbe = uniformArray( array );
  15638. }
  15639. update( frame ) {
  15640. const { light } = this;
  15641. super.update( frame );
  15642. //
  15643. for ( let i = 0; i < 9; i ++ ) {
  15644. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  15645. }
  15646. }
  15647. setup( builder ) {
  15648. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  15649. builder.context.irradiance.addAssign( irradiance );
  15650. }
  15651. }
  15652. class NodeParser {
  15653. parseFunction( /*source*/ ) {
  15654. console.warn( 'Abstract function.' );
  15655. }
  15656. }
  15657. class NodeFunction {
  15658. constructor( type, inputs, name = '', precision = '' ) {
  15659. this.type = type;
  15660. this.inputs = inputs;
  15661. this.name = name;
  15662. this.precision = precision;
  15663. }
  15664. getCode( /*name = this.name*/ ) {
  15665. console.warn( 'Abstract function.' );
  15666. }
  15667. }
  15668. NodeFunction.isNodeFunction = true;
  15669. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  15670. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  15671. const pragmaMain = '#pragma main';
  15672. const parse$1 = ( source ) => {
  15673. source = source.trim();
  15674. const pragmaMainIndex = source.indexOf( pragmaMain );
  15675. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  15676. const declaration = mainCode.match( declarationRegexp$1 );
  15677. if ( declaration !== null && declaration.length === 5 ) {
  15678. // tokenizer
  15679. const inputsCode = declaration[ 4 ];
  15680. const propsMatches = [];
  15681. let nameMatch = null;
  15682. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  15683. propsMatches.push( nameMatch );
  15684. }
  15685. // parser
  15686. const inputs = [];
  15687. let i = 0;
  15688. while ( i < propsMatches.length ) {
  15689. const isConst = propsMatches[ i ][ 0 ] === 'const';
  15690. if ( isConst === true ) {
  15691. i ++;
  15692. }
  15693. let qualifier = propsMatches[ i ][ 0 ];
  15694. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  15695. i ++;
  15696. } else {
  15697. qualifier = '';
  15698. }
  15699. const type = propsMatches[ i ++ ][ 0 ];
  15700. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  15701. if ( Number.isNaN( count ) === false ) i ++;
  15702. else count = null;
  15703. const name = propsMatches[ i ++ ][ 0 ];
  15704. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  15705. }
  15706. //
  15707. const blockCode = mainCode.substring( declaration[ 0 ].length );
  15708. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  15709. const type = declaration[ 2 ];
  15710. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  15711. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  15712. return {
  15713. type,
  15714. inputs,
  15715. name,
  15716. precision,
  15717. inputsCode,
  15718. blockCode,
  15719. headerCode
  15720. };
  15721. } else {
  15722. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  15723. }
  15724. };
  15725. class GLSLNodeFunction extends NodeFunction {
  15726. constructor( source ) {
  15727. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  15728. super( type, inputs, name, precision );
  15729. this.inputsCode = inputsCode;
  15730. this.blockCode = blockCode;
  15731. this.headerCode = headerCode;
  15732. }
  15733. getCode( name = this.name ) {
  15734. let code;
  15735. const blockCode = this.blockCode;
  15736. if ( blockCode !== '' ) {
  15737. const { type, inputsCode, headerCode, precision } = this;
  15738. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  15739. if ( precision !== '' ) {
  15740. declarationCode = `${ precision } ${ declarationCode }`;
  15741. }
  15742. code = headerCode + declarationCode + blockCode;
  15743. } else {
  15744. // interface function
  15745. code = '';
  15746. }
  15747. return code;
  15748. }
  15749. }
  15750. class GLSLNodeParser extends NodeParser {
  15751. parseFunction( source ) {
  15752. return new GLSLNodeFunction( source );
  15753. }
  15754. }
  15755. const outputNodeMap = new WeakMap();
  15756. class Nodes extends DataMap {
  15757. constructor( renderer, backend ) {
  15758. super();
  15759. this.renderer = renderer;
  15760. this.backend = backend;
  15761. this.nodeFrame = new NodeFrame();
  15762. this.nodeBuilderCache = new Map();
  15763. this.callHashCache = new ChainMap();
  15764. this.groupsData = new ChainMap();
  15765. }
  15766. updateGroup( nodeUniformsGroup ) {
  15767. const groupNode = nodeUniformsGroup.groupNode;
  15768. const name = groupNode.name;
  15769. // objectGroup is every updated
  15770. if ( name === objectGroup.name ) return true;
  15771. // renderGroup is updated once per render/compute call
  15772. if ( name === renderGroup.name ) {
  15773. const uniformsGroupData = this.get( nodeUniformsGroup );
  15774. const renderId = this.nodeFrame.renderId;
  15775. if ( uniformsGroupData.renderId !== renderId ) {
  15776. uniformsGroupData.renderId = renderId;
  15777. return true;
  15778. }
  15779. return false;
  15780. }
  15781. // frameGroup is updated once per frame
  15782. if ( name === frameGroup.name ) {
  15783. const uniformsGroupData = this.get( nodeUniformsGroup );
  15784. const frameId = this.nodeFrame.frameId;
  15785. if ( uniformsGroupData.frameId !== frameId ) {
  15786. uniformsGroupData.frameId = frameId;
  15787. return true;
  15788. }
  15789. return false;
  15790. }
  15791. // other groups are updated just when groupNode.needsUpdate is true
  15792. const groupChain = [ groupNode, nodeUniformsGroup ];
  15793. let groupData = this.groupsData.get( groupChain );
  15794. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  15795. if ( groupData.version !== groupNode.version ) {
  15796. groupData.version = groupNode.version;
  15797. return true;
  15798. }
  15799. return false;
  15800. }
  15801. getForRenderCacheKey( renderObject ) {
  15802. return renderObject.initialCacheKey;
  15803. }
  15804. getForRender( renderObject ) {
  15805. const renderObjectData = this.get( renderObject );
  15806. let nodeBuilderState = renderObjectData.nodeBuilderState;
  15807. if ( nodeBuilderState === undefined ) {
  15808. const { nodeBuilderCache } = this;
  15809. const cacheKey = this.getForRenderCacheKey( renderObject );
  15810. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  15811. if ( nodeBuilderState === undefined ) {
  15812. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  15813. nodeBuilder.scene = renderObject.scene;
  15814. nodeBuilder.material = renderObject.material;
  15815. nodeBuilder.camera = renderObject.camera;
  15816. nodeBuilder.context.material = renderObject.material;
  15817. nodeBuilder.lightsNode = renderObject.lightsNode;
  15818. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  15819. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  15820. nodeBuilder.clippingContext = renderObject.clippingContext;
  15821. nodeBuilder.build();
  15822. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15823. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  15824. }
  15825. nodeBuilderState.usedTimes ++;
  15826. renderObjectData.nodeBuilderState = nodeBuilderState;
  15827. }
  15828. return nodeBuilderState;
  15829. }
  15830. delete( object ) {
  15831. if ( object.isRenderObject ) {
  15832. const nodeBuilderState = this.get( object ).nodeBuilderState;
  15833. nodeBuilderState.usedTimes --;
  15834. if ( nodeBuilderState.usedTimes === 0 ) {
  15835. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  15836. }
  15837. }
  15838. return super.delete( object );
  15839. }
  15840. getForCompute( computeNode ) {
  15841. const computeData = this.get( computeNode );
  15842. let nodeBuilderState = computeData.nodeBuilderState;
  15843. if ( nodeBuilderState === undefined ) {
  15844. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  15845. nodeBuilder.build();
  15846. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15847. computeData.nodeBuilderState = nodeBuilderState;
  15848. }
  15849. return nodeBuilderState;
  15850. }
  15851. _createNodeBuilderState( nodeBuilder ) {
  15852. return new NodeBuilderState(
  15853. nodeBuilder.vertexShader,
  15854. nodeBuilder.fragmentShader,
  15855. nodeBuilder.computeShader,
  15856. nodeBuilder.getAttributesArray(),
  15857. nodeBuilder.getBindings(),
  15858. nodeBuilder.updateNodes,
  15859. nodeBuilder.updateBeforeNodes,
  15860. nodeBuilder.updateAfterNodes,
  15861. nodeBuilder.monitor,
  15862. nodeBuilder.transforms
  15863. );
  15864. }
  15865. getEnvironmentNode( scene ) {
  15866. return scene.environmentNode || this.get( scene ).environmentNode || null;
  15867. }
  15868. getBackgroundNode( scene ) {
  15869. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  15870. }
  15871. getFogNode( scene ) {
  15872. return scene.fogNode || this.get( scene ).fogNode || null;
  15873. }
  15874. getCacheKey( scene, lightsNode ) {
  15875. const chain = [ scene, lightsNode ];
  15876. const callId = this.renderer.info.calls;
  15877. let cacheKeyData = this.callHashCache.get( chain );
  15878. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  15879. const environmentNode = this.getEnvironmentNode( scene );
  15880. const fogNode = this.getFogNode( scene );
  15881. const values = [];
  15882. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  15883. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  15884. if ( fogNode ) values.push( fogNode.getCacheKey() );
  15885. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  15886. cacheKeyData = {
  15887. callId,
  15888. cacheKey: hashArray( values )
  15889. };
  15890. this.callHashCache.set( chain, cacheKeyData );
  15891. }
  15892. return cacheKeyData.cacheKey;
  15893. }
  15894. updateScene( scene ) {
  15895. this.updateEnvironment( scene );
  15896. this.updateFog( scene );
  15897. this.updateBackground( scene );
  15898. }
  15899. get isToneMappingState() {
  15900. return this.renderer.getRenderTarget() ? false : true;
  15901. }
  15902. updateBackground( scene ) {
  15903. const sceneData = this.get( scene );
  15904. const background = scene.background;
  15905. if ( background ) {
  15906. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  15907. if ( sceneData.background !== background || forceUpdate ) {
  15908. let backgroundNode = null;
  15909. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  15910. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  15911. backgroundNode = pmremTexture( background );
  15912. } else {
  15913. let envMap;
  15914. if ( background.isCubeTexture === true ) {
  15915. envMap = cubeTexture( background );
  15916. } else {
  15917. envMap = texture( background );
  15918. }
  15919. backgroundNode = cubeMapNode( envMap );
  15920. }
  15921. } else if ( background.isTexture === true ) {
  15922. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  15923. } else if ( background.isColor !== true ) {
  15924. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  15925. }
  15926. sceneData.backgroundNode = backgroundNode;
  15927. sceneData.background = background;
  15928. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  15929. }
  15930. } else if ( sceneData.backgroundNode ) {
  15931. delete sceneData.backgroundNode;
  15932. delete sceneData.background;
  15933. }
  15934. }
  15935. updateFog( scene ) {
  15936. const sceneData = this.get( scene );
  15937. const fog = scene.fog;
  15938. if ( fog ) {
  15939. if ( sceneData.fog !== fog ) {
  15940. let fogNode = null;
  15941. if ( fog.isFogExp2 ) {
  15942. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15943. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  15944. fogNode = densityFog( color, density );
  15945. } else if ( fog.isFog ) {
  15946. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15947. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  15948. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  15949. fogNode = rangeFog( color, near, far );
  15950. } else {
  15951. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  15952. }
  15953. sceneData.fogNode = fogNode;
  15954. sceneData.fog = fog;
  15955. }
  15956. } else {
  15957. delete sceneData.fogNode;
  15958. delete sceneData.fog;
  15959. }
  15960. }
  15961. updateEnvironment( scene ) {
  15962. const sceneData = this.get( scene );
  15963. const environment = scene.environment;
  15964. if ( environment ) {
  15965. if ( sceneData.environment !== environment ) {
  15966. let environmentNode = null;
  15967. if ( environment.isCubeTexture === true ) {
  15968. environmentNode = cubeTexture( environment );
  15969. } else if ( environment.isTexture === true ) {
  15970. environmentNode = texture( environment );
  15971. } else {
  15972. console.error( 'Nodes: Unsupported environment configuration.', environment );
  15973. }
  15974. sceneData.environmentNode = environmentNode;
  15975. sceneData.environment = environment;
  15976. }
  15977. } else if ( sceneData.environmentNode ) {
  15978. delete sceneData.environmentNode;
  15979. delete sceneData.environment;
  15980. }
  15981. }
  15982. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  15983. const nodeFrame = this.nodeFrame;
  15984. nodeFrame.renderer = renderer;
  15985. nodeFrame.scene = scene;
  15986. nodeFrame.object = object;
  15987. nodeFrame.camera = camera;
  15988. nodeFrame.material = material;
  15989. return nodeFrame;
  15990. }
  15991. getNodeFrameForRender( renderObject ) {
  15992. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  15993. }
  15994. getOutputCacheKey() {
  15995. const renderer = this.renderer;
  15996. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  15997. }
  15998. hasOutputChange( outputTarget ) {
  15999. const cacheKey = outputNodeMap.get( outputTarget );
  16000. return cacheKey !== this.getOutputCacheKey();
  16001. }
  16002. getOutputNode( outputTexture ) {
  16003. const renderer = this.renderer;
  16004. const cacheKey = this.getOutputCacheKey();
  16005. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  16006. outputNodeMap.set( outputTexture, cacheKey );
  16007. return output;
  16008. }
  16009. updateBefore( renderObject ) {
  16010. const nodeBuilder = renderObject.getNodeBuilderState();
  16011. for ( const node of nodeBuilder.updateBeforeNodes ) {
  16012. // update frame state for each node
  16013. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  16014. }
  16015. }
  16016. updateAfter( renderObject ) {
  16017. const nodeBuilder = renderObject.getNodeBuilderState();
  16018. for ( const node of nodeBuilder.updateAfterNodes ) {
  16019. // update frame state for each node
  16020. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  16021. }
  16022. }
  16023. updateForCompute( computeNode ) {
  16024. const nodeFrame = this.getNodeFrame();
  16025. const nodeBuilder = this.getForCompute( computeNode );
  16026. for ( const node of nodeBuilder.updateNodes ) {
  16027. nodeFrame.updateNode( node );
  16028. }
  16029. }
  16030. updateForRender( renderObject ) {
  16031. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16032. const nodeBuilder = renderObject.getNodeBuilderState();
  16033. for ( const node of nodeBuilder.updateNodes ) {
  16034. nodeFrame.updateNode( node );
  16035. }
  16036. }
  16037. needsRefresh( renderObject ) {
  16038. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16039. const monitor = renderObject.getMonitor();
  16040. return monitor.needsRefresh( renderObject, nodeFrame );
  16041. }
  16042. dispose() {
  16043. super.dispose();
  16044. this.nodeFrame = new NodeFrame();
  16045. this.nodeBuilderCache = new Map();
  16046. }
  16047. }
  16048. const _plane = /*@__PURE__*/ new Plane();
  16049. class ClippingContext {
  16050. constructor( parentContext = null ) {
  16051. this.version = 0;
  16052. this.clipIntersection = null;
  16053. this.cacheKey = '';
  16054. if ( parentContext === null ) {
  16055. this.intersectionPlanes = [];
  16056. this.unionPlanes = [];
  16057. this.viewNormalMatrix = new Matrix3();
  16058. this.clippingGroupContexts = new WeakMap();
  16059. this.shadowPass = false;
  16060. } else {
  16061. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  16062. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  16063. this.shadowPass = parentContext.shadowPass;
  16064. this.viewMatrix = parentContext.viewMatrix;
  16065. }
  16066. this.parentVersion = null;
  16067. }
  16068. projectPlanes( source, destination, offset ) {
  16069. const l = source.length;
  16070. for ( let i = 0; i < l; i ++ ) {
  16071. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  16072. const v = destination[ offset + i ];
  16073. const normal = _plane.normal;
  16074. v.x = - normal.x;
  16075. v.y = - normal.y;
  16076. v.z = - normal.z;
  16077. v.w = _plane.constant;
  16078. }
  16079. }
  16080. updateGlobal( scene, camera ) {
  16081. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  16082. this.viewMatrix = camera.matrixWorldInverse;
  16083. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  16084. }
  16085. update( parentContext, clippingGroup ) {
  16086. let update = false;
  16087. if ( parentContext.version !== this.parentVersion ) {
  16088. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  16089. this.unionPlanes = Array.from( parentContext.unionPlanes );
  16090. this.parentVersion = parentContext.version;
  16091. }
  16092. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  16093. this.clipIntersection = clippingGroup.clipIntersection;
  16094. if ( this.clipIntersection ) {
  16095. this.unionPlanes.length = parentContext.unionPlanes.length;
  16096. } else {
  16097. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  16098. }
  16099. }
  16100. const srcClippingPlanes = clippingGroup.clippingPlanes;
  16101. const l = srcClippingPlanes.length;
  16102. let dstClippingPlanes;
  16103. let offset;
  16104. if ( this.clipIntersection ) {
  16105. dstClippingPlanes = this.intersectionPlanes;
  16106. offset = parentContext.intersectionPlanes.length;
  16107. } else {
  16108. dstClippingPlanes = this.unionPlanes;
  16109. offset = parentContext.unionPlanes.length;
  16110. }
  16111. if ( dstClippingPlanes.length !== offset + l ) {
  16112. dstClippingPlanes.length = offset + l;
  16113. for ( let i = 0; i < l; i ++ ) {
  16114. dstClippingPlanes[ offset + i ] = new Vector4();
  16115. }
  16116. update = true;
  16117. }
  16118. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  16119. if ( update ) {
  16120. this.version ++;
  16121. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  16122. }
  16123. }
  16124. getGroupContext( clippingGroup ) {
  16125. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  16126. let context = this.clippingGroupContexts.get( clippingGroup );
  16127. if ( context === undefined ) {
  16128. context = new ClippingContext( this );
  16129. this.clippingGroupContexts.set( clippingGroup, context );
  16130. }
  16131. context.update( this, clippingGroup );
  16132. return context;
  16133. }
  16134. get unionClippingCount() {
  16135. return this.unionPlanes.length;
  16136. }
  16137. }
  16138. class RenderBundle {
  16139. constructor( scene, camera ) {
  16140. this.scene = scene;
  16141. this.camera = camera;
  16142. }
  16143. clone() {
  16144. return Object.assign( new this.constructor(), this );
  16145. }
  16146. }
  16147. class RenderBundles {
  16148. constructor() {
  16149. this.lists = new ChainMap();
  16150. }
  16151. get( scene, camera ) {
  16152. const lists = this.lists;
  16153. const keys = [ scene, camera ];
  16154. let list = lists.get( keys );
  16155. if ( list === undefined ) {
  16156. list = new RenderBundle( scene, camera );
  16157. lists.set( keys, list );
  16158. }
  16159. return list;
  16160. }
  16161. dispose() {
  16162. this.lists = new ChainMap();
  16163. }
  16164. }
  16165. class NodeLibrary {
  16166. constructor() {
  16167. this.lightNodes = new WeakMap();
  16168. this.materialNodes = new Map();
  16169. this.toneMappingNodes = new Map();
  16170. }
  16171. fromMaterial( material ) {
  16172. if ( material.isNodeMaterial ) return material;
  16173. let nodeMaterial = null;
  16174. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  16175. if ( nodeMaterialClass !== null ) {
  16176. nodeMaterial = new nodeMaterialClass();
  16177. for ( const key in material ) {
  16178. nodeMaterial[ key ] = material[ key ];
  16179. }
  16180. }
  16181. return nodeMaterial;
  16182. }
  16183. addToneMapping( toneMappingNode, toneMapping ) {
  16184. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  16185. }
  16186. getToneMappingFunction( toneMapping ) {
  16187. return this.toneMappingNodes.get( toneMapping ) || null;
  16188. }
  16189. getMaterialNodeClass( materialType ) {
  16190. return this.materialNodes.get( materialType ) || null;
  16191. }
  16192. addMaterial( materialNodeClass, materialClassType ) {
  16193. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  16194. }
  16195. getLightNodeClass( light ) {
  16196. return this.lightNodes.get( light ) || null;
  16197. }
  16198. addLight( lightNodeClass, lightClass ) {
  16199. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  16200. }
  16201. addType( nodeClass, type, library ) {
  16202. if ( library.has( type ) ) {
  16203. console.warn( `Redefinition of node ${ type }` );
  16204. return;
  16205. }
  16206. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16207. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  16208. library.set( type, nodeClass );
  16209. }
  16210. addClass( nodeClass, baseClass, library ) {
  16211. if ( library.has( baseClass ) ) {
  16212. console.warn( `Redefinition of node ${ baseClass.name }` );
  16213. return;
  16214. }
  16215. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16216. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  16217. library.set( baseClass, nodeClass );
  16218. }
  16219. }
  16220. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16221. class Lighting extends ChainMap {
  16222. constructor() {
  16223. super();
  16224. }
  16225. createNode( lights = [] ) {
  16226. return new LightsNode().setLights( lights );
  16227. }
  16228. getNode( scene, camera ) {
  16229. // ignore post-processing
  16230. if ( scene.isQuadMesh ) return _defaultLights;
  16231. // tiled lighting
  16232. const keys = [ scene, camera ];
  16233. let node = this.get( keys );
  16234. if ( node === undefined ) {
  16235. node = this.createNode();
  16236. this.set( keys, node );
  16237. }
  16238. return node;
  16239. }
  16240. }
  16241. const _scene = /*@__PURE__*/ new Scene();
  16242. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16243. const _screen = /*@__PURE__*/ new Vector4();
  16244. const _frustum = /*@__PURE__*/ new Frustum();
  16245. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16246. const _vector4 = /*@__PURE__*/ new Vector4();
  16247. class Renderer {
  16248. constructor( backend, parameters = {} ) {
  16249. this.isRenderer = true;
  16250. //
  16251. const {
  16252. logarithmicDepthBuffer = false,
  16253. alpha = true,
  16254. depth = true,
  16255. stencil = false,
  16256. antialias = false,
  16257. samples = 0,
  16258. getFallback = null
  16259. } = parameters;
  16260. // public
  16261. this.domElement = backend.getDomElement();
  16262. this.backend = backend;
  16263. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16264. this.autoClear = true;
  16265. this.autoClearColor = true;
  16266. this.autoClearDepth = true;
  16267. this.autoClearStencil = true;
  16268. this.alpha = alpha;
  16269. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16270. this.outputColorSpace = SRGBColorSpace;
  16271. this.toneMapping = NoToneMapping;
  16272. this.toneMappingExposure = 1.0;
  16273. this.sortObjects = true;
  16274. this.depth = depth;
  16275. this.stencil = stencil;
  16276. this.info = new Info();
  16277. this.nodes = {
  16278. modelViewMatrix: null,
  16279. modelNormalViewMatrix: null
  16280. };
  16281. this.library = new NodeLibrary();
  16282. this.lighting = new Lighting();
  16283. // internals
  16284. this._getFallback = getFallback;
  16285. this._pixelRatio = 1;
  16286. this._width = this.domElement.width;
  16287. this._height = this.domElement.height;
  16288. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16289. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16290. this._scissorTest = false;
  16291. this._attributes = null;
  16292. this._geometries = null;
  16293. this._nodes = null;
  16294. this._animation = null;
  16295. this._bindings = null;
  16296. this._objects = null;
  16297. this._pipelines = null;
  16298. this._bundles = null;
  16299. this._renderLists = null;
  16300. this._renderContexts = null;
  16301. this._textures = null;
  16302. this._background = null;
  16303. this._quad = new QuadMesh( new NodeMaterial() );
  16304. this._quad.material.type = 'Renderer_output';
  16305. this._currentRenderContext = null;
  16306. this._opaqueSort = null;
  16307. this._transparentSort = null;
  16308. this._frameBufferTarget = null;
  16309. const alphaClear = this.alpha === true ? 0 : 1;
  16310. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16311. this._clearDepth = 1;
  16312. this._clearStencil = 0;
  16313. this._renderTarget = null;
  16314. this._activeCubeFace = 0;
  16315. this._activeMipmapLevel = 0;
  16316. this._mrt = null;
  16317. this._renderObjectFunction = null;
  16318. this._currentRenderObjectFunction = null;
  16319. this._currentRenderBundle = null;
  16320. this._handleObjectFunction = this._renderObjectDirect;
  16321. this._isDeviceLost = false;
  16322. this.onDeviceLost = this._onDeviceLost;
  16323. this._initialized = false;
  16324. this._initPromise = null;
  16325. this._compilationPromises = null;
  16326. this.transparent = true;
  16327. this.opaque = true;
  16328. this.shadowMap = {
  16329. enabled: false,
  16330. type: PCFShadowMap
  16331. };
  16332. this.xr = {
  16333. enabled: false
  16334. };
  16335. this.debug = {
  16336. checkShaderErrors: true,
  16337. onShaderError: null,
  16338. getShaderAsync: async ( scene, camera, object ) => {
  16339. await this.compileAsync( scene, camera );
  16340. const renderList = this._renderLists.get( scene, camera );
  16341. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16342. const material = scene.overrideMaterial || object.material;
  16343. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16344. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16345. return { fragmentShader, vertexShader };
  16346. }
  16347. };
  16348. }
  16349. async init() {
  16350. if ( this._initialized ) {
  16351. throw new Error( 'Renderer: Backend has already been initialized.' );
  16352. }
  16353. if ( this._initPromise !== null ) {
  16354. return this._initPromise;
  16355. }
  16356. this._initPromise = new Promise( async ( resolve, reject ) => {
  16357. let backend = this.backend;
  16358. try {
  16359. await backend.init( this );
  16360. } catch ( error ) {
  16361. if ( this._getFallback !== null ) {
  16362. // try the fallback
  16363. try {
  16364. this.backend = backend = this._getFallback( error );
  16365. await backend.init( this );
  16366. } catch ( error ) {
  16367. reject( error );
  16368. return;
  16369. }
  16370. } else {
  16371. reject( error );
  16372. return;
  16373. }
  16374. }
  16375. this._nodes = new Nodes( this, backend );
  16376. this._animation = new Animation( this._nodes, this.info );
  16377. this._attributes = new Attributes( backend );
  16378. this._background = new Background( this, this._nodes );
  16379. this._geometries = new Geometries( this._attributes, this.info );
  16380. this._textures = new Textures( this, backend, this.info );
  16381. this._pipelines = new Pipelines( backend, this._nodes );
  16382. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16383. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16384. this._renderLists = new RenderLists( this.lighting );
  16385. this._bundles = new RenderBundles();
  16386. this._renderContexts = new RenderContexts();
  16387. //
  16388. this._animation.start();
  16389. this._initialized = true;
  16390. resolve();
  16391. } );
  16392. return this._initPromise;
  16393. }
  16394. get coordinateSystem() {
  16395. return this.backend.coordinateSystem;
  16396. }
  16397. async compileAsync( scene, camera, targetScene = null ) {
  16398. if ( this._isDeviceLost === true ) return;
  16399. if ( this._initialized === false ) await this.init();
  16400. // preserve render tree
  16401. const nodeFrame = this._nodes.nodeFrame;
  16402. const previousRenderId = nodeFrame.renderId;
  16403. const previousRenderContext = this._currentRenderContext;
  16404. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16405. const previousCompilationPromises = this._compilationPromises;
  16406. //
  16407. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16408. if ( targetScene === null ) targetScene = scene;
  16409. const renderTarget = this._renderTarget;
  16410. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16411. const activeMipmapLevel = this._activeMipmapLevel;
  16412. const compilationPromises = [];
  16413. this._currentRenderContext = renderContext;
  16414. this._currentRenderObjectFunction = this.renderObject;
  16415. this._handleObjectFunction = this._createObjectPipeline;
  16416. this._compilationPromises = compilationPromises;
  16417. nodeFrame.renderId ++;
  16418. //
  16419. nodeFrame.update();
  16420. //
  16421. renderContext.depth = this.depth;
  16422. renderContext.stencil = this.stencil;
  16423. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16424. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16425. //
  16426. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16427. //
  16428. const renderList = this._renderLists.get( scene, camera );
  16429. renderList.begin();
  16430. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16431. // include lights from target scene
  16432. if ( targetScene !== scene ) {
  16433. targetScene.traverseVisible( function ( object ) {
  16434. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16435. renderList.pushLight( object );
  16436. }
  16437. } );
  16438. }
  16439. renderList.finish();
  16440. //
  16441. if ( renderTarget !== null ) {
  16442. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16443. const renderTargetData = this._textures.get( renderTarget );
  16444. renderContext.textures = renderTargetData.textures;
  16445. renderContext.depthTexture = renderTargetData.depthTexture;
  16446. } else {
  16447. renderContext.textures = null;
  16448. renderContext.depthTexture = null;
  16449. }
  16450. //
  16451. this._nodes.updateScene( sceneRef );
  16452. //
  16453. this._background.update( sceneRef, renderList, renderContext );
  16454. // process render lists
  16455. const opaqueObjects = renderList.opaque;
  16456. const transparentObjects = renderList.transparent;
  16457. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16458. const lightsNode = renderList.lightsNode;
  16459. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16460. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16461. // restore render tree
  16462. nodeFrame.renderId = previousRenderId;
  16463. this._currentRenderContext = previousRenderContext;
  16464. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16465. this._compilationPromises = previousCompilationPromises;
  16466. this._handleObjectFunction = this._renderObjectDirect;
  16467. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16468. await Promise.all( compilationPromises );
  16469. }
  16470. async renderAsync( scene, camera ) {
  16471. if ( this._initialized === false ) await this.init();
  16472. const renderContext = this._renderScene( scene, camera );
  16473. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16474. }
  16475. async waitForGPU() {
  16476. await this.backend.waitForGPU();
  16477. }
  16478. setMRT( mrt ) {
  16479. this._mrt = mrt;
  16480. return this;
  16481. }
  16482. getMRT() {
  16483. return this._mrt;
  16484. }
  16485. _onDeviceLost( info ) {
  16486. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16487. if ( info.reason ) {
  16488. errorMessage += `\nReason: ${info.reason}`;
  16489. }
  16490. console.error( errorMessage );
  16491. this._isDeviceLost = true;
  16492. }
  16493. _renderBundle( bundle, sceneRef, lightsNode ) {
  16494. const { bundleGroup, camera, renderList } = bundle;
  16495. const renderContext = this._currentRenderContext;
  16496. //
  16497. const renderBundle = this._bundles.get( bundleGroup, camera );
  16498. const renderBundleData = this.backend.get( renderBundle );
  16499. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16500. //
  16501. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16502. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16503. renderBundleData.renderContexts.add( renderContext );
  16504. if ( renderBundleNeedsUpdate ) {
  16505. this.backend.beginBundle( renderContext );
  16506. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16507. renderBundleData.renderObjects = [];
  16508. }
  16509. this._currentRenderBundle = renderBundle;
  16510. const opaqueObjects = renderList.opaque;
  16511. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16512. this._currentRenderBundle = null;
  16513. //
  16514. this.backend.finishBundle( renderContext, renderBundle );
  16515. renderBundleData.version = bundleGroup.version;
  16516. } else {
  16517. const { renderObjects } = renderBundleData;
  16518. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16519. const renderObject = renderObjects[ i ];
  16520. if ( this._nodes.needsRefresh( renderObject ) ) {
  16521. this._nodes.updateBefore( renderObject );
  16522. this._nodes.updateForRender( renderObject );
  16523. this._bindings.updateForRender( renderObject );
  16524. this._nodes.updateAfter( renderObject );
  16525. }
  16526. }
  16527. }
  16528. this.backend.addBundle( renderContext, renderBundle );
  16529. }
  16530. render( scene, camera ) {
  16531. if ( this._initialized === false ) {
  16532. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16533. return this.renderAsync( scene, camera );
  16534. }
  16535. this._renderScene( scene, camera );
  16536. }
  16537. _getFrameBufferTarget() {
  16538. const { currentToneMapping, currentColorSpace } = this;
  16539. const useToneMapping = currentToneMapping !== NoToneMapping;
  16540. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16541. if ( useToneMapping === false && useColorSpace === false ) return null;
  16542. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16543. const { depth, stencil } = this;
  16544. let frameBufferTarget = this._frameBufferTarget;
  16545. if ( frameBufferTarget === null ) {
  16546. frameBufferTarget = new RenderTarget( width, height, {
  16547. depthBuffer: depth,
  16548. stencilBuffer: stencil,
  16549. type: HalfFloatType, // FloatType
  16550. format: RGBAFormat,
  16551. colorSpace: LinearSRGBColorSpace,
  16552. generateMipmaps: false,
  16553. minFilter: LinearFilter,
  16554. magFilter: LinearFilter,
  16555. samples: this.samples
  16556. } );
  16557. frameBufferTarget.isPostProcessingRenderTarget = true;
  16558. this._frameBufferTarget = frameBufferTarget;
  16559. }
  16560. frameBufferTarget.depthBuffer = depth;
  16561. frameBufferTarget.stencilBuffer = stencil;
  16562. frameBufferTarget.setSize( width, height );
  16563. frameBufferTarget.viewport.copy( this._viewport );
  16564. frameBufferTarget.scissor.copy( this._scissor );
  16565. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  16566. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  16567. frameBufferTarget.scissorTest = this._scissorTest;
  16568. return frameBufferTarget;
  16569. }
  16570. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  16571. if ( this._isDeviceLost === true ) return;
  16572. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  16573. // preserve render tree
  16574. const nodeFrame = this._nodes.nodeFrame;
  16575. const previousRenderId = nodeFrame.renderId;
  16576. const previousRenderContext = this._currentRenderContext;
  16577. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16578. //
  16579. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16580. const outputRenderTarget = this._renderTarget;
  16581. const activeCubeFace = this._activeCubeFace;
  16582. const activeMipmapLevel = this._activeMipmapLevel;
  16583. //
  16584. let renderTarget;
  16585. if ( frameBufferTarget !== null ) {
  16586. renderTarget = frameBufferTarget;
  16587. this.setRenderTarget( renderTarget );
  16588. } else {
  16589. renderTarget = outputRenderTarget;
  16590. }
  16591. //
  16592. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  16593. this._currentRenderContext = renderContext;
  16594. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  16595. //
  16596. this.info.calls ++;
  16597. this.info.render.calls ++;
  16598. this.info.render.frameCalls ++;
  16599. nodeFrame.renderId = this.info.calls;
  16600. //
  16601. const coordinateSystem = this.coordinateSystem;
  16602. if ( camera.coordinateSystem !== coordinateSystem ) {
  16603. camera.coordinateSystem = coordinateSystem;
  16604. camera.updateProjectionMatrix();
  16605. }
  16606. //
  16607. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16608. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16609. //
  16610. let viewport = this._viewport;
  16611. let scissor = this._scissor;
  16612. let pixelRatio = this._pixelRatio;
  16613. if ( renderTarget !== null ) {
  16614. viewport = renderTarget.viewport;
  16615. scissor = renderTarget.scissor;
  16616. pixelRatio = 1;
  16617. }
  16618. this.getDrawingBufferSize( _drawingBufferSize );
  16619. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  16620. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  16621. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  16622. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  16623. renderContext.viewportValue.width >>= activeMipmapLevel;
  16624. renderContext.viewportValue.height >>= activeMipmapLevel;
  16625. renderContext.viewportValue.minDepth = minDepth;
  16626. renderContext.viewportValue.maxDepth = maxDepth;
  16627. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  16628. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  16629. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  16630. renderContext.scissorValue.width >>= activeMipmapLevel;
  16631. renderContext.scissorValue.height >>= activeMipmapLevel;
  16632. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16633. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16634. //
  16635. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16636. //
  16637. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16638. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  16639. const renderList = this._renderLists.get( scene, camera );
  16640. renderList.begin();
  16641. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16642. renderList.finish();
  16643. if ( this.sortObjects === true ) {
  16644. renderList.sort( this._opaqueSort, this._transparentSort );
  16645. }
  16646. //
  16647. if ( renderTarget !== null ) {
  16648. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16649. const renderTargetData = this._textures.get( renderTarget );
  16650. renderContext.textures = renderTargetData.textures;
  16651. renderContext.depthTexture = renderTargetData.depthTexture;
  16652. renderContext.width = renderTargetData.width;
  16653. renderContext.height = renderTargetData.height;
  16654. renderContext.renderTarget = renderTarget;
  16655. renderContext.depth = renderTarget.depthBuffer;
  16656. renderContext.stencil = renderTarget.stencilBuffer;
  16657. } else {
  16658. renderContext.textures = null;
  16659. renderContext.depthTexture = null;
  16660. renderContext.width = this.domElement.width;
  16661. renderContext.height = this.domElement.height;
  16662. renderContext.depth = this.depth;
  16663. renderContext.stencil = this.stencil;
  16664. }
  16665. renderContext.width >>= activeMipmapLevel;
  16666. renderContext.height >>= activeMipmapLevel;
  16667. renderContext.activeCubeFace = activeCubeFace;
  16668. renderContext.activeMipmapLevel = activeMipmapLevel;
  16669. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  16670. //
  16671. this._nodes.updateScene( sceneRef );
  16672. //
  16673. this._background.update( sceneRef, renderList, renderContext );
  16674. //
  16675. this.backend.beginRender( renderContext );
  16676. // process render lists
  16677. const {
  16678. bundles,
  16679. lightsNode,
  16680. transparentDoublePass: transparentDoublePassObjects,
  16681. transparent: transparentObjects,
  16682. opaque: opaqueObjects
  16683. } = renderList;
  16684. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  16685. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16686. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16687. // finish render pass
  16688. this.backend.finishRender( renderContext );
  16689. // restore render tree
  16690. nodeFrame.renderId = previousRenderId;
  16691. this._currentRenderContext = previousRenderContext;
  16692. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16693. //
  16694. if ( frameBufferTarget !== null ) {
  16695. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  16696. const quad = this._quad;
  16697. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16698. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16699. quad.material.needsUpdate = true;
  16700. }
  16701. this._renderScene( quad, quad.camera, false );
  16702. }
  16703. //
  16704. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  16705. //
  16706. return renderContext;
  16707. }
  16708. getMaxAnisotropy() {
  16709. return this.backend.getMaxAnisotropy();
  16710. }
  16711. getActiveCubeFace() {
  16712. return this._activeCubeFace;
  16713. }
  16714. getActiveMipmapLevel() {
  16715. return this._activeMipmapLevel;
  16716. }
  16717. async setAnimationLoop( callback ) {
  16718. if ( this._initialized === false ) await this.init();
  16719. this._animation.setAnimationLoop( callback );
  16720. }
  16721. async getArrayBufferAsync( attribute ) {
  16722. return await this.backend.getArrayBufferAsync( attribute );
  16723. }
  16724. getContext() {
  16725. return this.backend.getContext();
  16726. }
  16727. getPixelRatio() {
  16728. return this._pixelRatio;
  16729. }
  16730. getDrawingBufferSize( target ) {
  16731. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  16732. }
  16733. getSize( target ) {
  16734. return target.set( this._width, this._height );
  16735. }
  16736. setPixelRatio( value = 1 ) {
  16737. if ( this._pixelRatio === value ) return;
  16738. this._pixelRatio = value;
  16739. this.setSize( this._width, this._height, false );
  16740. }
  16741. setDrawingBufferSize( width, height, pixelRatio ) {
  16742. this._width = width;
  16743. this._height = height;
  16744. this._pixelRatio = pixelRatio;
  16745. this.domElement.width = Math.floor( width * pixelRatio );
  16746. this.domElement.height = Math.floor( height * pixelRatio );
  16747. this.setViewport( 0, 0, width, height );
  16748. if ( this._initialized ) this.backend.updateSize();
  16749. }
  16750. setSize( width, height, updateStyle = true ) {
  16751. this._width = width;
  16752. this._height = height;
  16753. this.domElement.width = Math.floor( width * this._pixelRatio );
  16754. this.domElement.height = Math.floor( height * this._pixelRatio );
  16755. if ( updateStyle === true ) {
  16756. this.domElement.style.width = width + 'px';
  16757. this.domElement.style.height = height + 'px';
  16758. }
  16759. this.setViewport( 0, 0, width, height );
  16760. if ( this._initialized ) this.backend.updateSize();
  16761. }
  16762. setOpaqueSort( method ) {
  16763. this._opaqueSort = method;
  16764. }
  16765. setTransparentSort( method ) {
  16766. this._transparentSort = method;
  16767. }
  16768. getScissor( target ) {
  16769. const scissor = this._scissor;
  16770. target.x = scissor.x;
  16771. target.y = scissor.y;
  16772. target.width = scissor.width;
  16773. target.height = scissor.height;
  16774. return target;
  16775. }
  16776. setScissor( x, y, width, height ) {
  16777. const scissor = this._scissor;
  16778. if ( x.isVector4 ) {
  16779. scissor.copy( x );
  16780. } else {
  16781. scissor.set( x, y, width, height );
  16782. }
  16783. }
  16784. getScissorTest() {
  16785. return this._scissorTest;
  16786. }
  16787. setScissorTest( boolean ) {
  16788. this._scissorTest = boolean;
  16789. this.backend.setScissorTest( boolean );
  16790. }
  16791. getViewport( target ) {
  16792. return target.copy( this._viewport );
  16793. }
  16794. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  16795. const viewport = this._viewport;
  16796. if ( x.isVector4 ) {
  16797. viewport.copy( x );
  16798. } else {
  16799. viewport.set( x, y, width, height );
  16800. }
  16801. viewport.minDepth = minDepth;
  16802. viewport.maxDepth = maxDepth;
  16803. }
  16804. getClearColor( target ) {
  16805. return target.copy( this._clearColor );
  16806. }
  16807. setClearColor( color, alpha = 1 ) {
  16808. this._clearColor.set( color );
  16809. this._clearColor.a = alpha;
  16810. }
  16811. getClearAlpha() {
  16812. return this._clearColor.a;
  16813. }
  16814. setClearAlpha( alpha ) {
  16815. this._clearColor.a = alpha;
  16816. }
  16817. getClearDepth() {
  16818. return this._clearDepth;
  16819. }
  16820. setClearDepth( depth ) {
  16821. this._clearDepth = depth;
  16822. }
  16823. getClearStencil() {
  16824. return this._clearStencil;
  16825. }
  16826. setClearStencil( stencil ) {
  16827. this._clearStencil = stencil;
  16828. }
  16829. isOccluded( object ) {
  16830. const renderContext = this._currentRenderContext;
  16831. return renderContext && this.backend.isOccluded( renderContext, object );
  16832. }
  16833. clear( color = true, depth = true, stencil = true ) {
  16834. if ( this._initialized === false ) {
  16835. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  16836. return this.clearAsync( color, depth, stencil );
  16837. }
  16838. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  16839. let renderTargetData = null;
  16840. if ( renderTarget !== null ) {
  16841. this._textures.updateRenderTarget( renderTarget );
  16842. renderTargetData = this._textures.get( renderTarget );
  16843. }
  16844. this.backend.clear( color, depth, stencil, renderTargetData );
  16845. if ( renderTarget !== null && this._renderTarget === null ) {
  16846. // If a color space transform or tone mapping is required,
  16847. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  16848. const quad = this._quad;
  16849. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16850. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16851. quad.material.needsUpdate = true;
  16852. }
  16853. this._renderScene( quad, quad.camera, false );
  16854. }
  16855. }
  16856. clearColor() {
  16857. return this.clear( true, false, false );
  16858. }
  16859. clearDepth() {
  16860. return this.clear( false, true, false );
  16861. }
  16862. clearStencil() {
  16863. return this.clear( false, false, true );
  16864. }
  16865. async clearAsync( color = true, depth = true, stencil = true ) {
  16866. if ( this._initialized === false ) await this.init();
  16867. this.clear( color, depth, stencil );
  16868. }
  16869. clearColorAsync() {
  16870. return this.clearAsync( true, false, false );
  16871. }
  16872. clearDepthAsync() {
  16873. return this.clearAsync( false, true, false );
  16874. }
  16875. clearStencilAsync() {
  16876. return this.clearAsync( false, false, true );
  16877. }
  16878. get currentToneMapping() {
  16879. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  16880. }
  16881. get currentColorSpace() {
  16882. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  16883. }
  16884. dispose() {
  16885. this.info.dispose();
  16886. this.backend.dispose();
  16887. this._animation.dispose();
  16888. this._objects.dispose();
  16889. this._pipelines.dispose();
  16890. this._nodes.dispose();
  16891. this._bindings.dispose();
  16892. this._renderLists.dispose();
  16893. this._renderContexts.dispose();
  16894. this._textures.dispose();
  16895. this.setRenderTarget( null );
  16896. this.setAnimationLoop( null );
  16897. }
  16898. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16899. this._renderTarget = renderTarget;
  16900. this._activeCubeFace = activeCubeFace;
  16901. this._activeMipmapLevel = activeMipmapLevel;
  16902. }
  16903. getRenderTarget() {
  16904. return this._renderTarget;
  16905. }
  16906. setRenderObjectFunction( renderObjectFunction ) {
  16907. this._renderObjectFunction = renderObjectFunction;
  16908. }
  16909. getRenderObjectFunction() {
  16910. return this._renderObjectFunction;
  16911. }
  16912. compute( computeNodes ) {
  16913. if ( this.isDeviceLost === true ) return;
  16914. if ( this._initialized === false ) {
  16915. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  16916. return this.computeAsync( computeNodes );
  16917. }
  16918. //
  16919. const nodeFrame = this._nodes.nodeFrame;
  16920. const previousRenderId = nodeFrame.renderId;
  16921. //
  16922. this.info.calls ++;
  16923. this.info.compute.calls ++;
  16924. this.info.compute.frameCalls ++;
  16925. nodeFrame.renderId = this.info.calls;
  16926. //
  16927. const backend = this.backend;
  16928. const pipelines = this._pipelines;
  16929. const bindings = this._bindings;
  16930. const nodes = this._nodes;
  16931. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  16932. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  16933. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  16934. }
  16935. backend.beginCompute( computeNodes );
  16936. for ( const computeNode of computeList ) {
  16937. // onInit
  16938. if ( pipelines.has( computeNode ) === false ) {
  16939. const dispose = () => {
  16940. computeNode.removeEventListener( 'dispose', dispose );
  16941. pipelines.delete( computeNode );
  16942. bindings.delete( computeNode );
  16943. nodes.delete( computeNode );
  16944. };
  16945. computeNode.addEventListener( 'dispose', dispose );
  16946. //
  16947. const onInitFn = computeNode.onInitFunction;
  16948. if ( onInitFn !== null ) {
  16949. onInitFn.call( computeNode, { renderer: this } );
  16950. }
  16951. }
  16952. nodes.updateForCompute( computeNode );
  16953. bindings.updateForCompute( computeNode );
  16954. const computeBindings = bindings.getForCompute( computeNode );
  16955. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  16956. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  16957. }
  16958. backend.finishCompute( computeNodes );
  16959. //
  16960. nodeFrame.renderId = previousRenderId;
  16961. }
  16962. async computeAsync( computeNodes ) {
  16963. if ( this._initialized === false ) await this.init();
  16964. this.compute( computeNodes );
  16965. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  16966. }
  16967. async hasFeatureAsync( name ) {
  16968. if ( this._initialized === false ) await this.init();
  16969. return this.backend.hasFeature( name );
  16970. }
  16971. hasFeature( name ) {
  16972. if ( this._initialized === false ) {
  16973. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  16974. return false;
  16975. }
  16976. return this.backend.hasFeature( name );
  16977. }
  16978. hasInitialized() {
  16979. return this._initialized;
  16980. }
  16981. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  16982. if ( rectangle !== null ) {
  16983. if ( rectangle.isVector2 ) {
  16984. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  16985. } else if ( rectangle.isVector4 ) {
  16986. rectangle = _vector4.copy( rectangle ).floor();
  16987. } else {
  16988. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  16989. return;
  16990. }
  16991. } else {
  16992. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  16993. }
  16994. //
  16995. let renderContext = this._currentRenderContext;
  16996. let renderTarget;
  16997. if ( renderContext !== null ) {
  16998. renderTarget = renderContext.renderTarget;
  16999. } else {
  17000. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17001. if ( renderTarget !== null ) {
  17002. this._textures.updateRenderTarget( renderTarget );
  17003. renderContext = this._textures.get( renderTarget );
  17004. }
  17005. }
  17006. //
  17007. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  17008. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  17009. }
  17010. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  17011. this._textures.updateTexture( srcTexture );
  17012. this._textures.updateTexture( dstTexture );
  17013. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  17014. }
  17015. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  17016. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  17017. }
  17018. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  17019. if ( object.visible === false ) return;
  17020. const visible = object.layers.test( camera.layers );
  17021. if ( visible ) {
  17022. if ( object.isGroup ) {
  17023. groupOrder = object.renderOrder;
  17024. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  17025. } else if ( object.isLOD ) {
  17026. if ( object.autoUpdate === true ) object.update( camera );
  17027. } else if ( object.isLight ) {
  17028. renderList.pushLight( object );
  17029. } else if ( object.isSprite ) {
  17030. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17031. if ( this.sortObjects === true ) {
  17032. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  17033. }
  17034. const { geometry, material } = object;
  17035. if ( material.visible ) {
  17036. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17037. }
  17038. }
  17039. } else if ( object.isLineLoop ) {
  17040. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  17041. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17042. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17043. const { geometry, material } = object;
  17044. if ( this.sortObjects === true ) {
  17045. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17046. _vector4
  17047. .copy( geometry.boundingSphere.center )
  17048. .applyMatrix4( object.matrixWorld )
  17049. .applyMatrix4( _projScreenMatrix );
  17050. }
  17051. if ( Array.isArray( material ) ) {
  17052. const groups = geometry.groups;
  17053. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17054. const group = groups[ i ];
  17055. const groupMaterial = material[ group.materialIndex ];
  17056. if ( groupMaterial && groupMaterial.visible ) {
  17057. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  17058. }
  17059. }
  17060. } else if ( material.visible ) {
  17061. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17062. }
  17063. }
  17064. }
  17065. }
  17066. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  17067. const baseRenderList = renderList;
  17068. // replace render list
  17069. renderList = this._renderLists.get( object, camera );
  17070. renderList.begin();
  17071. baseRenderList.pushBundle( {
  17072. bundleGroup: object,
  17073. camera,
  17074. renderList,
  17075. } );
  17076. renderList.finish();
  17077. }
  17078. const children = object.children;
  17079. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17080. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  17081. }
  17082. }
  17083. _renderBundles( bundles, sceneRef, lightsNode ) {
  17084. for ( const bundle of bundles ) {
  17085. this._renderBundle( bundle, sceneRef, lightsNode );
  17086. }
  17087. }
  17088. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  17089. if ( doublePassList.length > 0 ) {
  17090. // render back side
  17091. for ( const { material } of doublePassList ) {
  17092. material.side = BackSide;
  17093. }
  17094. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  17095. // render front side
  17096. for ( const { material } of doublePassList ) {
  17097. material.side = FrontSide;
  17098. }
  17099. this._renderObjects( renderList, camera, scene, lightsNode );
  17100. // restore
  17101. for ( const { material } of doublePassList ) {
  17102. material.side = DoubleSide;
  17103. }
  17104. } else {
  17105. this._renderObjects( renderList, camera, scene, lightsNode );
  17106. }
  17107. }
  17108. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  17109. // process renderable objects
  17110. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  17111. const renderItem = renderList[ i ];
  17112. // @TODO: Add support for multiple materials per object. This will require to extract
  17113. // the material from the renderItem object and pass it with its group data to renderObject().
  17114. const { object, geometry, material, group, clippingContext } = renderItem;
  17115. if ( camera.isArrayCamera ) {
  17116. const cameras = camera.cameras;
  17117. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  17118. const camera2 = cameras[ j ];
  17119. if ( object.layers.test( camera2.layers ) ) {
  17120. const vp = camera2.viewport;
  17121. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  17122. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  17123. const viewportValue = this._currentRenderContext.viewportValue;
  17124. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  17125. viewportValue.minDepth = minDepth;
  17126. viewportValue.maxDepth = maxDepth;
  17127. this.backend.updateViewport( this._currentRenderContext );
  17128. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  17129. }
  17130. }
  17131. } else {
  17132. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  17133. }
  17134. }
  17135. }
  17136. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  17137. let overridePositionNode;
  17138. let overrideFragmentNode;
  17139. let overrideDepthNode;
  17140. //
  17141. object.onBeforeRender( this, scene, camera, geometry, material, group );
  17142. //
  17143. if ( scene.overrideMaterial !== null ) {
  17144. const overrideMaterial = scene.overrideMaterial;
  17145. if ( material.positionNode && material.positionNode.isNode ) {
  17146. overridePositionNode = overrideMaterial.positionNode;
  17147. overrideMaterial.positionNode = material.positionNode;
  17148. }
  17149. if ( overrideMaterial.isShadowNodeMaterial ) {
  17150. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  17151. if ( material.depthNode && material.depthNode.isNode ) {
  17152. overrideDepthNode = overrideMaterial.depthNode;
  17153. overrideMaterial.depthNode = material.depthNode;
  17154. }
  17155. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  17156. overrideFragmentNode = overrideMaterial.fragmentNode;
  17157. overrideMaterial.fragmentNode = material.castShadowNode;
  17158. }
  17159. }
  17160. material = overrideMaterial;
  17161. }
  17162. //
  17163. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17164. material.side = BackSide;
  17165. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  17166. material.side = FrontSide;
  17167. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  17168. material.side = DoubleSide;
  17169. } else {
  17170. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  17171. }
  17172. //
  17173. if ( overridePositionNode !== undefined ) {
  17174. scene.overrideMaterial.positionNode = overridePositionNode;
  17175. }
  17176. if ( overrideDepthNode !== undefined ) {
  17177. scene.overrideMaterial.depthNode = overrideDepthNode;
  17178. }
  17179. if ( overrideFragmentNode !== undefined ) {
  17180. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  17181. }
  17182. //
  17183. object.onAfterRender( this, scene, camera, geometry, material, group );
  17184. }
  17185. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  17186. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17187. renderObject.drawRange = object.geometry.drawRange;
  17188. renderObject.group = group;
  17189. //
  17190. const needsRefresh = this._nodes.needsRefresh( renderObject );
  17191. if ( needsRefresh ) {
  17192. this._nodes.updateBefore( renderObject );
  17193. this._geometries.updateForRender( renderObject );
  17194. this._nodes.updateForRender( renderObject );
  17195. this._bindings.updateForRender( renderObject );
  17196. }
  17197. this._pipelines.updateForRender( renderObject );
  17198. //
  17199. if ( this._currentRenderBundle !== null ) {
  17200. const renderBundleData = this.backend.get( this._currentRenderBundle );
  17201. renderBundleData.renderObjects.push( renderObject );
  17202. renderObject.bundle = this._currentRenderBundle.scene;
  17203. }
  17204. this.backend.draw( renderObject, this.info );
  17205. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  17206. }
  17207. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  17208. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17209. //
  17210. this._nodes.updateBefore( renderObject );
  17211. this._geometries.updateForRender( renderObject );
  17212. this._nodes.updateForRender( renderObject );
  17213. this._bindings.updateForRender( renderObject );
  17214. this._pipelines.getForRender( renderObject, this._compilationPromises );
  17215. this._nodes.updateAfter( renderObject );
  17216. }
  17217. get compile() {
  17218. return this.compileAsync;
  17219. }
  17220. }
  17221. class Binding {
  17222. constructor( name = '' ) {
  17223. this.name = name;
  17224. this.visibility = 0;
  17225. }
  17226. setVisibility( visibility ) {
  17227. this.visibility |= visibility;
  17228. }
  17229. clone() {
  17230. return Object.assign( new this.constructor(), this );
  17231. }
  17232. }
  17233. function getFloatLength( floatLength ) {
  17234. // ensure chunk size alignment (STD140 layout)
  17235. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17236. }
  17237. class Buffer extends Binding {
  17238. constructor( name, buffer = null ) {
  17239. super( name );
  17240. this.isBuffer = true;
  17241. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17242. this._buffer = buffer;
  17243. }
  17244. get byteLength() {
  17245. return getFloatLength( this._buffer.byteLength );
  17246. }
  17247. get buffer() {
  17248. return this._buffer;
  17249. }
  17250. update() {
  17251. return true;
  17252. }
  17253. }
  17254. class UniformBuffer extends Buffer {
  17255. constructor( name, buffer = null ) {
  17256. super( name, buffer );
  17257. this.isUniformBuffer = true;
  17258. }
  17259. }
  17260. let _id$4 = 0;
  17261. class NodeUniformBuffer extends UniformBuffer {
  17262. constructor( nodeUniform, groupNode ) {
  17263. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17264. this.nodeUniform = nodeUniform;
  17265. this.groupNode = groupNode;
  17266. }
  17267. get buffer() {
  17268. return this.nodeUniform.value;
  17269. }
  17270. }
  17271. class UniformsGroup extends UniformBuffer {
  17272. constructor( name ) {
  17273. super( name );
  17274. this.isUniformsGroup = true;
  17275. this._values = null;
  17276. // the order of uniforms in this array must match the order of uniforms in the shader
  17277. this.uniforms = [];
  17278. }
  17279. addUniform( uniform ) {
  17280. this.uniforms.push( uniform );
  17281. return this;
  17282. }
  17283. removeUniform( uniform ) {
  17284. const index = this.uniforms.indexOf( uniform );
  17285. if ( index !== - 1 ) {
  17286. this.uniforms.splice( index, 1 );
  17287. }
  17288. return this;
  17289. }
  17290. get values() {
  17291. if ( this._values === null ) {
  17292. this._values = Array.from( this.buffer );
  17293. }
  17294. return this._values;
  17295. }
  17296. get buffer() {
  17297. let buffer = this._buffer;
  17298. if ( buffer === null ) {
  17299. const byteLength = this.byteLength;
  17300. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17301. this._buffer = buffer;
  17302. }
  17303. return buffer;
  17304. }
  17305. get byteLength() {
  17306. let offset = 0; // global buffer offset in bytes
  17307. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17308. const uniform = this.uniforms[ i ];
  17309. const { boundary, itemSize } = uniform;
  17310. // offset within a single chunk in bytes
  17311. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17312. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17313. // conformance tests
  17314. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17315. // check for chunk overflow
  17316. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17317. } else if ( chunkOffset % boundary !== 0 ) {
  17318. // check for correct alignment
  17319. offset += ( chunkOffset % boundary );
  17320. }
  17321. uniform.offset = ( offset / this.bytesPerElement );
  17322. offset += ( itemSize * this.bytesPerElement );
  17323. }
  17324. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17325. }
  17326. update() {
  17327. let updated = false;
  17328. for ( const uniform of this.uniforms ) {
  17329. if ( this.updateByType( uniform ) === true ) {
  17330. updated = true;
  17331. }
  17332. }
  17333. return updated;
  17334. }
  17335. updateByType( uniform ) {
  17336. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17337. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17338. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17339. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17340. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17341. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17342. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17343. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17344. }
  17345. updateNumber( uniform ) {
  17346. let updated = false;
  17347. const a = this.values;
  17348. const v = uniform.getValue();
  17349. const offset = uniform.offset;
  17350. if ( a[ offset ] !== v ) {
  17351. const b = this.buffer;
  17352. b[ offset ] = a[ offset ] = v;
  17353. updated = true;
  17354. }
  17355. return updated;
  17356. }
  17357. updateVector2( uniform ) {
  17358. let updated = false;
  17359. const a = this.values;
  17360. const v = uniform.getValue();
  17361. const offset = uniform.offset;
  17362. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17363. const b = this.buffer;
  17364. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17365. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17366. updated = true;
  17367. }
  17368. return updated;
  17369. }
  17370. updateVector3( uniform ) {
  17371. let updated = false;
  17372. const a = this.values;
  17373. const v = uniform.getValue();
  17374. const offset = uniform.offset;
  17375. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17376. const b = this.buffer;
  17377. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17378. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17379. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17380. updated = true;
  17381. }
  17382. return updated;
  17383. }
  17384. updateVector4( uniform ) {
  17385. let updated = false;
  17386. const a = this.values;
  17387. const v = uniform.getValue();
  17388. const offset = uniform.offset;
  17389. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17390. const b = this.buffer;
  17391. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17392. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17393. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17394. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17395. updated = true;
  17396. }
  17397. return updated;
  17398. }
  17399. updateColor( uniform ) {
  17400. let updated = false;
  17401. const a = this.values;
  17402. const c = uniform.getValue();
  17403. const offset = uniform.offset;
  17404. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17405. const b = this.buffer;
  17406. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17407. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17408. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17409. updated = true;
  17410. }
  17411. return updated;
  17412. }
  17413. updateMatrix3( uniform ) {
  17414. let updated = false;
  17415. const a = this.values;
  17416. const e = uniform.getValue().elements;
  17417. const offset = uniform.offset;
  17418. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17419. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17420. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17421. const b = this.buffer;
  17422. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17423. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17424. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17425. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17426. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17427. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17428. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17429. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17430. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17431. updated = true;
  17432. }
  17433. return updated;
  17434. }
  17435. updateMatrix4( uniform ) {
  17436. let updated = false;
  17437. const a = this.values;
  17438. const e = uniform.getValue().elements;
  17439. const offset = uniform.offset;
  17440. if ( arraysEqual( a, e, offset ) === false ) {
  17441. const b = this.buffer;
  17442. b.set( e, offset );
  17443. setArray( a, e, offset );
  17444. updated = true;
  17445. }
  17446. return updated;
  17447. }
  17448. }
  17449. function setArray( a, b, offset ) {
  17450. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17451. a[ offset + i ] = b[ i ];
  17452. }
  17453. }
  17454. function arraysEqual( a, b, offset ) {
  17455. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17456. if ( a[ offset + i ] !== b[ i ] ) return false;
  17457. }
  17458. return true;
  17459. }
  17460. let _id$3 = 0;
  17461. class NodeUniformsGroup extends UniformsGroup {
  17462. constructor( name, groupNode ) {
  17463. super( name );
  17464. this.id = _id$3 ++;
  17465. this.groupNode = groupNode;
  17466. this.isNodeUniformsGroup = true;
  17467. }
  17468. getNodes() {
  17469. const nodes = [];
  17470. for ( const uniform of this.uniforms ) {
  17471. const node = uniform.nodeUniform.node;
  17472. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17473. nodes.push( node );
  17474. }
  17475. return nodes;
  17476. }
  17477. }
  17478. let _id$2 = 0;
  17479. class SampledTexture extends Binding {
  17480. constructor( name, texture ) {
  17481. super( name );
  17482. this.id = _id$2 ++;
  17483. this.texture = texture;
  17484. this.version = texture ? texture.version : 0;
  17485. this.store = false;
  17486. this.generation = null;
  17487. this.isSampledTexture = true;
  17488. }
  17489. needsBindingsUpdate( generation ) {
  17490. const { texture } = this;
  17491. if ( generation !== this.generation ) {
  17492. this.generation = generation;
  17493. return true;
  17494. }
  17495. return texture.isVideoTexture;
  17496. }
  17497. update() {
  17498. const { texture, version } = this;
  17499. if ( version !== texture.version ) {
  17500. this.version = texture.version;
  17501. return true;
  17502. }
  17503. return false;
  17504. }
  17505. }
  17506. class NodeSampledTexture extends SampledTexture {
  17507. constructor( name, textureNode, groupNode, access = null ) {
  17508. super( name, textureNode ? textureNode.value : null );
  17509. this.textureNode = textureNode;
  17510. this.groupNode = groupNode;
  17511. this.access = access;
  17512. }
  17513. needsBindingsUpdate( generation ) {
  17514. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17515. }
  17516. update() {
  17517. const { textureNode } = this;
  17518. if ( this.texture !== textureNode.value ) {
  17519. this.texture = textureNode.value;
  17520. return true;
  17521. }
  17522. return super.update();
  17523. }
  17524. }
  17525. class NodeSampledCubeTexture extends NodeSampledTexture {
  17526. constructor( name, textureNode, groupNode, access ) {
  17527. super( name, textureNode, groupNode, access );
  17528. this.isSampledCubeTexture = true;
  17529. }
  17530. }
  17531. class NodeSampledTexture3D extends NodeSampledTexture {
  17532. constructor( name, textureNode, groupNode, access ) {
  17533. super( name, textureNode, groupNode, access );
  17534. this.isSampledTexture3D = true;
  17535. }
  17536. }
  17537. const glslMethods = {
  17538. atan2: 'atan',
  17539. textureDimensions: 'textureSize',
  17540. equals: 'equal'
  17541. };
  17542. const precisionLib = {
  17543. low: 'lowp',
  17544. medium: 'mediump',
  17545. high: 'highp'
  17546. };
  17547. const supports$1 = {
  17548. swizzleAssign: true,
  17549. storageBuffer: false
  17550. };
  17551. const defaultPrecisions = `
  17552. precision highp float;
  17553. precision highp int;
  17554. precision highp sampler2D;
  17555. precision highp sampler3D;
  17556. precision highp samplerCube;
  17557. precision highp sampler2DArray;
  17558. precision highp usampler2D;
  17559. precision highp usampler3D;
  17560. precision highp usamplerCube;
  17561. precision highp usampler2DArray;
  17562. precision highp isampler2D;
  17563. precision highp isampler3D;
  17564. precision highp isamplerCube;
  17565. precision highp isampler2DArray;
  17566. precision lowp sampler2DShadow;
  17567. `;
  17568. class GLSLNodeBuilder extends NodeBuilder {
  17569. constructor( object, renderer ) {
  17570. super( object, renderer, new GLSLNodeParser() );
  17571. this.uniformGroups = {};
  17572. this.transforms = [];
  17573. this.extensions = {};
  17574. this.builtins = { vertex: [], fragment: [], compute: [] };
  17575. this.useComparisonMethod = true;
  17576. }
  17577. needsColorSpaceToLinearSRGB( texture ) {
  17578. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  17579. }
  17580. getMethod( method ) {
  17581. return glslMethods[ method ] || method;
  17582. }
  17583. getOutputStructName() {
  17584. return '';
  17585. }
  17586. buildFunctionCode( shaderNode ) {
  17587. const layout = shaderNode.layout;
  17588. const flowData = this.flowShaderNode( shaderNode );
  17589. const parameters = [];
  17590. for ( const input of layout.inputs ) {
  17591. parameters.push( this.getType( input.type ) + ' ' + input.name );
  17592. }
  17593. //
  17594. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  17595. ${ flowData.vars }
  17596. ${ flowData.code }
  17597. return ${ flowData.result };
  17598. }`;
  17599. //
  17600. return code;
  17601. }
  17602. setupPBO( storageBufferNode ) {
  17603. const attribute = storageBufferNode.value;
  17604. if ( attribute.pbo === undefined ) {
  17605. const originalArray = attribute.array;
  17606. const numElements = attribute.count * attribute.itemSize;
  17607. const { itemSize } = attribute;
  17608. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  17609. let format = isInteger ? RedIntegerFormat : RedFormat;
  17610. if ( itemSize === 2 ) {
  17611. format = isInteger ? RGIntegerFormat : RGFormat;
  17612. } else if ( itemSize === 3 ) {
  17613. format = isInteger ? RGBIntegerFormat : RGBFormat;
  17614. } else if ( itemSize === 4 ) {
  17615. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  17616. }
  17617. const typeMap = {
  17618. Float32Array: FloatType,
  17619. Uint8Array: UnsignedByteType,
  17620. Uint16Array: UnsignedShortType,
  17621. Uint32Array: UnsignedIntType,
  17622. Int8Array: ByteType,
  17623. Int16Array: ShortType,
  17624. Int32Array: IntType,
  17625. Uint8ClampedArray: UnsignedByteType,
  17626. };
  17627. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  17628. let height = Math.ceil( ( numElements / itemSize ) / width );
  17629. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  17630. const newSize = width * height * itemSize;
  17631. const newArray = new originalArray.constructor( newSize );
  17632. newArray.set( originalArray, 0 );
  17633. attribute.array = newArray;
  17634. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  17635. pboTexture.needsUpdate = true;
  17636. pboTexture.isPBOTexture = true;
  17637. const pbo = new TextureNode( pboTexture, null, null );
  17638. pbo.setPrecision( 'high' );
  17639. attribute.pboNode = pbo;
  17640. attribute.pbo = pbo.value;
  17641. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17642. }
  17643. }
  17644. getPropertyName( node, shaderStage = this.shaderStage ) {
  17645. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  17646. return shaderStage.charAt( 0 ) + '_' + node.name;
  17647. }
  17648. return super.getPropertyName( node, shaderStage );
  17649. }
  17650. generatePBO( storageArrayElementNode ) {
  17651. const { node, indexNode } = storageArrayElementNode;
  17652. const attribute = node.value;
  17653. if ( this.renderer.backend.has( attribute ) ) {
  17654. const attributeData = this.renderer.backend.get( attribute );
  17655. attributeData.pbo = attribute.pbo;
  17656. }
  17657. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17658. const textureName = this.getPropertyName( nodeUniform );
  17659. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  17660. const indexSnippet = indexNode.build( this, 'uint' );
  17661. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  17662. let propertyName = elementNodeData.propertyName;
  17663. if ( propertyName === undefined ) {
  17664. // property element
  17665. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  17666. propertyName = this.getPropertyName( nodeVar );
  17667. // property size
  17668. const bufferNodeData = this.getDataFromNode( node );
  17669. let propertySizeName = bufferNodeData.propertySizeName;
  17670. if ( propertySizeName === undefined ) {
  17671. propertySizeName = propertyName + 'Size';
  17672. this.getVarFromNode( node, propertySizeName, 'uint' );
  17673. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  17674. bufferNodeData.propertySizeName = propertySizeName;
  17675. }
  17676. //
  17677. const { itemSize } = attribute;
  17678. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  17679. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  17680. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  17681. //
  17682. let prefix = 'vec4';
  17683. if ( attribute.pbo.type === UnsignedIntType ) {
  17684. prefix = 'uvec4';
  17685. } else if ( attribute.pbo.type === IntType ) {
  17686. prefix = 'ivec4';
  17687. }
  17688. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  17689. elementNodeData.propertyName = propertyName;
  17690. }
  17691. return propertyName;
  17692. }
  17693. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  17694. if ( depthSnippet ) {
  17695. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  17696. } else {
  17697. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  17698. }
  17699. }
  17700. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  17701. if ( texture.isDepthTexture ) {
  17702. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  17703. } else {
  17704. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  17705. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  17706. }
  17707. }
  17708. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  17709. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  17710. }
  17711. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  17712. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  17713. }
  17714. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  17715. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  17716. }
  17717. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  17718. if ( shaderStage === 'fragment' ) {
  17719. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  17720. } else {
  17721. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  17722. }
  17723. }
  17724. getVars( shaderStage ) {
  17725. const snippets = [];
  17726. const vars = this.vars[ shaderStage ];
  17727. if ( vars !== undefined ) {
  17728. for ( const variable of vars ) {
  17729. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  17730. }
  17731. }
  17732. return snippets.join( '\n\t' );
  17733. }
  17734. getUniforms( shaderStage ) {
  17735. const uniforms = this.uniforms[ shaderStage ];
  17736. const bindingSnippets = [];
  17737. const uniformGroups = {};
  17738. for ( const uniform of uniforms ) {
  17739. let snippet = null;
  17740. let group = false;
  17741. if ( uniform.type === 'texture' ) {
  17742. const texture = uniform.node.value;
  17743. let typePrefix = '';
  17744. if ( texture.isDataTexture === true ) {
  17745. if ( texture.type === UnsignedIntType ) {
  17746. typePrefix = 'u';
  17747. } else if ( texture.type === IntType ) {
  17748. typePrefix = 'i';
  17749. }
  17750. }
  17751. if ( texture.compareFunction ) {
  17752. snippet = `sampler2DShadow ${ uniform.name };`;
  17753. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  17754. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  17755. } else {
  17756. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  17757. }
  17758. } else if ( uniform.type === 'cubeTexture' ) {
  17759. snippet = `samplerCube ${ uniform.name };`;
  17760. } else if ( uniform.type === 'texture3D' ) {
  17761. snippet = `sampler3D ${ uniform.name };`;
  17762. } else if ( uniform.type === 'buffer' ) {
  17763. const bufferNode = uniform.node;
  17764. const bufferType = this.getType( bufferNode.bufferType );
  17765. const bufferCount = bufferNode.bufferCount;
  17766. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  17767. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  17768. } else {
  17769. const vectorType = this.getVectorType( uniform.type );
  17770. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  17771. group = true;
  17772. }
  17773. const precision = uniform.node.precision;
  17774. if ( precision !== null ) {
  17775. snippet = precisionLib[ precision ] + ' ' + snippet;
  17776. }
  17777. if ( group ) {
  17778. snippet = '\t' + snippet;
  17779. const groupName = uniform.groupNode.name;
  17780. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  17781. groupSnippets.push( snippet );
  17782. } else {
  17783. snippet = 'uniform ' + snippet;
  17784. bindingSnippets.push( snippet );
  17785. }
  17786. }
  17787. let output = '';
  17788. for ( const name in uniformGroups ) {
  17789. const groupSnippets = uniformGroups[ name ];
  17790. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  17791. }
  17792. output += bindingSnippets.join( '\n' );
  17793. return output;
  17794. }
  17795. getTypeFromAttribute( attribute ) {
  17796. let nodeType = super.getTypeFromAttribute( attribute );
  17797. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  17798. let dataAttribute = attribute;
  17799. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  17800. const array = dataAttribute.array;
  17801. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  17802. nodeType = nodeType.slice( 1 );
  17803. }
  17804. }
  17805. return nodeType;
  17806. }
  17807. getAttributes( shaderStage ) {
  17808. let snippet = '';
  17809. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17810. const attributes = this.getAttributesArray();
  17811. let location = 0;
  17812. for ( const attribute of attributes ) {
  17813. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  17814. }
  17815. }
  17816. return snippet;
  17817. }
  17818. getStructMembers( struct ) {
  17819. const snippets = [];
  17820. const members = struct.getMemberTypes();
  17821. for ( let i = 0; i < members.length; i ++ ) {
  17822. const member = members[ i ];
  17823. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  17824. }
  17825. return snippets.join( '\n' );
  17826. }
  17827. getStructs( shaderStage ) {
  17828. const snippets = [];
  17829. const structs = this.structs[ shaderStage ];
  17830. if ( structs.length === 0 ) {
  17831. return 'layout( location = 0 ) out vec4 fragColor;\n';
  17832. }
  17833. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  17834. const struct = structs[ index ];
  17835. let snippet = '\n';
  17836. snippet += this.getStructMembers( struct );
  17837. snippet += '\n';
  17838. snippets.push( snippet );
  17839. }
  17840. return snippets.join( '\n\n' );
  17841. }
  17842. getVaryings( shaderStage ) {
  17843. let snippet = '';
  17844. const varyings = this.varyings;
  17845. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17846. for ( const varying of varyings ) {
  17847. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  17848. const type = varying.type;
  17849. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17850. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  17851. }
  17852. } else if ( shaderStage === 'fragment' ) {
  17853. for ( const varying of varyings ) {
  17854. if ( varying.needsInterpolation ) {
  17855. const type = varying.type;
  17856. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17857. snippet += `${flat}in ${type} ${varying.name};\n`;
  17858. }
  17859. }
  17860. }
  17861. for ( const builtin of this.builtins[ shaderStage ] ) {
  17862. snippet += `${builtin};\n`;
  17863. }
  17864. return snippet;
  17865. }
  17866. getVertexIndex() {
  17867. return 'uint( gl_VertexID )';
  17868. }
  17869. getInstanceIndex() {
  17870. return 'uint( gl_InstanceID )';
  17871. }
  17872. getInvocationLocalIndex() {
  17873. const workgroupSize = this.object.workgroupSize;
  17874. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  17875. return `uint( gl_InstanceID ) % ${size}u`;
  17876. }
  17877. getDrawIndex() {
  17878. const extensions = this.renderer.backend.extensions;
  17879. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  17880. return 'uint( gl_DrawID )';
  17881. }
  17882. return null;
  17883. }
  17884. getFrontFacing() {
  17885. return 'gl_FrontFacing';
  17886. }
  17887. getFragCoord() {
  17888. return 'gl_FragCoord.xy';
  17889. }
  17890. getFragDepth() {
  17891. return 'gl_FragDepth';
  17892. }
  17893. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  17894. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  17895. if ( map.has( name ) === false ) {
  17896. map.set( name, {
  17897. name,
  17898. behavior
  17899. } );
  17900. }
  17901. }
  17902. getExtensions( shaderStage ) {
  17903. const snippets = [];
  17904. if ( shaderStage === 'vertex' ) {
  17905. const ext = this.renderer.backend.extensions;
  17906. const isBatchedMesh = this.object.isBatchedMesh;
  17907. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  17908. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  17909. }
  17910. }
  17911. const extensions = this.extensions[ shaderStage ];
  17912. if ( extensions !== undefined ) {
  17913. for ( const { name, behavior } of extensions.values() ) {
  17914. snippets.push( `#extension ${name} : ${behavior}` );
  17915. }
  17916. }
  17917. return snippets.join( '\n' );
  17918. }
  17919. getClipDistance() {
  17920. return 'gl_ClipDistance';
  17921. }
  17922. isAvailable( name ) {
  17923. let result = supports$1[ name ];
  17924. if ( result === undefined ) {
  17925. let extensionName;
  17926. result = false;
  17927. switch ( name ) {
  17928. case 'float32Filterable':
  17929. extensionName = 'OES_texture_float_linear';
  17930. break;
  17931. case 'clipDistance':
  17932. extensionName = 'WEBGL_clip_cull_distance';
  17933. break;
  17934. }
  17935. if ( extensionName !== undefined ) {
  17936. const extensions = this.renderer.backend.extensions;
  17937. if ( extensions.has( extensionName ) ) {
  17938. extensions.get( extensionName );
  17939. result = true;
  17940. }
  17941. }
  17942. supports$1[ name ] = result;
  17943. }
  17944. return result;
  17945. }
  17946. isFlipY() {
  17947. return true;
  17948. }
  17949. enableHardwareClipping( planeCount ) {
  17950. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  17951. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  17952. }
  17953. registerTransform( varyingName, attributeNode ) {
  17954. this.transforms.push( { varyingName, attributeNode } );
  17955. }
  17956. getTransforms( /* shaderStage */ ) {
  17957. const transforms = this.transforms;
  17958. let snippet = '';
  17959. for ( let i = 0; i < transforms.length; i ++ ) {
  17960. const transform = transforms[ i ];
  17961. const attributeName = this.getPropertyName( transform.attributeNode );
  17962. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  17963. }
  17964. return snippet;
  17965. }
  17966. _getGLSLUniformStruct( name, vars ) {
  17967. return `
  17968. layout( std140 ) uniform ${name} {
  17969. ${vars}
  17970. };`;
  17971. }
  17972. _getGLSLVertexCode( shaderData ) {
  17973. return `#version 300 es
  17974. ${ this.getSignature() }
  17975. // extensions
  17976. ${shaderData.extensions}
  17977. // precision
  17978. ${ defaultPrecisions }
  17979. // uniforms
  17980. ${shaderData.uniforms}
  17981. // varyings
  17982. ${shaderData.varyings}
  17983. // attributes
  17984. ${shaderData.attributes}
  17985. // codes
  17986. ${shaderData.codes}
  17987. void main() {
  17988. // vars
  17989. ${shaderData.vars}
  17990. // transforms
  17991. ${shaderData.transforms}
  17992. // flow
  17993. ${shaderData.flow}
  17994. gl_PointSize = 1.0;
  17995. }
  17996. `;
  17997. }
  17998. _getGLSLFragmentCode( shaderData ) {
  17999. return `#version 300 es
  18000. ${ this.getSignature() }
  18001. // precision
  18002. ${ defaultPrecisions }
  18003. // uniforms
  18004. ${shaderData.uniforms}
  18005. // varyings
  18006. ${shaderData.varyings}
  18007. // codes
  18008. ${shaderData.codes}
  18009. ${shaderData.structs}
  18010. void main() {
  18011. // vars
  18012. ${shaderData.vars}
  18013. // flow
  18014. ${shaderData.flow}
  18015. }
  18016. `;
  18017. }
  18018. buildCode() {
  18019. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  18020. this.sortBindingGroups();
  18021. for ( const shaderStage in shadersData ) {
  18022. let flow = '// code\n\n';
  18023. flow += this.flowCode[ shaderStage ];
  18024. const flowNodes = this.flowNodes[ shaderStage ];
  18025. const mainNode = flowNodes[ flowNodes.length - 1 ];
  18026. for ( const node of flowNodes ) {
  18027. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  18028. const slotName = node.name;
  18029. if ( slotName ) {
  18030. if ( flow.length > 0 ) flow += '\n';
  18031. flow += `\t// flow -> ${ slotName }\n\t`;
  18032. }
  18033. flow += `${ flowSlotData.code }\n\t`;
  18034. if ( node === mainNode && shaderStage !== 'compute' ) {
  18035. flow += '// result\n\t';
  18036. if ( shaderStage === 'vertex' ) {
  18037. flow += 'gl_Position = ';
  18038. flow += `${ flowSlotData.result };`;
  18039. } else if ( shaderStage === 'fragment' ) {
  18040. if ( ! node.outputNode.isOutputStructNode ) {
  18041. flow += 'fragColor = ';
  18042. flow += `${ flowSlotData.result };`;
  18043. }
  18044. }
  18045. }
  18046. }
  18047. const stageData = shadersData[ shaderStage ];
  18048. stageData.extensions = this.getExtensions( shaderStage );
  18049. stageData.uniforms = this.getUniforms( shaderStage );
  18050. stageData.attributes = this.getAttributes( shaderStage );
  18051. stageData.varyings = this.getVaryings( shaderStage );
  18052. stageData.vars = this.getVars( shaderStage );
  18053. stageData.structs = this.getStructs( shaderStage );
  18054. stageData.codes = this.getCodes( shaderStage );
  18055. stageData.transforms = this.getTransforms( shaderStage );
  18056. stageData.flow = flow;
  18057. }
  18058. if ( this.material !== null ) {
  18059. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  18060. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  18061. } else {
  18062. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  18063. }
  18064. }
  18065. getUniformFromNode( node, type, shaderStage, name = null ) {
  18066. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  18067. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  18068. let uniformGPU = nodeData.uniformGPU;
  18069. if ( uniformGPU === undefined ) {
  18070. const group = node.groupNode;
  18071. const groupName = group.name;
  18072. const bindings = this.getBindGroupArray( groupName, shaderStage );
  18073. if ( type === 'texture' ) {
  18074. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  18075. bindings.push( uniformGPU );
  18076. } else if ( type === 'cubeTexture' ) {
  18077. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  18078. bindings.push( uniformGPU );
  18079. } else if ( type === 'texture3D' ) {
  18080. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  18081. bindings.push( uniformGPU );
  18082. } else if ( type === 'buffer' ) {
  18083. node.name = `NodeBuffer_${ node.id }`;
  18084. uniformNode.name = `buffer${ node.id }`;
  18085. const buffer = new NodeUniformBuffer( node, group );
  18086. buffer.name = node.name;
  18087. bindings.push( buffer );
  18088. uniformGPU = buffer;
  18089. } else {
  18090. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  18091. let uniformsGroup = uniformsStage[ groupName ];
  18092. if ( uniformsGroup === undefined ) {
  18093. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  18094. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  18095. uniformsStage[ groupName ] = uniformsGroup;
  18096. bindings.push( uniformsGroup );
  18097. }
  18098. uniformGPU = this.getNodeUniform( uniformNode, type );
  18099. uniformsGroup.addUniform( uniformGPU );
  18100. }
  18101. nodeData.uniformGPU = uniformGPU;
  18102. }
  18103. return uniformNode;
  18104. }
  18105. }
  18106. let vector2 = null;
  18107. let vector4 = null;
  18108. let color4 = null;
  18109. class Backend {
  18110. constructor( parameters = {} ) {
  18111. this.parameters = Object.assign( {}, parameters );
  18112. this.data = new WeakMap();
  18113. this.renderer = null;
  18114. this.domElement = null;
  18115. }
  18116. async init( renderer ) {
  18117. this.renderer = renderer;
  18118. }
  18119. // render context
  18120. begin( /*renderContext*/ ) { }
  18121. finish( /*renderContext*/ ) { }
  18122. // render object
  18123. draw( /*renderObject, info*/ ) { }
  18124. // program
  18125. createProgram( /*program*/ ) { }
  18126. destroyProgram( /*program*/ ) { }
  18127. // bindings
  18128. createBindings( /*bingGroup, bindings*/ ) { }
  18129. updateBindings( /*bingGroup, bindings*/ ) { }
  18130. // pipeline
  18131. createRenderPipeline( /*renderObject*/ ) { }
  18132. createComputePipeline( /*computeNode, pipeline*/ ) { }
  18133. destroyPipeline( /*pipeline*/ ) { }
  18134. // cache key
  18135. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  18136. getRenderCacheKey( /*renderObject*/ ) { } // return String
  18137. // node builder
  18138. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  18139. // textures
  18140. createSampler( /*texture*/ ) { }
  18141. createDefaultTexture( /*texture*/ ) { }
  18142. createTexture( /*texture*/ ) { }
  18143. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  18144. // attributes
  18145. createAttribute( /*attribute*/ ) { }
  18146. createIndexAttribute( /*attribute*/ ) { }
  18147. updateAttribute( /*attribute*/ ) { }
  18148. destroyAttribute( /*attribute*/ ) { }
  18149. // canvas
  18150. getContext() { }
  18151. updateSize() { }
  18152. // utils
  18153. resolveTimestampAsync( /*renderContext, type*/ ) { }
  18154. hasFeatureAsync( /*name*/ ) { } // return Boolean
  18155. hasFeature( /*name*/ ) { } // return Boolean
  18156. getInstanceCount( renderObject ) {
  18157. const { object, geometry } = renderObject;
  18158. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  18159. }
  18160. getDrawingBufferSize() {
  18161. vector2 = vector2 || new Vector2();
  18162. return this.renderer.getDrawingBufferSize( vector2 );
  18163. }
  18164. getScissor() {
  18165. vector4 = vector4 || new Vector4();
  18166. return this.renderer.getScissor( vector4 );
  18167. }
  18168. setScissorTest( /*boolean*/ ) { }
  18169. getClearColor() {
  18170. const renderer = this.renderer;
  18171. color4 = color4 || new Color4();
  18172. renderer.getClearColor( color4 );
  18173. color4.getRGB( color4, this.renderer.currentColorSpace );
  18174. return color4;
  18175. }
  18176. getDomElement() {
  18177. let domElement = this.domElement;
  18178. if ( domElement === null ) {
  18179. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  18180. // OffscreenCanvas does not have setAttribute, see #22811
  18181. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  18182. this.domElement = domElement;
  18183. }
  18184. return domElement;
  18185. }
  18186. // resource properties
  18187. set( object, value ) {
  18188. this.data.set( object, value );
  18189. }
  18190. get( object ) {
  18191. let map = this.data.get( object );
  18192. if ( map === undefined ) {
  18193. map = {};
  18194. this.data.set( object, map );
  18195. }
  18196. return map;
  18197. }
  18198. has( object ) {
  18199. return this.data.has( object );
  18200. }
  18201. delete( object ) {
  18202. this.data.delete( object );
  18203. }
  18204. dispose() { }
  18205. }
  18206. let _id$1 = 0;
  18207. class DualAttributeData {
  18208. constructor( attributeData, dualBuffer ) {
  18209. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  18210. this.type = attributeData.type;
  18211. this.bufferType = attributeData.bufferType;
  18212. this.pbo = attributeData.pbo;
  18213. this.byteLength = attributeData.byteLength;
  18214. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  18215. this.version = attributeData.version;
  18216. this.isInteger = attributeData.isInteger;
  18217. this.activeBufferIndex = 0;
  18218. this.baseId = attributeData.id;
  18219. }
  18220. get id() {
  18221. return `${ this.baseId }|${ this.activeBufferIndex }`;
  18222. }
  18223. get bufferGPU() {
  18224. return this.buffers[ this.activeBufferIndex ];
  18225. }
  18226. get transformBuffer() {
  18227. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18228. }
  18229. switchBuffers() {
  18230. this.activeBufferIndex ^= 1;
  18231. }
  18232. }
  18233. class WebGLAttributeUtils {
  18234. constructor( backend ) {
  18235. this.backend = backend;
  18236. }
  18237. createAttribute( attribute, bufferType ) {
  18238. const backend = this.backend;
  18239. const { gl } = backend;
  18240. const array = attribute.array;
  18241. const usage = attribute.usage || gl.STATIC_DRAW;
  18242. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18243. const bufferData = backend.get( bufferAttribute );
  18244. let bufferGPU = bufferData.bufferGPU;
  18245. if ( bufferGPU === undefined ) {
  18246. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18247. bufferData.bufferGPU = bufferGPU;
  18248. bufferData.bufferType = bufferType;
  18249. bufferData.version = bufferAttribute.version;
  18250. }
  18251. //attribute.onUploadCallback();
  18252. let type;
  18253. if ( array instanceof Float32Array ) {
  18254. type = gl.FLOAT;
  18255. } else if ( array instanceof Uint16Array ) {
  18256. if ( attribute.isFloat16BufferAttribute ) {
  18257. type = gl.HALF_FLOAT;
  18258. } else {
  18259. type = gl.UNSIGNED_SHORT;
  18260. }
  18261. } else if ( array instanceof Int16Array ) {
  18262. type = gl.SHORT;
  18263. } else if ( array instanceof Uint32Array ) {
  18264. type = gl.UNSIGNED_INT;
  18265. } else if ( array instanceof Int32Array ) {
  18266. type = gl.INT;
  18267. } else if ( array instanceof Int8Array ) {
  18268. type = gl.BYTE;
  18269. } else if ( array instanceof Uint8Array ) {
  18270. type = gl.UNSIGNED_BYTE;
  18271. } else if ( array instanceof Uint8ClampedArray ) {
  18272. type = gl.UNSIGNED_BYTE;
  18273. } else {
  18274. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18275. }
  18276. let attributeData = {
  18277. bufferGPU,
  18278. bufferType,
  18279. type,
  18280. byteLength: array.byteLength,
  18281. bytesPerElement: array.BYTES_PER_ELEMENT,
  18282. version: attribute.version,
  18283. pbo: attribute.pbo,
  18284. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18285. id: _id$1 ++
  18286. };
  18287. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18288. // create buffer for tranform feedback use
  18289. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18290. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18291. }
  18292. backend.set( attribute, attributeData );
  18293. }
  18294. updateAttribute( attribute ) {
  18295. const backend = this.backend;
  18296. const { gl } = backend;
  18297. const array = attribute.array;
  18298. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18299. const bufferData = backend.get( bufferAttribute );
  18300. const bufferType = bufferData.bufferType;
  18301. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18302. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18303. if ( updateRanges.length === 0 ) {
  18304. // Not using update ranges
  18305. gl.bufferSubData( bufferType, 0, array );
  18306. } else {
  18307. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18308. const range = updateRanges[ i ];
  18309. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18310. array, range.start, range.count );
  18311. }
  18312. bufferAttribute.clearUpdateRanges();
  18313. }
  18314. gl.bindBuffer( bufferType, null );
  18315. bufferData.version = bufferAttribute.version;
  18316. }
  18317. destroyAttribute( attribute ) {
  18318. const backend = this.backend;
  18319. const { gl } = backend;
  18320. if ( attribute.isInterleavedBufferAttribute ) {
  18321. backend.delete( attribute.data );
  18322. }
  18323. const attributeData = backend.get( attribute );
  18324. gl.deleteBuffer( attributeData.bufferGPU );
  18325. backend.delete( attribute );
  18326. }
  18327. async getArrayBufferAsync( attribute ) {
  18328. const backend = this.backend;
  18329. const { gl } = backend;
  18330. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18331. const { bufferGPU } = backend.get( bufferAttribute );
  18332. const array = attribute.array;
  18333. const byteLength = array.byteLength;
  18334. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18335. const writeBuffer = gl.createBuffer();
  18336. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18337. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18338. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18339. await backend.utils._clientWaitAsync();
  18340. const dstBuffer = new attribute.array.constructor( array.length );
  18341. // Ensure the buffer is bound before reading
  18342. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18343. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18344. gl.deleteBuffer( writeBuffer );
  18345. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18346. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18347. return dstBuffer.buffer;
  18348. }
  18349. _createBuffer( gl, bufferType, array, usage ) {
  18350. const bufferGPU = gl.createBuffer();
  18351. gl.bindBuffer( bufferType, bufferGPU );
  18352. gl.bufferData( bufferType, array, usage );
  18353. gl.bindBuffer( bufferType, null );
  18354. return bufferGPU;
  18355. }
  18356. }
  18357. let initialized$1 = false, equationToGL, factorToGL;
  18358. class WebGLState {
  18359. constructor( backend ) {
  18360. this.backend = backend;
  18361. this.gl = this.backend.gl;
  18362. this.enabled = {};
  18363. this.currentFlipSided = null;
  18364. this.currentCullFace = null;
  18365. this.currentProgram = null;
  18366. this.currentBlendingEnabled = false;
  18367. this.currentBlending = null;
  18368. this.currentBlendSrc = null;
  18369. this.currentBlendDst = null;
  18370. this.currentBlendSrcAlpha = null;
  18371. this.currentBlendDstAlpha = null;
  18372. this.currentPremultipledAlpha = null;
  18373. this.currentPolygonOffsetFactor = null;
  18374. this.currentPolygonOffsetUnits = null;
  18375. this.currentColorMask = null;
  18376. this.currentDepthFunc = null;
  18377. this.currentDepthMask = null;
  18378. this.currentStencilFunc = null;
  18379. this.currentStencilRef = null;
  18380. this.currentStencilFuncMask = null;
  18381. this.currentStencilFail = null;
  18382. this.currentStencilZFail = null;
  18383. this.currentStencilZPass = null;
  18384. this.currentStencilMask = null;
  18385. this.currentLineWidth = null;
  18386. this.currentClippingPlanes = 0;
  18387. this.currentBoundFramebuffers = {};
  18388. this.currentDrawbuffers = new WeakMap();
  18389. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18390. this.currentTextureSlot = null;
  18391. this.currentBoundTextures = {};
  18392. this.currentBoundBufferBases = {};
  18393. if ( initialized$1 === false ) {
  18394. this._init( this.gl );
  18395. initialized$1 = true;
  18396. }
  18397. }
  18398. _init( gl ) {
  18399. // Store only WebGL constants here.
  18400. equationToGL = {
  18401. [ AddEquation ]: gl.FUNC_ADD,
  18402. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18403. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18404. };
  18405. factorToGL = {
  18406. [ ZeroFactor ]: gl.ZERO,
  18407. [ OneFactor ]: gl.ONE,
  18408. [ SrcColorFactor ]: gl.SRC_COLOR,
  18409. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18410. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18411. [ DstColorFactor ]: gl.DST_COLOR,
  18412. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18413. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18414. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18415. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18416. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18417. };
  18418. }
  18419. enable( id ) {
  18420. const { enabled } = this;
  18421. if ( enabled[ id ] !== true ) {
  18422. this.gl.enable( id );
  18423. enabled[ id ] = true;
  18424. }
  18425. }
  18426. disable( id ) {
  18427. const { enabled } = this;
  18428. if ( enabled[ id ] !== false ) {
  18429. this.gl.disable( id );
  18430. enabled[ id ] = false;
  18431. }
  18432. }
  18433. setFlipSided( flipSided ) {
  18434. if ( this.currentFlipSided !== flipSided ) {
  18435. const { gl } = this;
  18436. if ( flipSided ) {
  18437. gl.frontFace( gl.CW );
  18438. } else {
  18439. gl.frontFace( gl.CCW );
  18440. }
  18441. this.currentFlipSided = flipSided;
  18442. }
  18443. }
  18444. setCullFace( cullFace ) {
  18445. const { gl } = this;
  18446. if ( cullFace !== CullFaceNone ) {
  18447. this.enable( gl.CULL_FACE );
  18448. if ( cullFace !== this.currentCullFace ) {
  18449. if ( cullFace === CullFaceBack ) {
  18450. gl.cullFace( gl.BACK );
  18451. } else if ( cullFace === CullFaceFront ) {
  18452. gl.cullFace( gl.FRONT );
  18453. } else {
  18454. gl.cullFace( gl.FRONT_AND_BACK );
  18455. }
  18456. }
  18457. } else {
  18458. this.disable( gl.CULL_FACE );
  18459. }
  18460. this.currentCullFace = cullFace;
  18461. }
  18462. setLineWidth( width ) {
  18463. const { currentLineWidth, gl } = this;
  18464. if ( width !== currentLineWidth ) {
  18465. gl.lineWidth( width );
  18466. this.currentLineWidth = width;
  18467. }
  18468. }
  18469. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18470. const { gl } = this;
  18471. if ( blending === NoBlending ) {
  18472. if ( this.currentBlendingEnabled === true ) {
  18473. this.disable( gl.BLEND );
  18474. this.currentBlendingEnabled = false;
  18475. }
  18476. return;
  18477. }
  18478. if ( this.currentBlendingEnabled === false ) {
  18479. this.enable( gl.BLEND );
  18480. this.currentBlendingEnabled = true;
  18481. }
  18482. if ( blending !== CustomBlending ) {
  18483. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18484. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18485. gl.blendEquation( gl.FUNC_ADD );
  18486. this.currentBlendEquation = AddEquation;
  18487. this.currentBlendEquationAlpha = AddEquation;
  18488. }
  18489. if ( premultipliedAlpha ) {
  18490. switch ( blending ) {
  18491. case NormalBlending:
  18492. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18493. break;
  18494. case AdditiveBlending:
  18495. gl.blendFunc( gl.ONE, gl.ONE );
  18496. break;
  18497. case SubtractiveBlending:
  18498. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18499. break;
  18500. case MultiplyBlending:
  18501. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18502. break;
  18503. default:
  18504. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18505. break;
  18506. }
  18507. } else {
  18508. switch ( blending ) {
  18509. case NormalBlending:
  18510. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18511. break;
  18512. case AdditiveBlending:
  18513. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18514. break;
  18515. case SubtractiveBlending:
  18516. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18517. break;
  18518. case MultiplyBlending:
  18519. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18520. break;
  18521. default:
  18522. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18523. break;
  18524. }
  18525. }
  18526. this.currentBlendSrc = null;
  18527. this.currentBlendDst = null;
  18528. this.currentBlendSrcAlpha = null;
  18529. this.currentBlendDstAlpha = null;
  18530. this.currentBlending = blending;
  18531. this.currentPremultipledAlpha = premultipliedAlpha;
  18532. }
  18533. return;
  18534. }
  18535. // custom blending
  18536. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18537. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18538. blendDstAlpha = blendDstAlpha || blendDst;
  18539. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  18540. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18541. this.currentBlendEquation = blendEquation;
  18542. this.currentBlendEquationAlpha = blendEquationAlpha;
  18543. }
  18544. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  18545. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18546. this.currentBlendSrc = blendSrc;
  18547. this.currentBlendDst = blendDst;
  18548. this.currentBlendSrcAlpha = blendSrcAlpha;
  18549. this.currentBlendDstAlpha = blendDstAlpha;
  18550. }
  18551. this.currentBlending = blending;
  18552. this.currentPremultipledAlpha = false;
  18553. }
  18554. setColorMask( colorMask ) {
  18555. if ( this.currentColorMask !== colorMask ) {
  18556. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  18557. this.currentColorMask = colorMask;
  18558. }
  18559. }
  18560. setDepthTest( depthTest ) {
  18561. const { gl } = this;
  18562. if ( depthTest ) {
  18563. this.enable( gl.DEPTH_TEST );
  18564. } else {
  18565. this.disable( gl.DEPTH_TEST );
  18566. }
  18567. }
  18568. setDepthMask( depthMask ) {
  18569. if ( this.currentDepthMask !== depthMask ) {
  18570. this.gl.depthMask( depthMask );
  18571. this.currentDepthMask = depthMask;
  18572. }
  18573. }
  18574. setDepthFunc( depthFunc ) {
  18575. if ( this.currentDepthFunc !== depthFunc ) {
  18576. const { gl } = this;
  18577. switch ( depthFunc ) {
  18578. case NeverDepth:
  18579. gl.depthFunc( gl.NEVER );
  18580. break;
  18581. case AlwaysDepth:
  18582. gl.depthFunc( gl.ALWAYS );
  18583. break;
  18584. case LessDepth:
  18585. gl.depthFunc( gl.LESS );
  18586. break;
  18587. case LessEqualDepth:
  18588. gl.depthFunc( gl.LEQUAL );
  18589. break;
  18590. case EqualDepth:
  18591. gl.depthFunc( gl.EQUAL );
  18592. break;
  18593. case GreaterEqualDepth:
  18594. gl.depthFunc( gl.GEQUAL );
  18595. break;
  18596. case GreaterDepth:
  18597. gl.depthFunc( gl.GREATER );
  18598. break;
  18599. case NotEqualDepth:
  18600. gl.depthFunc( gl.NOTEQUAL );
  18601. break;
  18602. default:
  18603. gl.depthFunc( gl.LEQUAL );
  18604. }
  18605. this.currentDepthFunc = depthFunc;
  18606. }
  18607. }
  18608. setStencilTest( stencilTest ) {
  18609. const { gl } = this;
  18610. if ( stencilTest ) {
  18611. this.enable( gl.STENCIL_TEST );
  18612. } else {
  18613. this.disable( gl.STENCIL_TEST );
  18614. }
  18615. }
  18616. setStencilMask( stencilMask ) {
  18617. if ( this.currentStencilMask !== stencilMask ) {
  18618. this.gl.stencilMask( stencilMask );
  18619. this.currentStencilMask = stencilMask;
  18620. }
  18621. }
  18622. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  18623. if ( this.currentStencilFunc !== stencilFunc ||
  18624. this.currentStencilRef !== stencilRef ||
  18625. this.currentStencilFuncMask !== stencilMask ) {
  18626. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18627. this.currentStencilFunc = stencilFunc;
  18628. this.currentStencilRef = stencilRef;
  18629. this.currentStencilFuncMask = stencilMask;
  18630. }
  18631. }
  18632. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  18633. if ( this.currentStencilFail !== stencilFail ||
  18634. this.currentStencilZFail !== stencilZFail ||
  18635. this.currentStencilZPass !== stencilZPass ) {
  18636. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18637. this.currentStencilFail = stencilFail;
  18638. this.currentStencilZFail = stencilZFail;
  18639. this.currentStencilZPass = stencilZPass;
  18640. }
  18641. }
  18642. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  18643. const { gl } = this;
  18644. material.side === DoubleSide
  18645. ? this.disable( gl.CULL_FACE )
  18646. : this.enable( gl.CULL_FACE );
  18647. let flipSided = ( material.side === BackSide );
  18648. if ( frontFaceCW ) flipSided = ! flipSided;
  18649. this.setFlipSided( flipSided );
  18650. ( material.blending === NormalBlending && material.transparent === false )
  18651. ? this.setBlending( NoBlending )
  18652. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  18653. this.setDepthFunc( material.depthFunc );
  18654. this.setDepthTest( material.depthTest );
  18655. this.setDepthMask( material.depthWrite );
  18656. this.setColorMask( material.colorWrite );
  18657. const stencilWrite = material.stencilWrite;
  18658. this.setStencilTest( stencilWrite );
  18659. if ( stencilWrite ) {
  18660. this.setStencilMask( material.stencilWriteMask );
  18661. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  18662. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  18663. }
  18664. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  18665. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  18666. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  18667. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  18668. if ( hardwareClippingPlanes > 0 ) {
  18669. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  18670. const CLIP_DISTANCE0_WEBGL = 0x3000;
  18671. for ( let i = 0; i < 8; i ++ ) {
  18672. if ( i < hardwareClippingPlanes ) {
  18673. this.enable( CLIP_DISTANCE0_WEBGL + i );
  18674. } else {
  18675. this.disable( CLIP_DISTANCE0_WEBGL + i );
  18676. }
  18677. }
  18678. }
  18679. }
  18680. }
  18681. setPolygonOffset( polygonOffset, factor, units ) {
  18682. const { gl } = this;
  18683. if ( polygonOffset ) {
  18684. this.enable( gl.POLYGON_OFFSET_FILL );
  18685. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  18686. gl.polygonOffset( factor, units );
  18687. this.currentPolygonOffsetFactor = factor;
  18688. this.currentPolygonOffsetUnits = units;
  18689. }
  18690. } else {
  18691. this.disable( gl.POLYGON_OFFSET_FILL );
  18692. }
  18693. }
  18694. useProgram( program ) {
  18695. if ( this.currentProgram !== program ) {
  18696. this.gl.useProgram( program );
  18697. this.currentProgram = program;
  18698. return true;
  18699. }
  18700. return false;
  18701. }
  18702. // framebuffer
  18703. bindFramebuffer( target, framebuffer ) {
  18704. const { gl, currentBoundFramebuffers } = this;
  18705. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  18706. gl.bindFramebuffer( target, framebuffer );
  18707. currentBoundFramebuffers[ target ] = framebuffer;
  18708. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  18709. if ( target === gl.DRAW_FRAMEBUFFER ) {
  18710. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  18711. }
  18712. if ( target === gl.FRAMEBUFFER ) {
  18713. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  18714. }
  18715. return true;
  18716. }
  18717. return false;
  18718. }
  18719. drawBuffers( renderContext, framebuffer ) {
  18720. const { gl } = this;
  18721. let drawBuffers = [];
  18722. let needsUpdate = false;
  18723. if ( renderContext.textures !== null ) {
  18724. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  18725. if ( drawBuffers === undefined ) {
  18726. drawBuffers = [];
  18727. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  18728. }
  18729. const textures = renderContext.textures;
  18730. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  18731. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  18732. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  18733. }
  18734. drawBuffers.length = textures.length;
  18735. needsUpdate = true;
  18736. }
  18737. } else {
  18738. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  18739. drawBuffers[ 0 ] = gl.BACK;
  18740. needsUpdate = true;
  18741. }
  18742. }
  18743. if ( needsUpdate ) {
  18744. gl.drawBuffers( drawBuffers );
  18745. }
  18746. }
  18747. // texture
  18748. activeTexture( webglSlot ) {
  18749. const { gl, currentTextureSlot, maxTextures } = this;
  18750. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18751. if ( currentTextureSlot !== webglSlot ) {
  18752. gl.activeTexture( webglSlot );
  18753. this.currentTextureSlot = webglSlot;
  18754. }
  18755. }
  18756. bindTexture( webglType, webglTexture, webglSlot ) {
  18757. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  18758. if ( webglSlot === undefined ) {
  18759. if ( currentTextureSlot === null ) {
  18760. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18761. } else {
  18762. webglSlot = currentTextureSlot;
  18763. }
  18764. }
  18765. let boundTexture = currentBoundTextures[ webglSlot ];
  18766. if ( boundTexture === undefined ) {
  18767. boundTexture = { type: undefined, texture: undefined };
  18768. currentBoundTextures[ webglSlot ] = boundTexture;
  18769. }
  18770. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18771. if ( currentTextureSlot !== webglSlot ) {
  18772. gl.activeTexture( webglSlot );
  18773. this.currentTextureSlot = webglSlot;
  18774. }
  18775. gl.bindTexture( webglType, webglTexture );
  18776. boundTexture.type = webglType;
  18777. boundTexture.texture = webglTexture;
  18778. }
  18779. }
  18780. bindBufferBase( target, index, buffer ) {
  18781. const { gl } = this;
  18782. const key = `${target}-${index}`;
  18783. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  18784. gl.bindBufferBase( target, index, buffer );
  18785. this.currentBoundBufferBases[ key ] = buffer;
  18786. return true;
  18787. }
  18788. return false;
  18789. }
  18790. unbindTexture() {
  18791. const { gl, currentTextureSlot, currentBoundTextures } = this;
  18792. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  18793. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  18794. gl.bindTexture( boundTexture.type, null );
  18795. boundTexture.type = undefined;
  18796. boundTexture.texture = undefined;
  18797. }
  18798. }
  18799. }
  18800. class WebGLUtils {
  18801. constructor( backend ) {
  18802. this.backend = backend;
  18803. this.gl = this.backend.gl;
  18804. this.extensions = backend.extensions;
  18805. }
  18806. convert( p, colorSpace = NoColorSpace ) {
  18807. const { gl, extensions } = this;
  18808. let extension;
  18809. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  18810. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  18811. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  18812. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  18813. if ( p === ByteType ) return gl.BYTE;
  18814. if ( p === ShortType ) return gl.SHORT;
  18815. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  18816. if ( p === IntType ) return gl.INT;
  18817. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  18818. if ( p === FloatType ) return gl.FLOAT;
  18819. if ( p === HalfFloatType ) {
  18820. return gl.HALF_FLOAT;
  18821. }
  18822. if ( p === AlphaFormat ) return gl.ALPHA;
  18823. if ( p === RGBFormat ) return gl.RGB;
  18824. if ( p === RGBAFormat ) return gl.RGBA;
  18825. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  18826. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  18827. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  18828. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  18829. // WebGL2 formats.
  18830. if ( p === RedFormat ) return gl.RED;
  18831. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  18832. if ( p === RGFormat ) return gl.RG;
  18833. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  18834. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  18835. // S3TC
  18836. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  18837. if ( colorSpace === SRGBColorSpace ) {
  18838. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  18839. if ( extension !== null ) {
  18840. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  18841. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  18842. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  18843. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  18844. } else {
  18845. return null;
  18846. }
  18847. } else {
  18848. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  18849. if ( extension !== null ) {
  18850. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  18851. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18852. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18853. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18854. } else {
  18855. return null;
  18856. }
  18857. }
  18858. }
  18859. // PVRTC
  18860. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  18861. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  18862. if ( extension !== null ) {
  18863. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  18864. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  18865. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  18866. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  18867. } else {
  18868. return null;
  18869. }
  18870. }
  18871. // ETC
  18872. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  18873. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  18874. if ( extension !== null ) {
  18875. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  18876. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  18877. } else {
  18878. return null;
  18879. }
  18880. }
  18881. // ASTC
  18882. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  18883. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  18884. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  18885. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  18886. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  18887. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  18888. if ( extension !== null ) {
  18889. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  18890. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  18891. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  18892. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  18893. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  18894. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  18895. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  18896. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  18897. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  18898. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  18899. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  18900. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  18901. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  18902. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  18903. } else {
  18904. return null;
  18905. }
  18906. }
  18907. // BPTC
  18908. if ( p === RGBA_BPTC_Format ) {
  18909. extension = extensions.get( 'EXT_texture_compression_bptc' );
  18910. if ( extension !== null ) {
  18911. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  18912. } else {
  18913. return null;
  18914. }
  18915. }
  18916. // RGTC
  18917. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  18918. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  18919. if ( extension !== null ) {
  18920. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  18921. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  18922. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  18923. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  18924. } else {
  18925. return null;
  18926. }
  18927. }
  18928. //
  18929. if ( p === UnsignedInt248Type ) {
  18930. return gl.UNSIGNED_INT_24_8;
  18931. }
  18932. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  18933. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  18934. }
  18935. _clientWaitAsync() {
  18936. const { gl } = this;
  18937. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18938. gl.flush();
  18939. return new Promise( ( resolve, reject ) => {
  18940. function test() {
  18941. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  18942. if ( res === gl.WAIT_FAILED ) {
  18943. gl.deleteSync( sync );
  18944. reject();
  18945. return;
  18946. }
  18947. if ( res === gl.TIMEOUT_EXPIRED ) {
  18948. requestAnimationFrame( test );
  18949. return;
  18950. }
  18951. gl.deleteSync( sync );
  18952. resolve();
  18953. }
  18954. test();
  18955. } );
  18956. }
  18957. }
  18958. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  18959. class WebGLTextureUtils {
  18960. constructor( backend ) {
  18961. this.backend = backend;
  18962. this.gl = backend.gl;
  18963. this.extensions = backend.extensions;
  18964. this.defaultTextures = {};
  18965. if ( initialized === false ) {
  18966. this._init( this.gl );
  18967. initialized = true;
  18968. }
  18969. }
  18970. _init( gl ) {
  18971. // Store only WebGL constants here.
  18972. wrappingToGL = {
  18973. [ RepeatWrapping ]: gl.REPEAT,
  18974. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  18975. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  18976. };
  18977. filterToGL = {
  18978. [ NearestFilter ]: gl.NEAREST,
  18979. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  18980. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  18981. [ LinearFilter ]: gl.LINEAR,
  18982. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  18983. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  18984. };
  18985. compareToGL = {
  18986. [ NeverCompare ]: gl.NEVER,
  18987. [ AlwaysCompare ]: gl.ALWAYS,
  18988. [ LessCompare ]: gl.LESS,
  18989. [ LessEqualCompare ]: gl.LEQUAL,
  18990. [ EqualCompare ]: gl.EQUAL,
  18991. [ GreaterEqualCompare ]: gl.GEQUAL,
  18992. [ GreaterCompare ]: gl.GREATER,
  18993. [ NotEqualCompare ]: gl.NOTEQUAL
  18994. };
  18995. }
  18996. filterFallback( f ) {
  18997. const { gl } = this;
  18998. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18999. return gl.NEAREST;
  19000. }
  19001. return gl.LINEAR;
  19002. }
  19003. getGLTextureType( texture ) {
  19004. const { gl } = this;
  19005. let glTextureType;
  19006. if ( texture.isCubeTexture === true ) {
  19007. glTextureType = gl.TEXTURE_CUBE_MAP;
  19008. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  19009. glTextureType = gl.TEXTURE_2D_ARRAY;
  19010. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  19011. glTextureType = gl.TEXTURE_3D;
  19012. } else {
  19013. glTextureType = gl.TEXTURE_2D;
  19014. }
  19015. return glTextureType;
  19016. }
  19017. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  19018. const { gl, extensions } = this;
  19019. if ( internalFormatName !== null ) {
  19020. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  19021. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  19022. }
  19023. let internalFormat = glFormat;
  19024. if ( glFormat === gl.RED ) {
  19025. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  19026. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  19027. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  19028. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  19029. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19030. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19031. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19032. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19033. }
  19034. if ( glFormat === gl.RED_INTEGER ) {
  19035. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  19036. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  19037. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19038. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19039. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19040. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19041. }
  19042. if ( glFormat === gl.RG ) {
  19043. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  19044. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  19045. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  19046. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  19047. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19048. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19049. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19050. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19051. }
  19052. if ( glFormat === gl.RG_INTEGER ) {
  19053. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  19054. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  19055. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19056. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19057. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19058. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19059. }
  19060. if ( glFormat === gl.RGB ) {
  19061. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  19062. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  19063. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  19064. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  19065. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19066. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19067. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19068. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19069. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  19070. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  19071. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19072. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  19073. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  19074. }
  19075. if ( glFormat === gl.RGB_INTEGER ) {
  19076. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  19077. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  19078. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19079. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19080. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19081. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19082. }
  19083. if ( glFormat === gl.RGBA ) {
  19084. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  19085. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  19086. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  19087. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  19088. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19089. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19090. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19091. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19092. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  19093. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  19094. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19095. }
  19096. if ( glFormat === gl.RGBA_INTEGER ) {
  19097. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  19098. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  19099. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19100. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19101. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19102. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19103. }
  19104. if ( glFormat === gl.DEPTH_COMPONENT ) {
  19105. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  19106. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  19107. }
  19108. if ( glFormat === gl.DEPTH_STENCIL ) {
  19109. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  19110. }
  19111. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  19112. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  19113. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  19114. extensions.get( 'EXT_color_buffer_float' );
  19115. }
  19116. return internalFormat;
  19117. }
  19118. setTextureParameters( textureType, texture ) {
  19119. const { gl, extensions, backend } = this;
  19120. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  19121. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  19122. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  19123. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  19124. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  19125. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  19126. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  19127. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  19128. }
  19129. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  19130. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  19131. // follow WebGPU backend mapping for texture filtering
  19132. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  19133. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  19134. if ( texture.compareFunction ) {
  19135. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  19136. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  19137. }
  19138. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19139. if ( texture.magFilter === NearestFilter ) return;
  19140. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  19141. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  19142. if ( texture.anisotropy > 1 ) {
  19143. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19144. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  19145. }
  19146. }
  19147. }
  19148. createDefaultTexture( texture ) {
  19149. const { gl, backend, defaultTextures } = this;
  19150. const glTextureType = this.getGLTextureType( texture );
  19151. let textureGPU = defaultTextures[ glTextureType ];
  19152. if ( textureGPU === undefined ) {
  19153. textureGPU = gl.createTexture();
  19154. backend.state.bindTexture( glTextureType, textureGPU );
  19155. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  19156. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  19157. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  19158. defaultTextures[ glTextureType ] = textureGPU;
  19159. }
  19160. backend.set( texture, {
  19161. textureGPU,
  19162. glTextureType,
  19163. isDefault: true
  19164. } );
  19165. }
  19166. createTexture( texture, options ) {
  19167. const { gl, backend } = this;
  19168. const { levels, width, height, depth } = options;
  19169. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  19170. const glType = backend.utils.convert( texture.type );
  19171. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  19172. const textureGPU = gl.createTexture();
  19173. const glTextureType = this.getGLTextureType( texture );
  19174. backend.state.bindTexture( glTextureType, textureGPU );
  19175. this.setTextureParameters( glTextureType, texture );
  19176. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  19177. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  19178. } else if ( texture.isData3DTexture ) {
  19179. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  19180. } else if ( ! texture.isVideoTexture ) {
  19181. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  19182. }
  19183. backend.set( texture, {
  19184. textureGPU,
  19185. glTextureType,
  19186. glFormat,
  19187. glType,
  19188. glInternalFormat
  19189. } );
  19190. }
  19191. copyBufferToTexture( buffer, texture ) {
  19192. const { gl, backend } = this;
  19193. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  19194. const { width, height } = texture.source.data;
  19195. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  19196. backend.state.bindTexture( glTextureType, textureGPU );
  19197. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  19198. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  19199. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  19200. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  19201. backend.state.unbindTexture();
  19202. // debug
  19203. // const framebuffer = gl.createFramebuffer();
  19204. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  19205. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  19206. // const readout = new Float32Array( width * height * 4 );
  19207. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  19208. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  19209. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  19210. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  19211. // console.log( readout );
  19212. }
  19213. updateTexture( texture, options ) {
  19214. const { gl } = this;
  19215. const { width, height } = options;
  19216. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  19217. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  19218. return;
  19219. const getImage = ( source ) => {
  19220. if ( source.isDataTexture ) {
  19221. return source.image.data;
  19222. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19223. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19224. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19225. source instanceof OffscreenCanvas ) {
  19226. return source;
  19227. }
  19228. return source.data;
  19229. };
  19230. this.backend.state.bindTexture( glTextureType, textureGPU );
  19231. this.setTextureParameters( glTextureType, texture );
  19232. if ( texture.isCompressedTexture ) {
  19233. const mipmaps = texture.mipmaps;
  19234. const image = options.image;
  19235. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19236. const mipmap = mipmaps[ i ];
  19237. if ( texture.isCompressedArrayTexture ) {
  19238. if ( texture.format !== gl.RGBA ) {
  19239. if ( glFormat !== null ) {
  19240. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19241. } else {
  19242. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19243. }
  19244. } else {
  19245. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19246. }
  19247. } else {
  19248. if ( glFormat !== null ) {
  19249. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19250. } else {
  19251. console.warn( 'Unsupported compressed texture format' );
  19252. }
  19253. }
  19254. }
  19255. } else if ( texture.isCubeTexture ) {
  19256. const images = options.images;
  19257. for ( let i = 0; i < 6; i ++ ) {
  19258. const image = getImage( images[ i ] );
  19259. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19260. }
  19261. } else if ( texture.isDataArrayTexture ) {
  19262. const image = options.image;
  19263. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19264. } else if ( texture.isData3DTexture ) {
  19265. const image = options.image;
  19266. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19267. } else if ( texture.isVideoTexture ) {
  19268. texture.update();
  19269. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19270. } else {
  19271. const image = getImage( options.image );
  19272. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19273. }
  19274. }
  19275. generateMipmaps( texture ) {
  19276. const { gl, backend } = this;
  19277. const { textureGPU, glTextureType } = backend.get( texture );
  19278. backend.state.bindTexture( glTextureType, textureGPU );
  19279. gl.generateMipmap( glTextureType );
  19280. }
  19281. deallocateRenderBuffers( renderTarget ) {
  19282. const { gl, backend } = this;
  19283. // remove framebuffer reference
  19284. if ( renderTarget ) {
  19285. const renderContextData = backend.get( renderTarget );
  19286. renderContextData.renderBufferStorageSetup = undefined;
  19287. if ( renderContextData.framebuffers ) {
  19288. for ( const cacheKey in renderContextData.framebuffers ) {
  19289. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19290. }
  19291. delete renderContextData.framebuffers;
  19292. }
  19293. if ( renderContextData.depthRenderbuffer ) {
  19294. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19295. delete renderContextData.depthRenderbuffer;
  19296. }
  19297. if ( renderContextData.stencilRenderbuffer ) {
  19298. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19299. delete renderContextData.stencilRenderbuffer;
  19300. }
  19301. if ( renderContextData.msaaFrameBuffer ) {
  19302. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19303. delete renderContextData.msaaFrameBuffer;
  19304. }
  19305. if ( renderContextData.msaaRenderbuffers ) {
  19306. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19307. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19308. }
  19309. delete renderContextData.msaaRenderbuffers;
  19310. }
  19311. }
  19312. }
  19313. destroyTexture( texture ) {
  19314. const { gl, backend } = this;
  19315. const { textureGPU, renderTarget } = backend.get( texture );
  19316. this.deallocateRenderBuffers( renderTarget );
  19317. gl.deleteTexture( textureGPU );
  19318. backend.delete( texture );
  19319. }
  19320. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19321. const { gl, backend } = this;
  19322. const { state } = this.backend;
  19323. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19324. let width, height, minX, minY;
  19325. let dstX, dstY;
  19326. if ( srcRegion !== null ) {
  19327. width = srcRegion.max.x - srcRegion.min.x;
  19328. height = srcRegion.max.y - srcRegion.min.y;
  19329. minX = srcRegion.min.x;
  19330. minY = srcRegion.min.y;
  19331. } else {
  19332. width = srcTexture.image.width;
  19333. height = srcTexture.image.height;
  19334. minX = 0;
  19335. minY = 0;
  19336. }
  19337. if ( dstPosition !== null ) {
  19338. dstX = dstPosition.x;
  19339. dstY = dstPosition.y;
  19340. } else {
  19341. dstX = 0;
  19342. dstY = 0;
  19343. }
  19344. state.bindTexture( glTextureType, dstTextureGPU );
  19345. // As another texture upload may have changed pixelStorei
  19346. // parameters, make sure they are correct for the dstTexture
  19347. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19348. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19349. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19350. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19351. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19352. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19353. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19354. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19355. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19356. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19357. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19358. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19359. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19360. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19361. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19362. const srcTextureData = backend.get( srcTexture );
  19363. const dstTextureData = backend.get( dstTexture );
  19364. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19365. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19366. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19367. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19368. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19369. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19370. let mask = gl.COLOR_BUFFER_BIT;
  19371. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19372. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19373. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19374. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19375. } else {
  19376. if ( srcTexture.isDataTexture ) {
  19377. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19378. } else {
  19379. if ( srcTexture.isCompressedTexture ) {
  19380. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19381. } else {
  19382. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19383. }
  19384. }
  19385. }
  19386. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19387. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19388. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19389. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19390. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19391. // Generate mipmaps only when copying level 0
  19392. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19393. state.unbindTexture();
  19394. }
  19395. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19396. const { gl } = this;
  19397. const { state } = this.backend;
  19398. const { textureGPU } = this.backend.get( texture );
  19399. const { x, y, z: width, w: height } = rectangle;
  19400. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19401. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19402. if ( requireDrawFrameBuffer ) {
  19403. const partial = ( x !== 0 || y !== 0 );
  19404. let mask;
  19405. let attachment;
  19406. if ( texture.isDepthTexture === true ) {
  19407. mask = gl.DEPTH_BUFFER_BIT;
  19408. attachment = gl.DEPTH_ATTACHMENT;
  19409. if ( renderContext.stencil ) {
  19410. mask |= gl.STENCIL_BUFFER_BIT;
  19411. }
  19412. } else {
  19413. mask = gl.COLOR_BUFFER_BIT;
  19414. attachment = gl.COLOR_ATTACHMENT0;
  19415. }
  19416. if ( partial ) {
  19417. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19418. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19419. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19420. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19421. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19422. const flippedY = srcHeight - y - height;
  19423. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19424. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19425. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19426. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19427. state.unbindTexture();
  19428. } else {
  19429. const fb = gl.createFramebuffer();
  19430. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19431. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19432. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19433. gl.deleteFramebuffer( fb );
  19434. }
  19435. } else {
  19436. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19437. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19438. state.unbindTexture();
  19439. }
  19440. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19441. this.backend._setFramebuffer( renderContext );
  19442. }
  19443. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19444. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19445. const { gl } = this;
  19446. const renderTarget = renderContext.renderTarget;
  19447. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19448. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19449. if ( depthBuffer && ! stencilBuffer ) {
  19450. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19451. if ( samples > 0 ) {
  19452. if ( depthTexture && depthTexture.isDepthTexture ) {
  19453. if ( depthTexture.type === gl.FLOAT ) {
  19454. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19455. }
  19456. }
  19457. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19458. } else {
  19459. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19460. }
  19461. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19462. } else if ( depthBuffer && stencilBuffer ) {
  19463. if ( samples > 0 ) {
  19464. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19465. } else {
  19466. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19467. }
  19468. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19469. }
  19470. }
  19471. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19472. const { backend, gl } = this;
  19473. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19474. const fb = gl.createFramebuffer();
  19475. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19476. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19477. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19478. const typedArrayType = this._getTypedArrayType( glType );
  19479. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19480. const elementCount = width * height;
  19481. const byteLength = elementCount * bytesPerTexel;
  19482. const buffer = gl.createBuffer();
  19483. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19484. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19485. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19486. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19487. await backend.utils._clientWaitAsync();
  19488. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19489. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19490. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19491. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19492. gl.deleteFramebuffer( fb );
  19493. return dstBuffer;
  19494. }
  19495. _getTypedArrayType( glType ) {
  19496. const { gl } = this;
  19497. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19498. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19499. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19500. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19501. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19502. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19503. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19504. if ( glType === gl.FLOAT ) return Float32Array;
  19505. throw new Error( `Unsupported WebGL type: ${glType}` );
  19506. }
  19507. _getBytesPerTexel( glType, glFormat ) {
  19508. const { gl } = this;
  19509. let bytesPerComponent = 0;
  19510. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19511. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19512. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19513. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19514. glType === gl.UNSIGNED_SHORT ||
  19515. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19516. if ( glType === gl.UNSIGNED_INT ||
  19517. glType === gl.FLOAT ) bytesPerComponent = 4;
  19518. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19519. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19520. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19521. }
  19522. }
  19523. class WebGLExtensions {
  19524. constructor( backend ) {
  19525. this.backend = backend;
  19526. this.gl = this.backend.gl;
  19527. this.availableExtensions = this.gl.getSupportedExtensions();
  19528. this.extensions = {};
  19529. }
  19530. get( name ) {
  19531. let extension = this.extensions[ name ];
  19532. if ( extension === undefined ) {
  19533. extension = this.gl.getExtension( name );
  19534. this.extensions[ name ] = extension;
  19535. }
  19536. return extension;
  19537. }
  19538. has( name ) {
  19539. return this.availableExtensions.includes( name );
  19540. }
  19541. }
  19542. class WebGLCapabilities {
  19543. constructor( backend ) {
  19544. this.backend = backend;
  19545. this.maxAnisotropy = null;
  19546. }
  19547. getMaxAnisotropy() {
  19548. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  19549. const gl = this.backend.gl;
  19550. const extensions = this.backend.extensions;
  19551. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19552. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19553. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  19554. } else {
  19555. this.maxAnisotropy = 0;
  19556. }
  19557. return this.maxAnisotropy;
  19558. }
  19559. }
  19560. const GLFeatureName = {
  19561. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  19562. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  19563. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  19564. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  19565. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19566. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19567. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  19568. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  19569. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  19570. };
  19571. class WebGLBufferRenderer {
  19572. constructor( backend ) {
  19573. this.gl = backend.gl;
  19574. this.extensions = backend.extensions;
  19575. this.info = backend.renderer.info;
  19576. this.mode = null;
  19577. this.index = 0;
  19578. this.type = null;
  19579. this.object = null;
  19580. }
  19581. render( start, count ) {
  19582. const { gl, mode, object, type, info, index } = this;
  19583. if ( index !== 0 ) {
  19584. gl.drawElements( mode, count, type, start );
  19585. } else {
  19586. gl.drawArrays( mode, start, count );
  19587. }
  19588. info.update( object, count, mode, 1 );
  19589. }
  19590. renderInstances( start, count, primcount ) {
  19591. const { gl, mode, type, index, object, info } = this;
  19592. if ( primcount === 0 ) return;
  19593. if ( index !== 0 ) {
  19594. gl.drawElementsInstanced( mode, count, type, start, primcount );
  19595. } else {
  19596. gl.drawArraysInstanced( mode, start, count, primcount );
  19597. }
  19598. info.update( object, count, mode, primcount );
  19599. }
  19600. renderMultiDraw( starts, counts, drawCount ) {
  19601. const { extensions, mode, object, info } = this;
  19602. if ( drawCount === 0 ) return;
  19603. const extension = extensions.get( 'WEBGL_multi_draw' );
  19604. if ( extension === null ) {
  19605. for ( let i = 0; i < drawCount; i ++ ) {
  19606. this.render( starts[ i ], counts[ i ] );
  19607. }
  19608. } else {
  19609. if ( this.index !== 0 ) {
  19610. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  19611. } else {
  19612. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  19613. }
  19614. let elementCount = 0;
  19615. for ( let i = 0; i < drawCount; i ++ ) {
  19616. elementCount += counts[ i ];
  19617. }
  19618. info.update( object, elementCount, mode, 1 );
  19619. }
  19620. }
  19621. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  19622. const { extensions, mode, object, info } = this;
  19623. if ( drawCount === 0 ) return;
  19624. const extension = extensions.get( 'WEBGL_multi_draw' );
  19625. if ( extension === null ) {
  19626. for ( let i = 0; i < drawCount; i ++ ) {
  19627. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  19628. }
  19629. } else {
  19630. if ( this.index !== 0 ) {
  19631. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  19632. } else {
  19633. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  19634. }
  19635. let elementCount = 0;
  19636. for ( let i = 0; i < drawCount; i ++ ) {
  19637. elementCount += counts[ i ] * primcount[ i ];
  19638. }
  19639. info.update( object, elementCount, mode, 1 );
  19640. }
  19641. }
  19642. //
  19643. }
  19644. //
  19645. class WebGLBackend extends Backend {
  19646. constructor( parameters = {} ) {
  19647. super( parameters );
  19648. this.isWebGLBackend = true;
  19649. }
  19650. init( renderer ) {
  19651. super.init( renderer );
  19652. //
  19653. const parameters = this.parameters;
  19654. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  19655. function onContextLost( event ) {
  19656. event.preventDefault();
  19657. const contextLossInfo = {
  19658. api: 'WebGL',
  19659. message: event.statusMessage || 'Unknown reason',
  19660. reason: null,
  19661. originalEvent: event
  19662. };
  19663. renderer.onDeviceLost( contextLossInfo );
  19664. }
  19665. this._onContextLost = onContextLost;
  19666. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  19667. this.gl = glContext;
  19668. this.extensions = new WebGLExtensions( this );
  19669. this.capabilities = new WebGLCapabilities( this );
  19670. this.attributeUtils = new WebGLAttributeUtils( this );
  19671. this.textureUtils = new WebGLTextureUtils( this );
  19672. this.bufferRenderer = new WebGLBufferRenderer( this );
  19673. this.state = new WebGLState( this );
  19674. this.utils = new WebGLUtils( this );
  19675. this.vaoCache = {};
  19676. this.transformFeedbackCache = {};
  19677. this.discard = false;
  19678. this.trackTimestamp = ( parameters.trackTimestamp === true );
  19679. this.extensions.get( 'EXT_color_buffer_float' );
  19680. this.extensions.get( 'WEBGL_clip_cull_distance' );
  19681. this.extensions.get( 'OES_texture_float_linear' );
  19682. this.extensions.get( 'EXT_color_buffer_half_float' );
  19683. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  19684. this.extensions.get( 'WEBGL_render_shared_exponent' );
  19685. this.extensions.get( 'WEBGL_multi_draw' );
  19686. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  19687. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  19688. this._knownBindings = new WeakSet();
  19689. this._currentContext = null;
  19690. }
  19691. get coordinateSystem() {
  19692. return WebGLCoordinateSystem;
  19693. }
  19694. async getArrayBufferAsync( attribute ) {
  19695. return await this.attributeUtils.getArrayBufferAsync( attribute );
  19696. }
  19697. async waitForGPU() {
  19698. await this.utils._clientWaitAsync();
  19699. }
  19700. initTimestampQuery( renderContext ) {
  19701. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19702. const renderContextData = this.get( renderContext );
  19703. if ( this.queryRunning ) {
  19704. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  19705. renderContextData.queryQueue.push( renderContext );
  19706. return;
  19707. }
  19708. if ( renderContextData.activeQuery ) {
  19709. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19710. renderContextData.activeQuery = null;
  19711. }
  19712. renderContextData.activeQuery = this.gl.createQuery();
  19713. if ( renderContextData.activeQuery !== null ) {
  19714. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  19715. this.queryRunning = true;
  19716. }
  19717. }
  19718. // timestamp utils
  19719. prepareTimestampBuffer( renderContext ) {
  19720. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19721. const renderContextData = this.get( renderContext );
  19722. if ( renderContextData.activeQuery ) {
  19723. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19724. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19725. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  19726. renderContextData.activeQuery = null;
  19727. this.queryRunning = false;
  19728. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  19729. const nextRenderContext = renderContextData.queryQueue.shift();
  19730. this.initTimestampQuery( nextRenderContext );
  19731. }
  19732. }
  19733. }
  19734. async resolveTimestampAsync( renderContext, type = 'render' ) {
  19735. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19736. const renderContextData = this.get( renderContext );
  19737. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19738. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  19739. const queryInfo = renderContextData.gpuQueries[ i ];
  19740. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  19741. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  19742. if ( available && ! disjoint ) {
  19743. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  19744. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  19745. this.gl.deleteQuery( queryInfo.query );
  19746. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  19747. i --;
  19748. this.renderer.info.updateTimestamp( type, duration );
  19749. }
  19750. }
  19751. }
  19752. getContext() {
  19753. return this.gl;
  19754. }
  19755. beginRender( renderContext ) {
  19756. const { gl } = this;
  19757. const renderContextData = this.get( renderContext );
  19758. //
  19759. //
  19760. this.initTimestampQuery( renderContext );
  19761. renderContextData.previousContext = this._currentContext;
  19762. this._currentContext = renderContext;
  19763. this._setFramebuffer( renderContext );
  19764. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  19765. //
  19766. if ( renderContext.viewport ) {
  19767. this.updateViewport( renderContext );
  19768. } else {
  19769. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19770. }
  19771. if ( renderContext.scissor ) {
  19772. const { x, y, width, height } = renderContext.scissorValue;
  19773. gl.scissor( x, renderContext.height - height - y, width, height );
  19774. }
  19775. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19776. if ( occlusionQueryCount > 0 ) {
  19777. // Get a reference to the array of objects with queries. The renderContextData property
  19778. // can be changed by another render pass before the async reading of all previous queries complete
  19779. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  19780. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  19781. renderContextData.lastOcclusionObject = null;
  19782. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  19783. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  19784. renderContextData.occlusionQueryIndex = 0;
  19785. }
  19786. }
  19787. finishRender( renderContext ) {
  19788. const { gl, state } = this;
  19789. const renderContextData = this.get( renderContext );
  19790. const previousContext = renderContextData.previousContext;
  19791. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19792. if ( occlusionQueryCount > 0 ) {
  19793. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  19794. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  19795. }
  19796. this.resolveOccludedAsync( renderContext );
  19797. }
  19798. const textures = renderContext.textures;
  19799. if ( textures !== null ) {
  19800. for ( let i = 0; i < textures.length; i ++ ) {
  19801. const texture = textures[ i ];
  19802. if ( texture.generateMipmaps ) {
  19803. this.generateMipmaps( texture );
  19804. }
  19805. }
  19806. }
  19807. this._currentContext = previousContext;
  19808. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  19809. const renderTargetContextData = this.get( renderContext.renderTarget );
  19810. const { samples } = renderContext.renderTarget;
  19811. if ( samples > 0 ) {
  19812. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19813. const mask = gl.COLOR_BUFFER_BIT;
  19814. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19815. const textures = renderContext.textures;
  19816. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19817. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19818. for ( let i = 0; i < textures.length; i ++ ) {
  19819. // TODO Add support for MRT
  19820. if ( renderContext.scissor ) {
  19821. const { x, y, width, height } = renderContext.scissorValue;
  19822. const viewY = renderContext.height - height - y;
  19823. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  19824. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  19825. } else {
  19826. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  19827. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  19828. }
  19829. }
  19830. }
  19831. }
  19832. if ( previousContext !== null ) {
  19833. this._setFramebuffer( previousContext );
  19834. if ( previousContext.viewport ) {
  19835. this.updateViewport( previousContext );
  19836. } else {
  19837. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19838. }
  19839. }
  19840. this.prepareTimestampBuffer( renderContext );
  19841. }
  19842. resolveOccludedAsync( renderContext ) {
  19843. const renderContextData = this.get( renderContext );
  19844. // handle occlusion query results
  19845. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  19846. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  19847. const occluded = new WeakSet();
  19848. const { gl } = this;
  19849. renderContextData.currentOcclusionQueryObjects = null;
  19850. renderContextData.currentOcclusionQueries = null;
  19851. const check = () => {
  19852. let completed = 0;
  19853. // check all queries and requeue as appropriate
  19854. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  19855. const query = currentOcclusionQueries[ i ];
  19856. if ( query === null ) continue;
  19857. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  19858. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  19859. currentOcclusionQueries[ i ] = null;
  19860. gl.deleteQuery( query );
  19861. completed ++;
  19862. }
  19863. }
  19864. if ( completed < currentOcclusionQueries.length ) {
  19865. requestAnimationFrame( check );
  19866. } else {
  19867. renderContextData.occluded = occluded;
  19868. }
  19869. };
  19870. check();
  19871. }
  19872. }
  19873. isOccluded( renderContext, object ) {
  19874. const renderContextData = this.get( renderContext );
  19875. return renderContextData.occluded && renderContextData.occluded.has( object );
  19876. }
  19877. updateViewport( renderContext ) {
  19878. const gl = this.gl;
  19879. const { x, y, width, height } = renderContext.viewportValue;
  19880. gl.viewport( x, renderContext.height - height - y, width, height );
  19881. }
  19882. setScissorTest( boolean ) {
  19883. const gl = this.gl;
  19884. if ( boolean ) {
  19885. gl.enable( gl.SCISSOR_TEST );
  19886. } else {
  19887. gl.disable( gl.SCISSOR_TEST );
  19888. }
  19889. }
  19890. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  19891. const { gl } = this;
  19892. if ( descriptor === null ) {
  19893. const clearColor = this.getClearColor();
  19894. // premultiply alpha
  19895. clearColor.r *= clearColor.a;
  19896. clearColor.g *= clearColor.a;
  19897. clearColor.b *= clearColor.a;
  19898. descriptor = {
  19899. textures: null,
  19900. clearColorValue: clearColor
  19901. };
  19902. }
  19903. //
  19904. let clear = 0;
  19905. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  19906. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  19907. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  19908. if ( clear !== 0 ) {
  19909. let clearColor;
  19910. if ( descriptor.clearColorValue ) {
  19911. clearColor = descriptor.clearColorValue;
  19912. } else {
  19913. clearColor = this.getClearColor();
  19914. // premultiply alpha
  19915. clearColor.r *= clearColor.a;
  19916. clearColor.g *= clearColor.a;
  19917. clearColor.b *= clearColor.a;
  19918. }
  19919. if ( depth ) this.state.setDepthMask( true );
  19920. if ( descriptor.textures === null ) {
  19921. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  19922. gl.clear( clear );
  19923. } else {
  19924. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  19925. if ( color ) {
  19926. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  19927. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  19928. }
  19929. }
  19930. if ( depth && stencil ) {
  19931. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  19932. } else if ( depth ) {
  19933. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  19934. } else if ( stencil ) {
  19935. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  19936. }
  19937. }
  19938. }
  19939. }
  19940. beginCompute( computeGroup ) {
  19941. const { state, gl } = this;
  19942. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  19943. this.initTimestampQuery( computeGroup );
  19944. }
  19945. compute( computeGroup, computeNode, bindings, pipeline ) {
  19946. const { state, gl } = this;
  19947. if ( ! this.discard ) {
  19948. // required here to handle async behaviour of render.compute()
  19949. gl.enable( gl.RASTERIZER_DISCARD );
  19950. this.discard = true;
  19951. }
  19952. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  19953. const vaoKey = this._getVaoKey( null, attributes );
  19954. const vaoGPU = this.vaoCache[ vaoKey ];
  19955. if ( vaoGPU === undefined ) {
  19956. this._createVao( null, attributes );
  19957. } else {
  19958. gl.bindVertexArray( vaoGPU );
  19959. }
  19960. state.useProgram( programGPU );
  19961. this._bindUniforms( bindings );
  19962. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  19963. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  19964. gl.beginTransformFeedback( gl.POINTS );
  19965. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  19966. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  19967. } else {
  19968. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  19969. }
  19970. gl.endTransformFeedback();
  19971. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  19972. // switch active buffers
  19973. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  19974. const dualAttributeData = transformBuffers[ i ];
  19975. if ( dualAttributeData.pbo ) {
  19976. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  19977. }
  19978. dualAttributeData.switchBuffers();
  19979. }
  19980. }
  19981. finishCompute( computeGroup ) {
  19982. const gl = this.gl;
  19983. this.discard = false;
  19984. gl.disable( gl.RASTERIZER_DISCARD );
  19985. this.prepareTimestampBuffer( computeGroup );
  19986. if ( this._currentContext ) {
  19987. this._setFramebuffer( this._currentContext );
  19988. }
  19989. }
  19990. draw( renderObject/*, info*/ ) {
  19991. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  19992. const { programGPU } = this.get( pipeline );
  19993. const { gl, state } = this;
  19994. const contextData = this.get( context );
  19995. const drawParams = renderObject.getDrawParameters();
  19996. if ( drawParams === null ) return;
  19997. //
  19998. this._bindUniforms( renderObject.getBindings() );
  19999. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20000. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  20001. state.useProgram( programGPU );
  20002. //
  20003. const renderObjectData = this.get( renderObject );
  20004. let vaoGPU = renderObjectData.staticVao;
  20005. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  20006. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  20007. vaoGPU = this.vaoCache[ vaoKey ];
  20008. if ( vaoGPU === undefined ) {
  20009. let staticVao;
  20010. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  20011. if ( staticVao ) {
  20012. renderObjectData.staticVao = vaoGPU;
  20013. renderObjectData.geometryId = renderObject.geometry.id;
  20014. }
  20015. }
  20016. }
  20017. gl.bindVertexArray( vaoGPU );
  20018. //
  20019. const index = renderObject.getIndex();
  20020. //
  20021. const lastObject = contextData.lastOcclusionObject;
  20022. if ( lastObject !== object && lastObject !== undefined ) {
  20023. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  20024. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20025. contextData.occlusionQueryIndex ++;
  20026. }
  20027. if ( object.occlusionTest === true ) {
  20028. const query = gl.createQuery();
  20029. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  20030. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  20031. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  20032. }
  20033. contextData.lastOcclusionObject = object;
  20034. }
  20035. //
  20036. const renderer = this.bufferRenderer;
  20037. if ( object.isPoints ) renderer.mode = gl.POINTS;
  20038. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  20039. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  20040. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  20041. else {
  20042. if ( material.wireframe === true ) {
  20043. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  20044. renderer.mode = gl.LINES;
  20045. } else {
  20046. renderer.mode = gl.TRIANGLES;
  20047. }
  20048. }
  20049. //
  20050. const { vertexCount, instanceCount } = drawParams;
  20051. let { firstVertex } = drawParams;
  20052. renderer.object = object;
  20053. if ( index !== null ) {
  20054. firstVertex *= index.array.BYTES_PER_ELEMENT;
  20055. const indexData = this.get( index );
  20056. renderer.index = index.count;
  20057. renderer.type = indexData.type;
  20058. } else {
  20059. renderer.index = 0;
  20060. }
  20061. if ( object.isBatchedMesh ) {
  20062. if ( object._multiDrawInstances !== null ) {
  20063. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  20064. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  20065. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  20066. } else {
  20067. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  20068. }
  20069. } else if ( instanceCount > 1 ) {
  20070. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  20071. } else {
  20072. renderer.render( firstVertex, vertexCount );
  20073. }
  20074. //
  20075. gl.bindVertexArray( null );
  20076. }
  20077. needsRenderUpdate( /*renderObject*/ ) {
  20078. return false;
  20079. }
  20080. getRenderCacheKey( /*renderObject*/ ) {
  20081. return '';
  20082. }
  20083. // textures
  20084. createDefaultTexture( texture ) {
  20085. this.textureUtils.createDefaultTexture( texture );
  20086. }
  20087. createTexture( texture, options ) {
  20088. this.textureUtils.createTexture( texture, options );
  20089. }
  20090. updateTexture( texture, options ) {
  20091. this.textureUtils.updateTexture( texture, options );
  20092. }
  20093. generateMipmaps( texture ) {
  20094. this.textureUtils.generateMipmaps( texture );
  20095. }
  20096. destroyTexture( texture ) {
  20097. this.textureUtils.destroyTexture( texture );
  20098. }
  20099. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20100. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  20101. }
  20102. createSampler( /*texture*/ ) {
  20103. //console.warn( 'Abstract class.' );
  20104. }
  20105. destroySampler() {}
  20106. // node builder
  20107. createNodeBuilder( object, renderer ) {
  20108. return new GLSLNodeBuilder( object, renderer );
  20109. }
  20110. // program
  20111. createProgram( program ) {
  20112. const gl = this.gl;
  20113. const { stage, code } = program;
  20114. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  20115. gl.shaderSource( shader, code );
  20116. gl.compileShader( shader );
  20117. this.set( program, {
  20118. shaderGPU: shader
  20119. } );
  20120. }
  20121. destroyProgram( /*program*/ ) {
  20122. console.warn( 'Abstract class.' );
  20123. }
  20124. createRenderPipeline( renderObject, promises ) {
  20125. const gl = this.gl;
  20126. const pipeline = renderObject.pipeline;
  20127. // Program
  20128. const { fragmentProgram, vertexProgram } = pipeline;
  20129. const programGPU = gl.createProgram();
  20130. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20131. const vertexShader = this.get( vertexProgram ).shaderGPU;
  20132. gl.attachShader( programGPU, fragmentShader );
  20133. gl.attachShader( programGPU, vertexShader );
  20134. gl.linkProgram( programGPU );
  20135. this.set( pipeline, {
  20136. programGPU,
  20137. fragmentShader,
  20138. vertexShader
  20139. } );
  20140. if ( promises !== null && this.parallel ) {
  20141. const p = new Promise( ( resolve /*, reject*/ ) => {
  20142. const parallel = this.parallel;
  20143. const checkStatus = () => {
  20144. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  20145. this._completeCompile( renderObject, pipeline );
  20146. resolve();
  20147. } else {
  20148. requestAnimationFrame( checkStatus );
  20149. }
  20150. };
  20151. checkStatus();
  20152. } );
  20153. promises.push( p );
  20154. return;
  20155. }
  20156. this._completeCompile( renderObject, pipeline );
  20157. }
  20158. _handleSource( string, errorLine ) {
  20159. const lines = string.split( '\n' );
  20160. const lines2 = [];
  20161. const from = Math.max( errorLine - 6, 0 );
  20162. const to = Math.min( errorLine + 6, lines.length );
  20163. for ( let i = from; i < to; i ++ ) {
  20164. const line = i + 1;
  20165. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  20166. }
  20167. return lines2.join( '\n' );
  20168. }
  20169. _getShaderErrors( gl, shader, type ) {
  20170. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  20171. const errors = gl.getShaderInfoLog( shader ).trim();
  20172. if ( status && errors === '' ) return '';
  20173. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  20174. if ( errorMatches ) {
  20175. const errorLine = parseInt( errorMatches[ 1 ] );
  20176. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  20177. } else {
  20178. return errors;
  20179. }
  20180. }
  20181. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  20182. if ( this.renderer.debug.checkShaderErrors ) {
  20183. const gl = this.gl;
  20184. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  20185. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20186. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  20187. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  20188. } else {
  20189. // default error reporting
  20190. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  20191. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  20192. console.error(
  20193. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  20194. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  20195. 'Program Info Log: ' + programLog + '\n' +
  20196. vertexErrors + '\n' +
  20197. fragmentErrors
  20198. );
  20199. }
  20200. } else if ( programLog !== '' ) {
  20201. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  20202. }
  20203. }
  20204. }
  20205. _completeCompile( renderObject, pipeline ) {
  20206. const { state, gl } = this;
  20207. const pipelineData = this.get( pipeline );
  20208. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  20209. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20210. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20211. }
  20212. state.useProgram( programGPU );
  20213. // Bindings
  20214. const bindings = renderObject.getBindings();
  20215. this._setupBindings( bindings, programGPU );
  20216. //
  20217. this.set( pipeline, {
  20218. programGPU
  20219. } );
  20220. }
  20221. createComputePipeline( computePipeline, bindings ) {
  20222. const { state, gl } = this;
  20223. // Program
  20224. const fragmentProgram = {
  20225. stage: 'fragment',
  20226. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20227. };
  20228. this.createProgram( fragmentProgram );
  20229. const { computeProgram } = computePipeline;
  20230. const programGPU = gl.createProgram();
  20231. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20232. const vertexShader = this.get( computeProgram ).shaderGPU;
  20233. const transforms = computeProgram.transforms;
  20234. const transformVaryingNames = [];
  20235. const transformAttributeNodes = [];
  20236. for ( let i = 0; i < transforms.length; i ++ ) {
  20237. const transform = transforms[ i ];
  20238. transformVaryingNames.push( transform.varyingName );
  20239. transformAttributeNodes.push( transform.attributeNode );
  20240. }
  20241. gl.attachShader( programGPU, fragmentShader );
  20242. gl.attachShader( programGPU, vertexShader );
  20243. gl.transformFeedbackVaryings(
  20244. programGPU,
  20245. transformVaryingNames,
  20246. gl.SEPARATE_ATTRIBS
  20247. );
  20248. gl.linkProgram( programGPU );
  20249. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20250. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20251. }
  20252. state.useProgram( programGPU );
  20253. // Bindings
  20254. this._setupBindings( bindings, programGPU );
  20255. const attributeNodes = computeProgram.attributes;
  20256. const attributes = [];
  20257. const transformBuffers = [];
  20258. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20259. const attribute = attributeNodes[ i ].node.attribute;
  20260. attributes.push( attribute );
  20261. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20262. }
  20263. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20264. const attribute = transformAttributeNodes[ i ].attribute;
  20265. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20266. const attributeData = this.get( attribute );
  20267. transformBuffers.push( attributeData );
  20268. }
  20269. //
  20270. this.set( computePipeline, {
  20271. programGPU,
  20272. transformBuffers,
  20273. attributes
  20274. } );
  20275. }
  20276. createBindings( bindGroup, bindings ) {
  20277. if ( this._knownBindings.has( bindings ) === false ) {
  20278. this._knownBindings.add( bindings );
  20279. let uniformBuffers = 0;
  20280. let textures = 0;
  20281. for ( const bindGroup of bindings ) {
  20282. this.set( bindGroup, {
  20283. textures: textures,
  20284. uniformBuffers: uniformBuffers
  20285. } );
  20286. for ( const binding of bindGroup.bindings ) {
  20287. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20288. if ( binding.isSampledTexture ) textures ++;
  20289. }
  20290. }
  20291. }
  20292. this.updateBindings( bindGroup, bindings );
  20293. }
  20294. updateBindings( bindGroup /*, bindings*/ ) {
  20295. const { gl } = this;
  20296. const bindGroupData = this.get( bindGroup );
  20297. let i = bindGroupData.uniformBuffers;
  20298. let t = bindGroupData.textures;
  20299. for ( const binding of bindGroup.bindings ) {
  20300. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20301. const data = binding.buffer;
  20302. const bufferGPU = gl.createBuffer();
  20303. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20304. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20305. this.set( binding, {
  20306. index: i ++,
  20307. bufferGPU
  20308. } );
  20309. } else if ( binding.isSampledTexture ) {
  20310. const { textureGPU, glTextureType } = this.get( binding.texture );
  20311. this.set( binding, {
  20312. index: t ++,
  20313. textureGPU,
  20314. glTextureType
  20315. } );
  20316. }
  20317. }
  20318. }
  20319. updateBinding( binding ) {
  20320. const gl = this.gl;
  20321. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20322. const bindingData = this.get( binding );
  20323. const bufferGPU = bindingData.bufferGPU;
  20324. const data = binding.buffer;
  20325. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20326. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20327. }
  20328. }
  20329. // attributes
  20330. createIndexAttribute( attribute ) {
  20331. const gl = this.gl;
  20332. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20333. }
  20334. createAttribute( attribute ) {
  20335. if ( this.has( attribute ) ) return;
  20336. const gl = this.gl;
  20337. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20338. }
  20339. createStorageAttribute( attribute ) {
  20340. if ( this.has( attribute ) ) return;
  20341. const gl = this.gl;
  20342. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20343. }
  20344. updateAttribute( attribute ) {
  20345. this.attributeUtils.updateAttribute( attribute );
  20346. }
  20347. destroyAttribute( attribute ) {
  20348. this.attributeUtils.destroyAttribute( attribute );
  20349. }
  20350. updateSize() {
  20351. //console.warn( 'Abstract class.' );
  20352. }
  20353. hasFeature( name ) {
  20354. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20355. const extensions = this.extensions;
  20356. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20357. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20358. }
  20359. return false;
  20360. }
  20361. getMaxAnisotropy() {
  20362. return this.capabilities.getMaxAnisotropy();
  20363. }
  20364. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20365. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20366. }
  20367. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20368. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20369. }
  20370. _setFramebuffer( descriptor ) {
  20371. const { gl, state } = this;
  20372. let currentFrameBuffer = null;
  20373. if ( descriptor.textures !== null ) {
  20374. const renderTarget = descriptor.renderTarget;
  20375. const renderTargetContextData = this.get( renderTarget );
  20376. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20377. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20378. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20379. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20380. const cacheKey = getCacheKey( descriptor );
  20381. let fb;
  20382. if ( isCube ) {
  20383. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20384. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20385. } else {
  20386. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20387. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20388. }
  20389. if ( fb === undefined ) {
  20390. fb = gl.createFramebuffer();
  20391. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20392. const textures = descriptor.textures;
  20393. if ( isCube ) {
  20394. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20395. const { textureGPU } = this.get( textures[ 0 ] );
  20396. const cubeFace = this.renderer._activeCubeFace;
  20397. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20398. } else {
  20399. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20400. for ( let i = 0; i < textures.length; i ++ ) {
  20401. const texture = textures[ i ];
  20402. const textureData = this.get( texture );
  20403. textureData.renderTarget = descriptor.renderTarget;
  20404. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20405. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20406. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20407. }
  20408. state.drawBuffers( descriptor, fb );
  20409. }
  20410. if ( descriptor.depthTexture !== null ) {
  20411. const textureData = this.get( descriptor.depthTexture );
  20412. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20413. textureData.renderTarget = descriptor.renderTarget;
  20414. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20415. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20416. }
  20417. }
  20418. if ( samples > 0 ) {
  20419. if ( msaaFb === undefined ) {
  20420. const invalidationArray = [];
  20421. msaaFb = gl.createFramebuffer();
  20422. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20423. const msaaRenderbuffers = [];
  20424. const textures = descriptor.textures;
  20425. for ( let i = 0; i < textures.length; i ++ ) {
  20426. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20427. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20428. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20429. if ( depthBuffer ) {
  20430. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20431. invalidationArray.push( depthStyle );
  20432. }
  20433. const texture = descriptor.textures[ i ];
  20434. const textureData = this.get( texture );
  20435. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20436. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20437. }
  20438. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20439. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20440. if ( depthRenderbuffer === undefined ) {
  20441. depthRenderbuffer = gl.createRenderbuffer();
  20442. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20443. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20444. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20445. invalidationArray.push( depthStyle );
  20446. }
  20447. renderTargetContextData.invalidationArray = invalidationArray;
  20448. }
  20449. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20450. } else {
  20451. currentFrameBuffer = fb;
  20452. }
  20453. }
  20454. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20455. }
  20456. _getVaoKey( index, attributes ) {
  20457. let key = [];
  20458. if ( index !== null ) {
  20459. const indexData = this.get( index );
  20460. key += ':' + indexData.id;
  20461. }
  20462. for ( let i = 0; i < attributes.length; i ++ ) {
  20463. const attributeData = this.get( attributes[ i ] );
  20464. key += ':' + attributeData.id;
  20465. }
  20466. return key;
  20467. }
  20468. _createVao( index, attributes ) {
  20469. const { gl } = this;
  20470. const vaoGPU = gl.createVertexArray();
  20471. let key = '';
  20472. let staticVao = true;
  20473. gl.bindVertexArray( vaoGPU );
  20474. if ( index !== null ) {
  20475. const indexData = this.get( index );
  20476. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20477. key += ':' + indexData.id;
  20478. }
  20479. for ( let i = 0; i < attributes.length; i ++ ) {
  20480. const attribute = attributes[ i ];
  20481. const attributeData = this.get( attribute );
  20482. key += ':' + attributeData.id;
  20483. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20484. gl.enableVertexAttribArray( i );
  20485. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20486. let stride, offset;
  20487. if ( attribute.isInterleavedBufferAttribute === true ) {
  20488. stride = attribute.data.stride * attributeData.bytesPerElement;
  20489. offset = attribute.offset * attributeData.bytesPerElement;
  20490. } else {
  20491. stride = 0;
  20492. offset = 0;
  20493. }
  20494. if ( attributeData.isInteger ) {
  20495. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20496. } else {
  20497. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20498. }
  20499. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20500. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20501. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20502. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20503. }
  20504. }
  20505. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20506. this.vaoCache[ key ] = vaoGPU;
  20507. return { vaoGPU, staticVao };
  20508. }
  20509. _getTransformFeedback( transformBuffers ) {
  20510. let key = '';
  20511. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20512. key += ':' + transformBuffers[ i ].id;
  20513. }
  20514. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20515. if ( transformFeedbackGPU !== undefined ) {
  20516. return transformFeedbackGPU;
  20517. }
  20518. const { gl } = this;
  20519. transformFeedbackGPU = gl.createTransformFeedback();
  20520. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20521. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20522. const attributeData = transformBuffers[ i ];
  20523. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20524. }
  20525. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20526. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20527. return transformFeedbackGPU;
  20528. }
  20529. _setupBindings( bindings, programGPU ) {
  20530. const gl = this.gl;
  20531. for ( const bindGroup of bindings ) {
  20532. for ( const binding of bindGroup.bindings ) {
  20533. const bindingData = this.get( binding );
  20534. const index = bindingData.index;
  20535. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20536. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20537. gl.uniformBlockBinding( programGPU, location, index );
  20538. } else if ( binding.isSampledTexture ) {
  20539. const location = gl.getUniformLocation( programGPU, binding.name );
  20540. gl.uniform1i( location, index );
  20541. }
  20542. }
  20543. }
  20544. }
  20545. _bindUniforms( bindings ) {
  20546. const { gl, state } = this;
  20547. for ( const bindGroup of bindings ) {
  20548. for ( const binding of bindGroup.bindings ) {
  20549. const bindingData = this.get( binding );
  20550. const index = bindingData.index;
  20551. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20552. // TODO USE bindBufferRange to group multiple uniform buffers
  20553. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  20554. } else if ( binding.isSampledTexture ) {
  20555. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  20556. }
  20557. }
  20558. }
  20559. }
  20560. dispose() {
  20561. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  20562. }
  20563. }
  20564. class Sampler extends Binding {
  20565. constructor( name, texture ) {
  20566. super( name );
  20567. this.texture = texture;
  20568. this.version = texture ? texture.version : 0;
  20569. this.isSampler = true;
  20570. }
  20571. }
  20572. class NodeSampler extends Sampler {
  20573. constructor( name, textureNode, groupNode ) {
  20574. super( name, textureNode ? textureNode.value : null );
  20575. this.textureNode = textureNode;
  20576. this.groupNode = groupNode;
  20577. }
  20578. update() {
  20579. this.texture = this.textureNode.value;
  20580. }
  20581. }
  20582. class StorageBuffer extends Buffer {
  20583. constructor( name, attribute ) {
  20584. super( name, attribute ? attribute.array : null );
  20585. this.attribute = attribute;
  20586. this.isStorageBuffer = true;
  20587. }
  20588. }
  20589. let _id = 0;
  20590. class NodeStorageBuffer extends StorageBuffer {
  20591. constructor( nodeUniform, groupNode ) {
  20592. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  20593. this.nodeUniform = nodeUniform;
  20594. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  20595. this.groupNode = groupNode;
  20596. }
  20597. get buffer() {
  20598. return this.nodeUniform.value;
  20599. }
  20600. }
  20601. class WebGPUTexturePassUtils extends DataMap {
  20602. constructor( device ) {
  20603. super();
  20604. this.device = device;
  20605. const mipmapVertexSource = `
  20606. struct VarysStruct {
  20607. @builtin( position ) Position: vec4<f32>,
  20608. @location( 0 ) vTex : vec2<f32>
  20609. };
  20610. @vertex
  20611. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  20612. var Varys : VarysStruct;
  20613. var pos = array< vec2<f32>, 4 >(
  20614. vec2<f32>( -1.0, 1.0 ),
  20615. vec2<f32>( 1.0, 1.0 ),
  20616. vec2<f32>( -1.0, -1.0 ),
  20617. vec2<f32>( 1.0, -1.0 )
  20618. );
  20619. var tex = array< vec2<f32>, 4 >(
  20620. vec2<f32>( 0.0, 0.0 ),
  20621. vec2<f32>( 1.0, 0.0 ),
  20622. vec2<f32>( 0.0, 1.0 ),
  20623. vec2<f32>( 1.0, 1.0 )
  20624. );
  20625. Varys.vTex = tex[ vertexIndex ];
  20626. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  20627. return Varys;
  20628. }
  20629. `;
  20630. const mipmapFragmentSource = `
  20631. @group( 0 ) @binding( 0 )
  20632. var imgSampler : sampler;
  20633. @group( 0 ) @binding( 1 )
  20634. var img : texture_2d<f32>;
  20635. @fragment
  20636. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20637. return textureSample( img, imgSampler, vTex );
  20638. }
  20639. `;
  20640. const flipYFragmentSource = `
  20641. @group( 0 ) @binding( 0 )
  20642. var imgSampler : sampler;
  20643. @group( 0 ) @binding( 1 )
  20644. var img : texture_2d<f32>;
  20645. @fragment
  20646. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20647. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  20648. }
  20649. `;
  20650. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  20651. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  20652. // We'll need a new pipeline for every texture format used.
  20653. this.transferPipelines = {};
  20654. this.flipYPipelines = {};
  20655. this.mipmapVertexShaderModule = device.createShaderModule( {
  20656. label: 'mipmapVertex',
  20657. code: mipmapVertexSource
  20658. } );
  20659. this.mipmapFragmentShaderModule = device.createShaderModule( {
  20660. label: 'mipmapFragment',
  20661. code: mipmapFragmentSource
  20662. } );
  20663. this.flipYFragmentShaderModule = device.createShaderModule( {
  20664. label: 'flipYFragment',
  20665. code: flipYFragmentSource
  20666. } );
  20667. }
  20668. getTransferPipeline( format ) {
  20669. let pipeline = this.transferPipelines[ format ];
  20670. if ( pipeline === undefined ) {
  20671. pipeline = this.device.createRenderPipeline( {
  20672. label: `mipmap-${ format }`,
  20673. vertex: {
  20674. module: this.mipmapVertexShaderModule,
  20675. entryPoint: 'main'
  20676. },
  20677. fragment: {
  20678. module: this.mipmapFragmentShaderModule,
  20679. entryPoint: 'main',
  20680. targets: [ { format } ]
  20681. },
  20682. primitive: {
  20683. topology: GPUPrimitiveTopology.TriangleStrip,
  20684. stripIndexFormat: GPUIndexFormat.Uint32
  20685. },
  20686. layout: 'auto'
  20687. } );
  20688. this.transferPipelines[ format ] = pipeline;
  20689. }
  20690. return pipeline;
  20691. }
  20692. getFlipYPipeline( format ) {
  20693. let pipeline = this.flipYPipelines[ format ];
  20694. if ( pipeline === undefined ) {
  20695. pipeline = this.device.createRenderPipeline( {
  20696. label: `flipY-${ format }`,
  20697. vertex: {
  20698. module: this.mipmapVertexShaderModule,
  20699. entryPoint: 'main'
  20700. },
  20701. fragment: {
  20702. module: this.flipYFragmentShaderModule,
  20703. entryPoint: 'main',
  20704. targets: [ { format } ]
  20705. },
  20706. primitive: {
  20707. topology: GPUPrimitiveTopology.TriangleStrip,
  20708. stripIndexFormat: GPUIndexFormat.Uint32
  20709. },
  20710. layout: 'auto'
  20711. } );
  20712. this.flipYPipelines[ format ] = pipeline;
  20713. }
  20714. return pipeline;
  20715. }
  20716. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20717. const format = textureGPUDescriptor.format;
  20718. const { width, height } = textureGPUDescriptor.size;
  20719. const transferPipeline = this.getTransferPipeline( format );
  20720. const flipYPipeline = this.getFlipYPipeline( format );
  20721. const tempTexture = this.device.createTexture( {
  20722. size: { width, height, depthOrArrayLayers: 1 },
  20723. format,
  20724. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  20725. } );
  20726. const srcView = textureGPU.createView( {
  20727. baseMipLevel: 0,
  20728. mipLevelCount: 1,
  20729. dimension: GPUTextureViewDimension.TwoD,
  20730. baseArrayLayer
  20731. } );
  20732. const dstView = tempTexture.createView( {
  20733. baseMipLevel: 0,
  20734. mipLevelCount: 1,
  20735. dimension: GPUTextureViewDimension.TwoD,
  20736. baseArrayLayer: 0
  20737. } );
  20738. const commandEncoder = this.device.createCommandEncoder( {} );
  20739. const pass = ( pipeline, sourceView, destinationView ) => {
  20740. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20741. const bindGroup = this.device.createBindGroup( {
  20742. layout: bindGroupLayout,
  20743. entries: [ {
  20744. binding: 0,
  20745. resource: this.flipYSampler
  20746. }, {
  20747. binding: 1,
  20748. resource: sourceView
  20749. } ]
  20750. } );
  20751. const passEncoder = commandEncoder.beginRenderPass( {
  20752. colorAttachments: [ {
  20753. view: destinationView,
  20754. loadOp: GPULoadOp.Clear,
  20755. storeOp: GPUStoreOp.Store,
  20756. clearValue: [ 0, 0, 0, 0 ]
  20757. } ]
  20758. } );
  20759. passEncoder.setPipeline( pipeline );
  20760. passEncoder.setBindGroup( 0, bindGroup );
  20761. passEncoder.draw( 4, 1, 0, 0 );
  20762. passEncoder.end();
  20763. };
  20764. pass( transferPipeline, srcView, dstView );
  20765. pass( flipYPipeline, dstView, srcView );
  20766. this.device.queue.submit( [ commandEncoder.finish() ] );
  20767. tempTexture.destroy();
  20768. }
  20769. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20770. const textureData = this.get( textureGPU );
  20771. if ( textureData.useCount === undefined ) {
  20772. textureData.useCount = 0;
  20773. textureData.layers = [];
  20774. }
  20775. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  20776. const commandEncoder = this.device.createCommandEncoder( {} );
  20777. this._mipmapRunBundles( commandEncoder, passes );
  20778. this.device.queue.submit( [ commandEncoder.finish() ] );
  20779. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  20780. textureData.useCount ++;
  20781. }
  20782. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  20783. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  20784. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20785. let srcView = textureGPU.createView( {
  20786. baseMipLevel: 0,
  20787. mipLevelCount: 1,
  20788. dimension: GPUTextureViewDimension.TwoD,
  20789. baseArrayLayer
  20790. } );
  20791. const passes = [];
  20792. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  20793. const bindGroup = this.device.createBindGroup( {
  20794. layout: bindGroupLayout,
  20795. entries: [ {
  20796. binding: 0,
  20797. resource: this.mipmapSampler
  20798. }, {
  20799. binding: 1,
  20800. resource: srcView
  20801. } ]
  20802. } );
  20803. const dstView = textureGPU.createView( {
  20804. baseMipLevel: i,
  20805. mipLevelCount: 1,
  20806. dimension: GPUTextureViewDimension.TwoD,
  20807. baseArrayLayer
  20808. } );
  20809. const passDescriptor = {
  20810. colorAttachments: [ {
  20811. view: dstView,
  20812. loadOp: GPULoadOp.Clear,
  20813. storeOp: GPUStoreOp.Store,
  20814. clearValue: [ 0, 0, 0, 0 ]
  20815. } ]
  20816. };
  20817. const passEncoder = this.device.createRenderBundleEncoder( {
  20818. colorFormats: [ textureGPUDescriptor.format ]
  20819. } );
  20820. passEncoder.setPipeline( pipeline );
  20821. passEncoder.setBindGroup( 0, bindGroup );
  20822. passEncoder.draw( 4, 1, 0, 0 );
  20823. passes.push( {
  20824. renderBundles: [ passEncoder.finish() ],
  20825. passDescriptor
  20826. } );
  20827. srcView = dstView;
  20828. }
  20829. return passes;
  20830. }
  20831. _mipmapRunBundles( commandEncoder, passes ) {
  20832. const levels = passes.length;
  20833. for ( let i = 0; i < levels; i ++ ) {
  20834. const pass = passes[ i ];
  20835. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  20836. passEncoder.executeBundles( pass.renderBundles );
  20837. passEncoder.end();
  20838. }
  20839. }
  20840. }
  20841. const _compareToWebGPU = {
  20842. [ NeverCompare ]: 'never',
  20843. [ LessCompare ]: 'less',
  20844. [ EqualCompare ]: 'equal',
  20845. [ LessEqualCompare ]: 'less-equal',
  20846. [ GreaterCompare ]: 'greater',
  20847. [ GreaterEqualCompare ]: 'greater-equal',
  20848. [ AlwaysCompare ]: 'always',
  20849. [ NotEqualCompare ]: 'not-equal'
  20850. };
  20851. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  20852. class WebGPUTextureUtils {
  20853. constructor( backend ) {
  20854. this.backend = backend;
  20855. this._passUtils = null;
  20856. this.defaultTexture = {};
  20857. this.defaultCubeTexture = {};
  20858. this.defaultVideoFrame = null;
  20859. this.colorBuffer = null;
  20860. this.depthTexture = new DepthTexture();
  20861. this.depthTexture.name = 'depthBuffer';
  20862. }
  20863. createSampler( texture ) {
  20864. const backend = this.backend;
  20865. const device = backend.device;
  20866. const textureGPU = backend.get( texture );
  20867. const samplerDescriptorGPU = {
  20868. addressModeU: this._convertAddressMode( texture.wrapS ),
  20869. addressModeV: this._convertAddressMode( texture.wrapT ),
  20870. addressModeW: this._convertAddressMode( texture.wrapR ),
  20871. magFilter: this._convertFilterMode( texture.magFilter ),
  20872. minFilter: this._convertFilterMode( texture.minFilter ),
  20873. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  20874. maxAnisotropy: 1
  20875. };
  20876. // anisotropy can only be used when all filter modes are set to linear.
  20877. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  20878. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  20879. }
  20880. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  20881. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  20882. }
  20883. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  20884. }
  20885. createDefaultTexture( texture ) {
  20886. let textureGPU;
  20887. const format = getFormat( texture );
  20888. if ( texture.isCubeTexture ) {
  20889. textureGPU = this._getDefaultCubeTextureGPU( format );
  20890. } else if ( texture.isVideoTexture ) {
  20891. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  20892. } else {
  20893. textureGPU = this._getDefaultTextureGPU( format );
  20894. }
  20895. this.backend.get( texture ).texture = textureGPU;
  20896. }
  20897. createTexture( texture, options = {} ) {
  20898. const backend = this.backend;
  20899. const textureData = backend.get( texture );
  20900. if ( textureData.initialized ) {
  20901. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  20902. }
  20903. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  20904. if ( options.levels === undefined ) options.levels = 1;
  20905. if ( options.depth === undefined ) options.depth = 1;
  20906. const { width, height, depth, levels } = options;
  20907. if ( texture.isFramebufferTexture ) {
  20908. if ( options.renderTarget ) {
  20909. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  20910. } else {
  20911. options.format = this.backend.utils.getPreferredCanvasFormat();
  20912. }
  20913. }
  20914. const dimension = this._getDimension( texture );
  20915. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  20916. textureData.format = format;
  20917. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  20918. sampleCount = backend.utils.getSampleCount( sampleCount );
  20919. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  20920. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  20921. if ( texture.isStorageTexture === true ) {
  20922. usage |= GPUTextureUsage.STORAGE_BINDING;
  20923. }
  20924. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  20925. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  20926. }
  20927. const textureDescriptorGPU = {
  20928. label: texture.name,
  20929. size: {
  20930. width: width,
  20931. height: height,
  20932. depthOrArrayLayers: depth,
  20933. },
  20934. mipLevelCount: levels,
  20935. sampleCount: primarySampleCount,
  20936. dimension: dimension,
  20937. format: format,
  20938. usage: usage
  20939. };
  20940. // texture creation
  20941. if ( texture.isVideoTexture ) {
  20942. const video = texture.source.data;
  20943. const videoFrame = new VideoFrame( video );
  20944. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  20945. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  20946. videoFrame.close();
  20947. textureData.externalTexture = video;
  20948. } else {
  20949. if ( format === undefined ) {
  20950. console.warn( 'WebGPURenderer: Texture format not supported.' );
  20951. return this.createDefaultTexture( texture );
  20952. }
  20953. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  20954. }
  20955. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  20956. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  20957. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  20958. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  20959. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  20960. }
  20961. textureData.initialized = true;
  20962. textureData.textureDescriptorGPU = textureDescriptorGPU;
  20963. }
  20964. destroyTexture( texture ) {
  20965. const backend = this.backend;
  20966. const textureData = backend.get( texture );
  20967. textureData.texture.destroy();
  20968. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  20969. backend.delete( texture );
  20970. }
  20971. destroySampler( texture ) {
  20972. const backend = this.backend;
  20973. const textureData = backend.get( texture );
  20974. delete textureData.sampler;
  20975. }
  20976. generateMipmaps( texture ) {
  20977. const textureData = this.backend.get( texture );
  20978. if ( texture.isCubeTexture ) {
  20979. for ( let i = 0; i < 6; i ++ ) {
  20980. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20981. }
  20982. } else {
  20983. const depth = texture.image.depth || 1;
  20984. for ( let i = 0; i < depth; i ++ ) {
  20985. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20986. }
  20987. }
  20988. }
  20989. getColorBuffer() {
  20990. if ( this.colorBuffer ) this.colorBuffer.destroy();
  20991. const backend = this.backend;
  20992. const { width, height } = backend.getDrawingBufferSize();
  20993. this.colorBuffer = backend.device.createTexture( {
  20994. label: 'colorBuffer',
  20995. size: {
  20996. width: width,
  20997. height: height,
  20998. depthOrArrayLayers: 1
  20999. },
  21000. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  21001. format: backend.utils.getPreferredCanvasFormat(),
  21002. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  21003. } );
  21004. return this.colorBuffer;
  21005. }
  21006. getDepthBuffer( depth = true, stencil = false ) {
  21007. const backend = this.backend;
  21008. const { width, height } = backend.getDrawingBufferSize();
  21009. const depthTexture = this.depthTexture;
  21010. const depthTextureGPU = backend.get( depthTexture ).texture;
  21011. let format, type;
  21012. if ( stencil ) {
  21013. format = DepthStencilFormat;
  21014. type = UnsignedInt248Type;
  21015. } else if ( depth ) {
  21016. format = DepthFormat;
  21017. type = UnsignedIntType;
  21018. }
  21019. if ( depthTextureGPU !== undefined ) {
  21020. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  21021. return depthTextureGPU;
  21022. }
  21023. this.destroyTexture( depthTexture );
  21024. }
  21025. depthTexture.name = 'depthBuffer';
  21026. depthTexture.format = format;
  21027. depthTexture.type = type;
  21028. depthTexture.image.width = width;
  21029. depthTexture.image.height = height;
  21030. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  21031. return backend.get( depthTexture ).texture;
  21032. }
  21033. updateTexture( texture, options ) {
  21034. const textureData = this.backend.get( texture );
  21035. const { textureDescriptorGPU } = textureData;
  21036. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  21037. return;
  21038. // transfer texture data
  21039. if ( texture.isDataTexture ) {
  21040. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21041. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  21042. for ( let i = 0; i < options.image.depth; i ++ ) {
  21043. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  21044. }
  21045. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  21046. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  21047. } else if ( texture.isCubeTexture ) {
  21048. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  21049. } else if ( texture.isVideoTexture ) {
  21050. const video = texture.source.data;
  21051. textureData.externalTexture = video;
  21052. } else {
  21053. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21054. }
  21055. //
  21056. textureData.version = texture.version;
  21057. if ( texture.onUpdate ) texture.onUpdate( texture );
  21058. }
  21059. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21060. const device = this.backend.device;
  21061. const textureData = this.backend.get( texture );
  21062. const textureGPU = textureData.texture;
  21063. const format = textureData.textureDescriptorGPU.format;
  21064. const bytesPerTexel = this._getBytesPerTexel( format );
  21065. let bytesPerRow = width * bytesPerTexel;
  21066. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  21067. const readBuffer = device.createBuffer(
  21068. {
  21069. size: width * height * bytesPerTexel,
  21070. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  21071. }
  21072. );
  21073. const encoder = device.createCommandEncoder();
  21074. encoder.copyTextureToBuffer(
  21075. {
  21076. texture: textureGPU,
  21077. origin: { x, y, z: faceIndex },
  21078. },
  21079. {
  21080. buffer: readBuffer,
  21081. bytesPerRow: bytesPerRow
  21082. },
  21083. {
  21084. width: width,
  21085. height: height
  21086. }
  21087. );
  21088. const typedArrayType = this._getTypedArrayType( format );
  21089. device.queue.submit( [ encoder.finish() ] );
  21090. await readBuffer.mapAsync( GPUMapMode.READ );
  21091. const buffer = readBuffer.getMappedRange();
  21092. return new typedArrayType( buffer );
  21093. }
  21094. _isEnvironmentTexture( texture ) {
  21095. const mapping = texture.mapping;
  21096. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  21097. }
  21098. _getDefaultTextureGPU( format ) {
  21099. let defaultTexture = this.defaultTexture[ format ];
  21100. if ( defaultTexture === undefined ) {
  21101. const texture = new Texture();
  21102. texture.minFilter = NearestFilter;
  21103. texture.magFilter = NearestFilter;
  21104. this.createTexture( texture, { width: 1, height: 1, format } );
  21105. this.defaultTexture[ format ] = defaultTexture = texture;
  21106. }
  21107. return this.backend.get( defaultTexture ).texture;
  21108. }
  21109. _getDefaultCubeTextureGPU( format ) {
  21110. let defaultCubeTexture = this.defaultTexture[ format ];
  21111. if ( defaultCubeTexture === undefined ) {
  21112. const texture = new CubeTexture();
  21113. texture.minFilter = NearestFilter;
  21114. texture.magFilter = NearestFilter;
  21115. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  21116. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  21117. }
  21118. return this.backend.get( defaultCubeTexture ).texture;
  21119. }
  21120. _getDefaultVideoFrame() {
  21121. let defaultVideoFrame = this.defaultVideoFrame;
  21122. if ( defaultVideoFrame === null ) {
  21123. const init = {
  21124. timestamp: 0,
  21125. codedWidth: 1,
  21126. codedHeight: 1,
  21127. format: 'RGBA',
  21128. };
  21129. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  21130. }
  21131. return defaultVideoFrame;
  21132. }
  21133. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  21134. for ( let i = 0; i < 6; i ++ ) {
  21135. const image = images[ i ];
  21136. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  21137. if ( image.isDataTexture ) {
  21138. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21139. } else {
  21140. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21141. }
  21142. }
  21143. }
  21144. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  21145. const device = this.backend.device;
  21146. device.queue.copyExternalImageToTexture(
  21147. {
  21148. source: image
  21149. }, {
  21150. texture: textureGPU,
  21151. mipLevel: 0,
  21152. origin: { x: 0, y: 0, z: originDepth }
  21153. }, {
  21154. width: image.width,
  21155. height: image.height,
  21156. depthOrArrayLayers: 1
  21157. }
  21158. );
  21159. if ( flipY === true ) {
  21160. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21161. }
  21162. }
  21163. _getPassUtils() {
  21164. let passUtils = this._passUtils;
  21165. if ( passUtils === null ) {
  21166. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  21167. }
  21168. return passUtils;
  21169. }
  21170. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  21171. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  21172. }
  21173. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  21174. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  21175. }
  21176. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  21177. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21178. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  21179. const device = this.backend.device;
  21180. const data = image.data;
  21181. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  21182. const bytesPerRow = image.width * bytesPerTexel;
  21183. device.queue.writeTexture(
  21184. {
  21185. texture: textureGPU,
  21186. mipLevel: 0,
  21187. origin: { x: 0, y: 0, z: originDepth }
  21188. },
  21189. data,
  21190. {
  21191. offset: image.width * image.height * bytesPerTexel * depth,
  21192. bytesPerRow
  21193. },
  21194. {
  21195. width: image.width,
  21196. height: image.height,
  21197. depthOrArrayLayers: 1
  21198. } );
  21199. if ( flipY === true ) {
  21200. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21201. }
  21202. }
  21203. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  21204. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21205. const device = this.backend.device;
  21206. const blockData = this._getBlockData( textureDescriptorGPU.format );
  21207. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  21208. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21209. const mipmap = mipmaps[ i ];
  21210. const width = mipmap.width;
  21211. const height = mipmap.height;
  21212. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  21213. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  21214. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  21215. for ( let j = 0; j < depth; j ++ ) {
  21216. device.queue.writeTexture(
  21217. {
  21218. texture: textureGPU,
  21219. mipLevel: i,
  21220. origin: { x: 0, y: 0, z: j }
  21221. },
  21222. mipmap.data,
  21223. {
  21224. offset: j * bytesPerImage,
  21225. bytesPerRow,
  21226. rowsPerImage: Math.ceil( height / blockData.height )
  21227. },
  21228. {
  21229. width: Math.ceil( width / blockData.width ) * blockData.width,
  21230. height: Math.ceil( height / blockData.height ) * blockData.height,
  21231. depthOrArrayLayers: 1
  21232. }
  21233. );
  21234. }
  21235. }
  21236. }
  21237. _getBlockData( format ) {
  21238. // this method is only relevant for compressed texture formats
  21239. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21240. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21241. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21242. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21243. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21244. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21245. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21246. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21247. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21248. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21249. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21250. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21251. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21252. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21253. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21254. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21255. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21256. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21257. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21258. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21259. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21260. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21261. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21262. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21263. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21264. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21265. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21266. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21267. }
  21268. _convertAddressMode( value ) {
  21269. let addressMode = GPUAddressMode.ClampToEdge;
  21270. if ( value === RepeatWrapping ) {
  21271. addressMode = GPUAddressMode.Repeat;
  21272. } else if ( value === MirroredRepeatWrapping ) {
  21273. addressMode = GPUAddressMode.MirrorRepeat;
  21274. }
  21275. return addressMode;
  21276. }
  21277. _convertFilterMode( value ) {
  21278. let filterMode = GPUFilterMode.Linear;
  21279. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21280. filterMode = GPUFilterMode.Nearest;
  21281. }
  21282. return filterMode;
  21283. }
  21284. _getBytesPerTexel( format ) {
  21285. // 8-bit formats
  21286. if ( format === GPUTextureFormat.R8Unorm ||
  21287. format === GPUTextureFormat.R8Snorm ||
  21288. format === GPUTextureFormat.R8Uint ||
  21289. format === GPUTextureFormat.R8Sint ) return 1;
  21290. // 16-bit formats
  21291. if ( format === GPUTextureFormat.R16Uint ||
  21292. format === GPUTextureFormat.R16Sint ||
  21293. format === GPUTextureFormat.R16Float ||
  21294. format === GPUTextureFormat.RG8Unorm ||
  21295. format === GPUTextureFormat.RG8Snorm ||
  21296. format === GPUTextureFormat.RG8Uint ||
  21297. format === GPUTextureFormat.RG8Sint ) return 2;
  21298. // 32-bit formats
  21299. if ( format === GPUTextureFormat.R32Uint ||
  21300. format === GPUTextureFormat.R32Sint ||
  21301. format === GPUTextureFormat.R32Float ||
  21302. format === GPUTextureFormat.RG16Uint ||
  21303. format === GPUTextureFormat.RG16Sint ||
  21304. format === GPUTextureFormat.RG16Float ||
  21305. format === GPUTextureFormat.RGBA8Unorm ||
  21306. format === GPUTextureFormat.RGBA8UnormSRGB ||
  21307. format === GPUTextureFormat.RGBA8Snorm ||
  21308. format === GPUTextureFormat.RGBA8Uint ||
  21309. format === GPUTextureFormat.RGBA8Sint ||
  21310. format === GPUTextureFormat.BGRA8Unorm ||
  21311. format === GPUTextureFormat.BGRA8UnormSRGB ||
  21312. // Packed 32-bit formats
  21313. format === GPUTextureFormat.RGB9E5UFloat ||
  21314. format === GPUTextureFormat.RGB10A2Unorm ||
  21315. format === GPUTextureFormat.RG11B10UFloat ||
  21316. format === GPUTextureFormat.Depth32Float ||
  21317. format === GPUTextureFormat.Depth24Plus ||
  21318. format === GPUTextureFormat.Depth24PlusStencil8 ||
  21319. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  21320. // 64-bit formats
  21321. if ( format === GPUTextureFormat.RG32Uint ||
  21322. format === GPUTextureFormat.RG32Sint ||
  21323. format === GPUTextureFormat.RG32Float ||
  21324. format === GPUTextureFormat.RGBA16Uint ||
  21325. format === GPUTextureFormat.RGBA16Sint ||
  21326. format === GPUTextureFormat.RGBA16Float ) return 8;
  21327. // 128-bit formats
  21328. if ( format === GPUTextureFormat.RGBA32Uint ||
  21329. format === GPUTextureFormat.RGBA32Sint ||
  21330. format === GPUTextureFormat.RGBA32Float ) return 16;
  21331. }
  21332. _getTypedArrayType( format ) {
  21333. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  21334. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  21335. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  21336. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  21337. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  21338. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  21339. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  21340. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  21341. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  21342. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  21343. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  21344. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  21345. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  21346. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  21347. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  21348. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  21349. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  21350. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  21351. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  21352. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  21353. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  21354. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  21355. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  21356. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  21357. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  21358. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  21359. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  21360. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  21361. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  21362. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  21363. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  21364. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  21365. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  21366. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  21367. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  21368. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  21369. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  21370. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  21371. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  21372. }
  21373. _getDimension( texture ) {
  21374. let dimension;
  21375. if ( texture.isData3DTexture ) {
  21376. dimension = GPUTextureDimension.ThreeD;
  21377. } else {
  21378. dimension = GPUTextureDimension.TwoD;
  21379. }
  21380. return dimension;
  21381. }
  21382. }
  21383. function getFormat( texture, device = null ) {
  21384. const format = texture.format;
  21385. const type = texture.type;
  21386. const colorSpace = texture.colorSpace;
  21387. let formatGPU;
  21388. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  21389. switch ( format ) {
  21390. case RGBA_S3TC_DXT1_Format:
  21391. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  21392. break;
  21393. case RGBA_S3TC_DXT3_Format:
  21394. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  21395. break;
  21396. case RGBA_S3TC_DXT5_Format:
  21397. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  21398. break;
  21399. case RGB_ETC2_Format:
  21400. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  21401. break;
  21402. case RGBA_ETC2_EAC_Format:
  21403. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  21404. break;
  21405. case RGBA_ASTC_4x4_Format:
  21406. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  21407. break;
  21408. case RGBA_ASTC_5x4_Format:
  21409. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  21410. break;
  21411. case RGBA_ASTC_5x5_Format:
  21412. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  21413. break;
  21414. case RGBA_ASTC_6x5_Format:
  21415. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  21416. break;
  21417. case RGBA_ASTC_6x6_Format:
  21418. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  21419. break;
  21420. case RGBA_ASTC_8x5_Format:
  21421. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  21422. break;
  21423. case RGBA_ASTC_8x6_Format:
  21424. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  21425. break;
  21426. case RGBA_ASTC_8x8_Format:
  21427. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  21428. break;
  21429. case RGBA_ASTC_10x5_Format:
  21430. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  21431. break;
  21432. case RGBA_ASTC_10x6_Format:
  21433. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  21434. break;
  21435. case RGBA_ASTC_10x8_Format:
  21436. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  21437. break;
  21438. case RGBA_ASTC_10x10_Format:
  21439. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  21440. break;
  21441. case RGBA_ASTC_12x10_Format:
  21442. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  21443. break;
  21444. case RGBA_ASTC_12x12_Format:
  21445. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  21446. break;
  21447. case RGBAFormat:
  21448. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21449. break;
  21450. default:
  21451. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21452. }
  21453. } else {
  21454. switch ( format ) {
  21455. case RGBAFormat:
  21456. switch ( type ) {
  21457. case ByteType:
  21458. formatGPU = GPUTextureFormat.RGBA8Snorm;
  21459. break;
  21460. case ShortType:
  21461. formatGPU = GPUTextureFormat.RGBA16Sint;
  21462. break;
  21463. case UnsignedShortType:
  21464. formatGPU = GPUTextureFormat.RGBA16Uint;
  21465. break;
  21466. case UnsignedIntType:
  21467. formatGPU = GPUTextureFormat.RGBA32Uint;
  21468. break;
  21469. case IntType:
  21470. formatGPU = GPUTextureFormat.RGBA32Sint;
  21471. break;
  21472. case UnsignedByteType:
  21473. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21474. break;
  21475. case HalfFloatType:
  21476. formatGPU = GPUTextureFormat.RGBA16Float;
  21477. break;
  21478. case FloatType:
  21479. formatGPU = GPUTextureFormat.RGBA32Float;
  21480. break;
  21481. default:
  21482. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  21483. }
  21484. break;
  21485. case RGBFormat:
  21486. switch ( type ) {
  21487. case UnsignedInt5999Type:
  21488. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  21489. break;
  21490. default:
  21491. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  21492. }
  21493. break;
  21494. case RedFormat:
  21495. switch ( type ) {
  21496. case ByteType:
  21497. formatGPU = GPUTextureFormat.R8Snorm;
  21498. break;
  21499. case ShortType:
  21500. formatGPU = GPUTextureFormat.R16Sint;
  21501. break;
  21502. case UnsignedShortType:
  21503. formatGPU = GPUTextureFormat.R16Uint;
  21504. break;
  21505. case UnsignedIntType:
  21506. formatGPU = GPUTextureFormat.R32Uint;
  21507. break;
  21508. case IntType:
  21509. formatGPU = GPUTextureFormat.R32Sint;
  21510. break;
  21511. case UnsignedByteType:
  21512. formatGPU = GPUTextureFormat.R8Unorm;
  21513. break;
  21514. case HalfFloatType:
  21515. formatGPU = GPUTextureFormat.R16Float;
  21516. break;
  21517. case FloatType:
  21518. formatGPU = GPUTextureFormat.R32Float;
  21519. break;
  21520. default:
  21521. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  21522. }
  21523. break;
  21524. case RGFormat:
  21525. switch ( type ) {
  21526. case ByteType:
  21527. formatGPU = GPUTextureFormat.RG8Snorm;
  21528. break;
  21529. case ShortType:
  21530. formatGPU = GPUTextureFormat.RG16Sint;
  21531. break;
  21532. case UnsignedShortType:
  21533. formatGPU = GPUTextureFormat.RG16Uint;
  21534. break;
  21535. case UnsignedIntType:
  21536. formatGPU = GPUTextureFormat.RG32Uint;
  21537. break;
  21538. case IntType:
  21539. formatGPU = GPUTextureFormat.RG32Sint;
  21540. break;
  21541. case UnsignedByteType:
  21542. formatGPU = GPUTextureFormat.RG8Unorm;
  21543. break;
  21544. case HalfFloatType:
  21545. formatGPU = GPUTextureFormat.RG16Float;
  21546. break;
  21547. case FloatType:
  21548. formatGPU = GPUTextureFormat.RG32Float;
  21549. break;
  21550. default:
  21551. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  21552. }
  21553. break;
  21554. case DepthFormat:
  21555. switch ( type ) {
  21556. case UnsignedShortType:
  21557. formatGPU = GPUTextureFormat.Depth16Unorm;
  21558. break;
  21559. case UnsignedIntType:
  21560. formatGPU = GPUTextureFormat.Depth24Plus;
  21561. break;
  21562. case FloatType:
  21563. formatGPU = GPUTextureFormat.Depth32Float;
  21564. break;
  21565. default:
  21566. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  21567. }
  21568. break;
  21569. case DepthStencilFormat:
  21570. switch ( type ) {
  21571. case UnsignedInt248Type:
  21572. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  21573. break;
  21574. case FloatType:
  21575. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  21576. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  21577. }
  21578. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  21579. break;
  21580. default:
  21581. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  21582. }
  21583. break;
  21584. case RedIntegerFormat:
  21585. switch ( type ) {
  21586. case IntType:
  21587. formatGPU = GPUTextureFormat.R32Sint;
  21588. break;
  21589. case UnsignedIntType:
  21590. formatGPU = GPUTextureFormat.R32Uint;
  21591. break;
  21592. default:
  21593. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  21594. }
  21595. break;
  21596. case RGIntegerFormat:
  21597. switch ( type ) {
  21598. case IntType:
  21599. formatGPU = GPUTextureFormat.RG32Sint;
  21600. break;
  21601. case UnsignedIntType:
  21602. formatGPU = GPUTextureFormat.RG32Uint;
  21603. break;
  21604. default:
  21605. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  21606. }
  21607. break;
  21608. case RGBAIntegerFormat:
  21609. switch ( type ) {
  21610. case IntType:
  21611. formatGPU = GPUTextureFormat.RGBA32Sint;
  21612. break;
  21613. case UnsignedIntType:
  21614. formatGPU = GPUTextureFormat.RGBA32Uint;
  21615. break;
  21616. default:
  21617. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  21618. }
  21619. break;
  21620. default:
  21621. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21622. }
  21623. }
  21624. return formatGPU;
  21625. }
  21626. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  21627. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  21628. const wgslTypeLib$1 = {
  21629. 'f32': 'float',
  21630. 'i32': 'int',
  21631. 'u32': 'uint',
  21632. 'bool': 'bool',
  21633. 'vec2<f32>': 'vec2',
  21634. 'vec2<i32>': 'ivec2',
  21635. 'vec2<u32>': 'uvec2',
  21636. 'vec2<bool>': 'bvec2',
  21637. 'vec2f': 'vec2',
  21638. 'vec2i': 'ivec2',
  21639. 'vec2u': 'uvec2',
  21640. 'vec2b': 'bvec2',
  21641. 'vec3<f32>': 'vec3',
  21642. 'vec3<i32>': 'ivec3',
  21643. 'vec3<u32>': 'uvec3',
  21644. 'vec3<bool>': 'bvec3',
  21645. 'vec3f': 'vec3',
  21646. 'vec3i': 'ivec3',
  21647. 'vec3u': 'uvec3',
  21648. 'vec3b': 'bvec3',
  21649. 'vec4<f32>': 'vec4',
  21650. 'vec4<i32>': 'ivec4',
  21651. 'vec4<u32>': 'uvec4',
  21652. 'vec4<bool>': 'bvec4',
  21653. 'vec4f': 'vec4',
  21654. 'vec4i': 'ivec4',
  21655. 'vec4u': 'uvec4',
  21656. 'vec4b': 'bvec4',
  21657. 'mat2x2<f32>': 'mat2',
  21658. 'mat2x2f': 'mat2',
  21659. 'mat3x3<f32>': 'mat3',
  21660. 'mat3x3f': 'mat3',
  21661. 'mat4x4<f32>': 'mat4',
  21662. 'mat4x4f': 'mat4',
  21663. 'sampler': 'sampler',
  21664. 'texture_1d': 'texture',
  21665. 'texture_2d': 'texture',
  21666. 'texture_2d_array': 'texture',
  21667. 'texture_multisampled_2d': 'cubeTexture',
  21668. 'texture_depth_2d': 'depthTexture',
  21669. 'texture_3d': 'texture3D',
  21670. 'texture_cube': 'cubeTexture',
  21671. 'texture_cube_array': 'cubeTexture',
  21672. 'texture_storage_1d': 'storageTexture',
  21673. 'texture_storage_2d': 'storageTexture',
  21674. 'texture_storage_2d_array': 'storageTexture',
  21675. 'texture_storage_3d': 'storageTexture'
  21676. };
  21677. const parse = ( source ) => {
  21678. source = source.trim();
  21679. const declaration = source.match( declarationRegexp );
  21680. if ( declaration !== null && declaration.length === 4 ) {
  21681. const inputsCode = declaration[ 2 ];
  21682. const propsMatches = [];
  21683. let match = null;
  21684. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  21685. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  21686. }
  21687. // Process matches to correctly pair names and types
  21688. const inputs = [];
  21689. for ( let i = 0; i < propsMatches.length; i ++ ) {
  21690. const { name, type } = propsMatches[ i ];
  21691. let resolvedType = type;
  21692. if ( resolvedType.startsWith( 'ptr' ) ) {
  21693. resolvedType = 'pointer';
  21694. } else {
  21695. if ( resolvedType.startsWith( 'texture' ) ) {
  21696. resolvedType = type.split( '<' )[ 0 ];
  21697. }
  21698. resolvedType = wgslTypeLib$1[ resolvedType ];
  21699. }
  21700. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  21701. }
  21702. const blockCode = source.substring( declaration[ 0 ].length );
  21703. const outputType = declaration[ 3 ] || 'void';
  21704. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21705. const type = wgslTypeLib$1[ outputType ] || outputType;
  21706. return {
  21707. type,
  21708. inputs,
  21709. name,
  21710. inputsCode,
  21711. blockCode,
  21712. outputType
  21713. };
  21714. } else {
  21715. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  21716. }
  21717. };
  21718. class WGSLNodeFunction extends NodeFunction {
  21719. constructor( source ) {
  21720. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  21721. super( type, inputs, name );
  21722. this.inputsCode = inputsCode;
  21723. this.blockCode = blockCode;
  21724. this.outputType = outputType;
  21725. }
  21726. getCode( name = this.name ) {
  21727. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  21728. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  21729. }
  21730. }
  21731. class WGSLNodeParser extends NodeParser {
  21732. parseFunction( source ) {
  21733. return new WGSLNodeFunction( source );
  21734. }
  21735. }
  21736. // GPUShaderStage is not defined in browsers not supporting WebGPU
  21737. const GPUShaderStage = self.GPUShaderStage;
  21738. const wrapNames = {
  21739. [ RepeatWrapping ]: 'repeat',
  21740. [ ClampToEdgeWrapping ]: 'clamp',
  21741. [ MirroredRepeatWrapping ]: 'mirror'
  21742. };
  21743. const gpuShaderStageLib = {
  21744. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  21745. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  21746. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  21747. };
  21748. const supports = {
  21749. instance: true,
  21750. swizzleAssign: false,
  21751. storageBuffer: true
  21752. };
  21753. const wgslFnOpLib = {
  21754. '^^': 'tsl_xor'
  21755. };
  21756. const wgslTypeLib = {
  21757. float: 'f32',
  21758. int: 'i32',
  21759. uint: 'u32',
  21760. bool: 'bool',
  21761. color: 'vec3<f32>',
  21762. vec2: 'vec2<f32>',
  21763. ivec2: 'vec2<i32>',
  21764. uvec2: 'vec2<u32>',
  21765. bvec2: 'vec2<bool>',
  21766. vec3: 'vec3<f32>',
  21767. ivec3: 'vec3<i32>',
  21768. uvec3: 'vec3<u32>',
  21769. bvec3: 'vec3<bool>',
  21770. vec4: 'vec4<f32>',
  21771. ivec4: 'vec4<i32>',
  21772. uvec4: 'vec4<u32>',
  21773. bvec4: 'vec4<bool>',
  21774. mat2: 'mat2x2<f32>',
  21775. mat3: 'mat3x3<f32>',
  21776. mat4: 'mat4x4<f32>'
  21777. };
  21778. const wgslCodeCache = {};
  21779. const wgslPolyfill = {
  21780. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  21781. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  21782. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  21783. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  21784. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  21785. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  21786. 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 ); }' ),
  21787. 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 ); }' ),
  21788. 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 ); }' ),
  21789. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  21790. 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 ); }' ),
  21791. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  21792. biquadraticTexture: new CodeNode( /* wgsl */`
  21793. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  21794. let res = vec2f( iRes );
  21795. let uvScaled = coord * res;
  21796. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  21797. // https://www.shadertoy.com/view/WtyXRy
  21798. let uv = uvWrapping - 0.5;
  21799. let iuv = floor( uv );
  21800. let f = fract( uv );
  21801. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  21802. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  21803. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  21804. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  21805. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  21806. }
  21807. ` )
  21808. };
  21809. const wgslMethods = {
  21810. dFdx: 'dpdx',
  21811. dFdy: '- dpdy',
  21812. mod_float: 'tsl_mod_float',
  21813. mod_vec2: 'tsl_mod_vec2',
  21814. mod_vec3: 'tsl_mod_vec3',
  21815. mod_vec4: 'tsl_mod_vec4',
  21816. equals_bool: 'tsl_equals_bool',
  21817. equals_bvec2: 'tsl_equals_bvec2',
  21818. equals_bvec3: 'tsl_equals_bvec3',
  21819. equals_bvec4: 'tsl_equals_bvec4',
  21820. inversesqrt: 'inverseSqrt',
  21821. bitcast: 'bitcast<f32>'
  21822. };
  21823. // WebGPU issue: does not support pow() with negative base on Windows
  21824. if ( /Windows/g.test( navigator.userAgent ) ) {
  21825. 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 ); }' );
  21826. 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 ] );
  21827. 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 ] );
  21828. 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 ] );
  21829. wgslMethods.pow_float = 'tsl_pow_float';
  21830. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  21831. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  21832. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  21833. }
  21834. //
  21835. let diagnostics = '';
  21836. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  21837. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  21838. }
  21839. //
  21840. class WGSLNodeBuilder extends NodeBuilder {
  21841. constructor( object, renderer ) {
  21842. super( object, renderer, new WGSLNodeParser() );
  21843. this.uniformGroups = {};
  21844. this.builtins = {};
  21845. this.directives = {};
  21846. this.scopedArrays = new Map();
  21847. }
  21848. needsToWorkingColorSpace( texture ) {
  21849. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  21850. }
  21851. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21852. if ( shaderStage === 'fragment' ) {
  21853. if ( depthSnippet ) {
  21854. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  21855. } else {
  21856. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  21857. }
  21858. } else if ( this.isFilteredTexture( texture ) ) {
  21859. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  21860. } else {
  21861. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  21862. }
  21863. }
  21864. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  21865. if ( shaderStage === 'fragment' ) {
  21866. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  21867. } else {
  21868. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  21869. }
  21870. }
  21871. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21872. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  21873. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  21874. } else if ( this.isFilteredTexture( texture ) ) {
  21875. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  21876. } else {
  21877. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  21878. }
  21879. }
  21880. generateWrapFunction( texture ) {
  21881. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  21882. let nodeCode = wgslCodeCache[ functionName ];
  21883. if ( nodeCode === undefined ) {
  21884. const includes = [];
  21885. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  21886. const addWrapSnippet = ( wrap, axis ) => {
  21887. if ( wrap === RepeatWrapping ) {
  21888. includes.push( wgslPolyfill.repeatWrapping_float );
  21889. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  21890. } else if ( wrap === ClampToEdgeWrapping ) {
  21891. includes.push( wgslPolyfill.clampWrapping_float );
  21892. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  21893. } else if ( wrap === MirroredRepeatWrapping ) {
  21894. includes.push( wgslPolyfill.mirrorWrapping_float );
  21895. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  21896. } else {
  21897. code += `\t\tcoord.${ axis }`;
  21898. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  21899. }
  21900. };
  21901. addWrapSnippet( texture.wrapS, 'x' );
  21902. code += ',\n';
  21903. addWrapSnippet( texture.wrapT, 'y' );
  21904. code += '\n\t);\n\n}\n';
  21905. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  21906. }
  21907. nodeCode.build( this );
  21908. return functionName;
  21909. }
  21910. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  21911. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  21912. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  21913. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  21914. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  21915. let textureDimensionsParams;
  21916. if ( texture.isMultisampleRenderTargetTexture === true ) {
  21917. textureDimensionsParams = textureProperty;
  21918. } else {
  21919. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  21920. }
  21921. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  21922. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  21923. }
  21924. return textureDimensionNode.build( this );
  21925. }
  21926. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  21927. this._include( 'biquadraticTexture' );
  21928. const wrapFunction = this.generateWrapFunction( texture );
  21929. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21930. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  21931. }
  21932. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  21933. const wrapFunction = this.generateWrapFunction( texture );
  21934. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21935. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  21936. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  21937. }
  21938. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  21939. if ( depthSnippet ) {
  21940. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  21941. } else {
  21942. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  21943. }
  21944. }
  21945. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  21946. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  21947. }
  21948. isSampleCompare( texture ) {
  21949. return texture.isDepthTexture === true && texture.compareFunction !== null;
  21950. }
  21951. isUnfilterable( texture ) {
  21952. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  21953. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  21954. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  21955. texture.isMultisampleRenderTargetTexture === true;
  21956. }
  21957. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21958. let snippet = null;
  21959. if ( texture.isVideoTexture === true ) {
  21960. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21961. } else if ( this.isUnfilterable( texture ) ) {
  21962. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  21963. } else {
  21964. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  21965. }
  21966. return snippet;
  21967. }
  21968. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21969. if ( shaderStage === 'fragment' ) {
  21970. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  21971. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  21972. } else {
  21973. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  21974. }
  21975. }
  21976. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21977. if ( shaderStage === 'fragment' ) {
  21978. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  21979. } else {
  21980. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  21981. }
  21982. }
  21983. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21984. let snippet = null;
  21985. if ( texture.isVideoTexture === true ) {
  21986. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21987. } else {
  21988. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  21989. }
  21990. return snippet;
  21991. }
  21992. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21993. if ( shaderStage === 'fragment' ) {
  21994. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  21995. } else {
  21996. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  21997. }
  21998. }
  21999. getPropertyName( node, shaderStage = this.shaderStage ) {
  22000. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  22001. if ( shaderStage === 'vertex' ) {
  22002. return `varyings.${ node.name }`;
  22003. }
  22004. } else if ( node.isNodeUniform === true ) {
  22005. const name = node.name;
  22006. const type = node.type;
  22007. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22008. return name;
  22009. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22010. return `NodeBuffer_${ node.id }.${name}`;
  22011. } else {
  22012. return node.groupNode.name + '.' + name;
  22013. }
  22014. }
  22015. return super.getPropertyName( node );
  22016. }
  22017. getOutputStructName() {
  22018. return 'output';
  22019. }
  22020. _getUniformGroupCount( shaderStage ) {
  22021. return Object.keys( this.uniforms[ shaderStage ] ).length;
  22022. }
  22023. getFunctionOperator( op ) {
  22024. const fnOp = wgslFnOpLib[ op ];
  22025. if ( fnOp !== undefined ) {
  22026. this._include( fnOp );
  22027. return fnOp;
  22028. }
  22029. return null;
  22030. }
  22031. getStorageAccess( node ) {
  22032. if ( node.isStorageTextureNode ) {
  22033. switch ( node.access ) {
  22034. case GPUStorageTextureAccess.ReadOnly:
  22035. return 'read';
  22036. case GPUStorageTextureAccess.WriteOnly:
  22037. return 'write';
  22038. default:
  22039. return 'read_write';
  22040. }
  22041. } else {
  22042. switch ( node.access ) {
  22043. case GPUBufferBindingType.Storage:
  22044. return 'read_write';
  22045. case GPUBufferBindingType.ReadOnlyStorage:
  22046. return 'read';
  22047. default:
  22048. return 'write';
  22049. }
  22050. }
  22051. }
  22052. getUniformFromNode( node, type, shaderStage, name = null ) {
  22053. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  22054. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  22055. if ( nodeData.uniformGPU === undefined ) {
  22056. let uniformGPU;
  22057. const group = node.groupNode;
  22058. const groupName = group.name;
  22059. const bindings = this.getBindGroupArray( groupName, shaderStage );
  22060. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22061. let texture = null;
  22062. if ( type === 'texture' || type === 'storageTexture' ) {
  22063. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22064. } else if ( type === 'cubeTexture' ) {
  22065. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22066. } else if ( type === 'texture3D' ) {
  22067. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22068. }
  22069. texture.store = node.isStorageTextureNode === true;
  22070. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22071. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  22072. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  22073. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22074. bindings.push( sampler, texture );
  22075. uniformGPU = [ sampler, texture ];
  22076. } else {
  22077. bindings.push( texture );
  22078. uniformGPU = [ texture ];
  22079. }
  22080. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22081. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  22082. const buffer = new bufferClass( node, group );
  22083. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22084. bindings.push( buffer );
  22085. uniformGPU = buffer;
  22086. } else {
  22087. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  22088. let uniformsGroup = uniformsStage[ groupName ];
  22089. if ( uniformsGroup === undefined ) {
  22090. uniformsGroup = new NodeUniformsGroup( groupName, group );
  22091. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22092. uniformsStage[ groupName ] = uniformsGroup;
  22093. bindings.push( uniformsGroup );
  22094. }
  22095. uniformGPU = this.getNodeUniform( uniformNode, type );
  22096. uniformsGroup.addUniform( uniformGPU );
  22097. }
  22098. nodeData.uniformGPU = uniformGPU;
  22099. }
  22100. return uniformNode;
  22101. }
  22102. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  22103. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  22104. if ( map.has( name ) === false ) {
  22105. map.set( name, {
  22106. name,
  22107. property,
  22108. type
  22109. } );
  22110. }
  22111. return property;
  22112. }
  22113. hasBuiltin( name, shaderStage = this.shaderStage ) {
  22114. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  22115. }
  22116. getVertexIndex() {
  22117. if ( this.shaderStage === 'vertex' ) {
  22118. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  22119. }
  22120. return 'vertexIndex';
  22121. }
  22122. buildFunctionCode( shaderNode ) {
  22123. const layout = shaderNode.layout;
  22124. const flowData = this.flowShaderNode( shaderNode );
  22125. const parameters = [];
  22126. for ( const input of layout.inputs ) {
  22127. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  22128. }
  22129. //
  22130. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  22131. ${ flowData.vars }
  22132. ${ flowData.code }
  22133. `;
  22134. if ( flowData.result ) {
  22135. code += `\treturn ${ flowData.result };\n`;
  22136. }
  22137. code += '\n}\n';
  22138. //
  22139. return code;
  22140. }
  22141. getInstanceIndex() {
  22142. if ( this.shaderStage === 'vertex' ) {
  22143. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  22144. }
  22145. return 'instanceIndex';
  22146. }
  22147. getInvocationLocalIndex() {
  22148. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  22149. }
  22150. getSubgroupSize() {
  22151. this.enableSubGroups();
  22152. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22153. }
  22154. getInvocationSubgroupIndex() {
  22155. this.enableSubGroups();
  22156. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  22157. }
  22158. getSubgroupIndex() {
  22159. this.enableSubGroups();
  22160. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  22161. }
  22162. getDrawIndex() {
  22163. return null;
  22164. }
  22165. getFrontFacing() {
  22166. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  22167. }
  22168. getFragCoord() {
  22169. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  22170. }
  22171. getFragDepth() {
  22172. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  22173. }
  22174. getClipDistance() {
  22175. return 'varyings.hw_clip_distances';
  22176. }
  22177. isFlipY() {
  22178. return false;
  22179. }
  22180. enableDirective( name, shaderStage = this.shaderStage ) {
  22181. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  22182. stage.add( name );
  22183. }
  22184. getDirectives( shaderStage ) {
  22185. const snippets = [];
  22186. const directives = this.directives[ shaderStage ];
  22187. if ( directives !== undefined ) {
  22188. for ( const directive of directives ) {
  22189. snippets.push( `enable ${directive};` );
  22190. }
  22191. }
  22192. return snippets.join( '\n' );
  22193. }
  22194. enableSubGroups() {
  22195. this.enableDirective( 'subgroups' );
  22196. }
  22197. enableSubgroupsF16() {
  22198. this.enableDirective( 'subgroups-f16' );
  22199. }
  22200. enableClipDistances() {
  22201. this.enableDirective( 'clip_distances' );
  22202. }
  22203. enableShaderF16() {
  22204. this.enableDirective( 'f16' );
  22205. }
  22206. enableDualSourceBlending() {
  22207. this.enableDirective( 'dual_source_blending' );
  22208. }
  22209. enableHardwareClipping( planeCount ) {
  22210. this.enableClipDistances();
  22211. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  22212. }
  22213. getBuiltins( shaderStage ) {
  22214. const snippets = [];
  22215. const builtins = this.builtins[ shaderStage ];
  22216. if ( builtins !== undefined ) {
  22217. for ( const { name, property, type } of builtins.values() ) {
  22218. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  22219. }
  22220. }
  22221. return snippets.join( ',\n\t' );
  22222. }
  22223. getScopedArray( name, scope, bufferType, bufferCount ) {
  22224. if ( this.scopedArrays.has( name ) === false ) {
  22225. this.scopedArrays.set( name, {
  22226. name,
  22227. scope,
  22228. bufferType,
  22229. bufferCount
  22230. } );
  22231. }
  22232. return name;
  22233. }
  22234. getScopedArrays( shaderStage ) {
  22235. if ( shaderStage !== 'compute' ) {
  22236. return;
  22237. }
  22238. const snippets = [];
  22239. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22240. const type = this.getType( bufferType );
  22241. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22242. }
  22243. return snippets.join( '\n' );
  22244. }
  22245. getAttributes( shaderStage ) {
  22246. const snippets = [];
  22247. if ( shaderStage === 'compute' ) {
  22248. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22249. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22250. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22251. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22252. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22253. this.enableDirective( 'subgroups', shaderStage );
  22254. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22255. }
  22256. }
  22257. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22258. const builtins = this.getBuiltins( 'attribute' );
  22259. if ( builtins ) snippets.push( builtins );
  22260. const attributes = this.getAttributesArray();
  22261. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22262. const attribute = attributes[ index ];
  22263. const name = attribute.name;
  22264. const type = this.getType( attribute.type );
  22265. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22266. }
  22267. }
  22268. return snippets.join( ',\n\t' );
  22269. }
  22270. getStructMembers( struct ) {
  22271. const snippets = [];
  22272. const members = struct.getMemberTypes();
  22273. for ( let i = 0; i < members.length; i ++ ) {
  22274. const member = members[ i ];
  22275. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22276. }
  22277. const builtins = this.getBuiltins( 'output' );
  22278. if ( builtins ) snippets.push( '\t' + builtins );
  22279. return snippets.join( ',\n' );
  22280. }
  22281. getStructs( shaderStage ) {
  22282. const snippets = [];
  22283. const structs = this.structs[ shaderStage ];
  22284. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22285. const struct = structs[ index ];
  22286. const name = struct.name;
  22287. let snippet = `\struct ${ name } {\n`;
  22288. snippet += this.getStructMembers( struct );
  22289. snippet += '\n}';
  22290. snippets.push( snippet );
  22291. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  22292. }
  22293. return snippets.join( '\n\n' );
  22294. }
  22295. getVar( type, name ) {
  22296. return `var ${ name } : ${ this.getType( type ) }`;
  22297. }
  22298. getVars( shaderStage ) {
  22299. const snippets = [];
  22300. const vars = this.vars[ shaderStage ];
  22301. if ( vars !== undefined ) {
  22302. for ( const variable of vars ) {
  22303. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  22304. }
  22305. }
  22306. return `\n${ snippets.join( '\n' ) }\n`;
  22307. }
  22308. getVaryings( shaderStage ) {
  22309. const snippets = [];
  22310. if ( shaderStage === 'vertex' ) {
  22311. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  22312. }
  22313. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  22314. const varyings = this.varyings;
  22315. const vars = this.vars[ shaderStage ];
  22316. for ( let index = 0; index < varyings.length; index ++ ) {
  22317. const varying = varyings[ index ];
  22318. if ( varying.needsInterpolation ) {
  22319. let attributesSnippet = `@location( ${index} )`;
  22320. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  22321. attributesSnippet += ' @interpolate( flat )';
  22322. }
  22323. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  22324. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  22325. vars.push( varying );
  22326. }
  22327. }
  22328. }
  22329. const builtins = this.getBuiltins( shaderStage );
  22330. if ( builtins ) snippets.push( builtins );
  22331. const code = snippets.join( ',\n\t' );
  22332. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  22333. }
  22334. getUniforms( shaderStage ) {
  22335. const uniforms = this.uniforms[ shaderStage ];
  22336. const bindingSnippets = [];
  22337. const bufferSnippets = [];
  22338. const structSnippets = [];
  22339. const uniformGroups = {};
  22340. for ( const uniform of uniforms ) {
  22341. const groupName = uniform.groupNode.name;
  22342. const uniformIndexes = this.bindingsIndexes[ groupName ];
  22343. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  22344. const texture = uniform.node.value;
  22345. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  22346. if ( this.isSampleCompare( texture ) ) {
  22347. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  22348. } else {
  22349. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  22350. }
  22351. }
  22352. let textureType;
  22353. let multisampled = '';
  22354. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22355. multisampled = '_multisampled';
  22356. }
  22357. if ( texture.isCubeTexture === true ) {
  22358. textureType = 'texture_cube<f32>';
  22359. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  22360. textureType = 'texture_2d_array<f32>';
  22361. } else if ( texture.isDepthTexture === true ) {
  22362. textureType = `texture_depth${multisampled}_2d`;
  22363. } else if ( texture.isVideoTexture === true ) {
  22364. textureType = 'texture_external';
  22365. } else if ( texture.isData3DTexture === true ) {
  22366. textureType = 'texture_3d<f32>';
  22367. } else if ( uniform.node.isStorageTextureNode === true ) {
  22368. const format = getFormat( texture );
  22369. const access = this.getStorageAccess( uniform.node );
  22370. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  22371. } else {
  22372. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  22373. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  22374. }
  22375. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  22376. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  22377. const bufferNode = uniform.node;
  22378. const bufferType = this.getType( bufferNode.bufferType );
  22379. const bufferCount = bufferNode.bufferCount;
  22380. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  22381. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  22382. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  22383. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  22384. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  22385. } else {
  22386. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  22387. const groupName = uniform.groupNode.name;
  22388. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  22389. index: uniformIndexes.binding ++,
  22390. id: uniformIndexes.group,
  22391. snippets: []
  22392. } );
  22393. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  22394. }
  22395. }
  22396. for ( const name in uniformGroups ) {
  22397. const group = uniformGroups[ name ];
  22398. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  22399. }
  22400. let code = bindingSnippets.join( '\n' );
  22401. code += bufferSnippets.join( '\n' );
  22402. code += structSnippets.join( '\n' );
  22403. return code;
  22404. }
  22405. buildCode() {
  22406. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  22407. this.sortBindingGroups();
  22408. for ( const shaderStage in shadersData ) {
  22409. const stageData = shadersData[ shaderStage ];
  22410. stageData.uniforms = this.getUniforms( shaderStage );
  22411. stageData.attributes = this.getAttributes( shaderStage );
  22412. stageData.varyings = this.getVaryings( shaderStage );
  22413. stageData.structs = this.getStructs( shaderStage );
  22414. stageData.vars = this.getVars( shaderStage );
  22415. stageData.codes = this.getCodes( shaderStage );
  22416. stageData.directives = this.getDirectives( shaderStage );
  22417. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  22418. //
  22419. let flow = '// code\n\n';
  22420. flow += this.flowCode[ shaderStage ];
  22421. const flowNodes = this.flowNodes[ shaderStage ];
  22422. const mainNode = flowNodes[ flowNodes.length - 1 ];
  22423. const outputNode = mainNode.outputNode;
  22424. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  22425. for ( const node of flowNodes ) {
  22426. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  22427. const slotName = node.name;
  22428. if ( slotName ) {
  22429. if ( flow.length > 0 ) flow += '\n';
  22430. flow += `\t// flow -> ${ slotName }\n\t`;
  22431. }
  22432. flow += `${ flowSlotData.code }\n\t`;
  22433. if ( node === mainNode && shaderStage !== 'compute' ) {
  22434. flow += '// result\n\n\t';
  22435. if ( shaderStage === 'vertex' ) {
  22436. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  22437. } else if ( shaderStage === 'fragment' ) {
  22438. if ( isOutputStruct ) {
  22439. stageData.returnType = outputNode.nodeType;
  22440. flow += `return ${ flowSlotData.result };`;
  22441. } else {
  22442. let structSnippet = '\t@location(0) color: vec4<f32>';
  22443. const builtins = this.getBuiltins( 'output' );
  22444. if ( builtins ) structSnippet += ',\n\t' + builtins;
  22445. stageData.returnType = 'OutputStruct';
  22446. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  22447. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  22448. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  22449. }
  22450. }
  22451. }
  22452. }
  22453. stageData.flow = flow;
  22454. }
  22455. if ( this.material !== null ) {
  22456. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  22457. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  22458. } else {
  22459. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  22460. }
  22461. }
  22462. getMethod( method, output = null ) {
  22463. let wgslMethod;
  22464. if ( output !== null ) {
  22465. wgslMethod = this._getWGSLMethod( method + '_' + output );
  22466. }
  22467. if ( wgslMethod === undefined ) {
  22468. wgslMethod = this._getWGSLMethod( method );
  22469. }
  22470. return wgslMethod || method;
  22471. }
  22472. getType( type ) {
  22473. return wgslTypeLib[ type ] || type;
  22474. }
  22475. isAvailable( name ) {
  22476. let result = supports[ name ];
  22477. if ( result === undefined ) {
  22478. if ( name === 'float32Filterable' ) {
  22479. result = this.renderer.hasFeature( 'float32-filterable' );
  22480. } else if ( name === 'clipDistance' ) {
  22481. result = this.renderer.hasFeature( 'clip-distances' );
  22482. }
  22483. supports[ name ] = result;
  22484. }
  22485. return result;
  22486. }
  22487. _getWGSLMethod( method ) {
  22488. if ( wgslPolyfill[ method ] !== undefined ) {
  22489. this._include( method );
  22490. }
  22491. return wgslMethods[ method ];
  22492. }
  22493. _include( name ) {
  22494. const codeNode = wgslPolyfill[ name ];
  22495. codeNode.build( this );
  22496. if ( this.currentFunctionNode !== null ) {
  22497. this.currentFunctionNode.includes.push( codeNode );
  22498. }
  22499. return codeNode;
  22500. }
  22501. _getWGSLVertexCode( shaderData ) {
  22502. return `${ this.getSignature() }
  22503. // directives
  22504. ${shaderData.directives}
  22505. // uniforms
  22506. ${shaderData.uniforms}
  22507. // varyings
  22508. ${shaderData.varyings}
  22509. var<private> varyings : VaryingsStruct;
  22510. // codes
  22511. ${shaderData.codes}
  22512. @vertex
  22513. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  22514. // vars
  22515. ${shaderData.vars}
  22516. // flow
  22517. ${shaderData.flow}
  22518. return varyings;
  22519. }
  22520. `;
  22521. }
  22522. _getWGSLFragmentCode( shaderData ) {
  22523. return `${ this.getSignature() }
  22524. // global
  22525. ${ diagnostics }
  22526. // uniforms
  22527. ${shaderData.uniforms}
  22528. // structs
  22529. ${shaderData.structs}
  22530. // codes
  22531. ${shaderData.codes}
  22532. @fragment
  22533. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  22534. // vars
  22535. ${shaderData.vars}
  22536. // flow
  22537. ${shaderData.flow}
  22538. }
  22539. `;
  22540. }
  22541. _getWGSLComputeCode( shaderData, workgroupSize ) {
  22542. return `${ this.getSignature() }
  22543. // directives
  22544. ${shaderData.directives}
  22545. // system
  22546. var<private> instanceIndex : u32;
  22547. // locals
  22548. ${shaderData.scopedArrays}
  22549. // uniforms
  22550. ${shaderData.uniforms}
  22551. // codes
  22552. ${shaderData.codes}
  22553. @compute @workgroup_size( ${workgroupSize} )
  22554. fn main( ${shaderData.attributes} ) {
  22555. // system
  22556. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  22557. // vars
  22558. ${shaderData.vars}
  22559. // flow
  22560. ${shaderData.flow}
  22561. }
  22562. `;
  22563. }
  22564. _getWGSLStruct( name, vars ) {
  22565. return `
  22566. struct ${name} {
  22567. ${vars}
  22568. };`;
  22569. }
  22570. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  22571. const structName = name + 'Struct';
  22572. const structSnippet = this._getWGSLStruct( structName, vars );
  22573. return `${structSnippet}
  22574. @binding( ${binding} ) @group( ${group} )
  22575. var<${access}> ${name} : ${structName};`;
  22576. }
  22577. }
  22578. class WebGPUUtils {
  22579. constructor( backend ) {
  22580. this.backend = backend;
  22581. }
  22582. getCurrentDepthStencilFormat( renderContext ) {
  22583. let format;
  22584. if ( renderContext.depthTexture !== null ) {
  22585. format = this.getTextureFormatGPU( renderContext.depthTexture );
  22586. } else if ( renderContext.depth && renderContext.stencil ) {
  22587. format = GPUTextureFormat.Depth24PlusStencil8;
  22588. } else if ( renderContext.depth ) {
  22589. format = GPUTextureFormat.Depth24Plus;
  22590. }
  22591. return format;
  22592. }
  22593. getTextureFormatGPU( texture ) {
  22594. return this.backend.get( texture ).format;
  22595. }
  22596. getCurrentColorFormat( renderContext ) {
  22597. let format;
  22598. if ( renderContext.textures !== null ) {
  22599. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  22600. } else {
  22601. format = this.getPreferredCanvasFormat(); // default context format
  22602. }
  22603. return format;
  22604. }
  22605. getCurrentColorSpace( renderContext ) {
  22606. if ( renderContext.textures !== null ) {
  22607. return renderContext.textures[ 0 ].colorSpace;
  22608. }
  22609. return this.backend.renderer.outputColorSpace;
  22610. }
  22611. getPrimitiveTopology( object, material ) {
  22612. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  22613. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  22614. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  22615. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  22616. }
  22617. getSampleCount( sampleCount ) {
  22618. let count = 1;
  22619. if ( sampleCount > 1 ) {
  22620. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  22621. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  22622. if ( count === 2 ) {
  22623. count = 4;
  22624. }
  22625. }
  22626. return count;
  22627. }
  22628. getSampleCountRenderContext( renderContext ) {
  22629. if ( renderContext.textures !== null ) {
  22630. return this.getSampleCount( renderContext.sampleCount );
  22631. }
  22632. return this.getSampleCount( this.backend.renderer.samples );
  22633. }
  22634. getPreferredCanvasFormat() {
  22635. // TODO: Remove this check when Quest 34.5 is out
  22636. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  22637. if ( navigator.userAgent.includes( 'Quest' ) ) {
  22638. return GPUTextureFormat.BGRA8Unorm;
  22639. } else {
  22640. return navigator.gpu.getPreferredCanvasFormat();
  22641. }
  22642. }
  22643. }
  22644. const typedArraysToVertexFormatPrefix = new Map( [
  22645. [ Int8Array, [ 'sint8', 'snorm8' ]],
  22646. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  22647. [ Int16Array, [ 'sint16', 'snorm16' ]],
  22648. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  22649. [ Int32Array, [ 'sint32', 'snorm32' ]],
  22650. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  22651. [ Float32Array, [ 'float32', ]],
  22652. ] );
  22653. const typedAttributeToVertexFormatPrefix = new Map( [
  22654. [ Float16BufferAttribute, [ 'float16', ]],
  22655. ] );
  22656. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  22657. [ Int32Array, 'sint32' ],
  22658. [ Int16Array, 'sint32' ], // patch for INT16
  22659. [ Uint32Array, 'uint32' ],
  22660. [ Uint16Array, 'uint32' ], // patch for UINT16
  22661. [ Float32Array, 'float32' ]
  22662. ] );
  22663. class WebGPUAttributeUtils {
  22664. constructor( backend ) {
  22665. this.backend = backend;
  22666. }
  22667. createAttribute( attribute, usage ) {
  22668. const bufferAttribute = this._getBufferAttribute( attribute );
  22669. const backend = this.backend;
  22670. const bufferData = backend.get( bufferAttribute );
  22671. let buffer = bufferData.buffer;
  22672. if ( buffer === undefined ) {
  22673. const device = backend.device;
  22674. let array = bufferAttribute.array;
  22675. // patch for INT16 and UINT16
  22676. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  22677. const tempArray = new Uint32Array( array.length );
  22678. for ( let i = 0; i < array.length; i ++ ) {
  22679. tempArray[ i ] = array[ i ];
  22680. }
  22681. array = tempArray;
  22682. }
  22683. bufferAttribute.array = array;
  22684. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  22685. array = new array.constructor( bufferAttribute.count * 4 );
  22686. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  22687. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  22688. }
  22689. // Update BufferAttribute
  22690. bufferAttribute.itemSize = 4;
  22691. bufferAttribute.array = array;
  22692. }
  22693. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  22694. buffer = device.createBuffer( {
  22695. label: bufferAttribute.name,
  22696. size: size,
  22697. usage: usage,
  22698. mappedAtCreation: true
  22699. } );
  22700. new array.constructor( buffer.getMappedRange() ).set( array );
  22701. buffer.unmap();
  22702. bufferData.buffer = buffer;
  22703. }
  22704. }
  22705. updateAttribute( attribute ) {
  22706. const bufferAttribute = this._getBufferAttribute( attribute );
  22707. const backend = this.backend;
  22708. const device = backend.device;
  22709. const buffer = backend.get( bufferAttribute ).buffer;
  22710. const array = bufferAttribute.array;
  22711. const updateRanges = bufferAttribute.updateRanges;
  22712. if ( updateRanges.length === 0 ) {
  22713. // Not using update ranges
  22714. device.queue.writeBuffer(
  22715. buffer,
  22716. 0,
  22717. array,
  22718. 0
  22719. );
  22720. } else {
  22721. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  22722. const range = updateRanges[ i ];
  22723. device.queue.writeBuffer(
  22724. buffer,
  22725. 0,
  22726. array,
  22727. range.start * array.BYTES_PER_ELEMENT,
  22728. range.count * array.BYTES_PER_ELEMENT
  22729. );
  22730. }
  22731. bufferAttribute.clearUpdateRanges();
  22732. }
  22733. }
  22734. createShaderVertexBuffers( renderObject ) {
  22735. const attributes = renderObject.getAttributes();
  22736. const vertexBuffers = new Map();
  22737. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  22738. const geometryAttribute = attributes[ slot ];
  22739. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  22740. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  22741. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  22742. if ( vertexBufferLayout === undefined ) {
  22743. let arrayStride, stepMode;
  22744. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  22745. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  22746. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22747. } else {
  22748. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  22749. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22750. }
  22751. // patch for INT16 and UINT16
  22752. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  22753. arrayStride = 4;
  22754. }
  22755. vertexBufferLayout = {
  22756. arrayStride,
  22757. attributes: [],
  22758. stepMode
  22759. };
  22760. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  22761. }
  22762. const format = this._getVertexFormat( geometryAttribute );
  22763. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  22764. vertexBufferLayout.attributes.push( {
  22765. shaderLocation: slot,
  22766. offset,
  22767. format
  22768. } );
  22769. }
  22770. return Array.from( vertexBuffers.values() );
  22771. }
  22772. destroyAttribute( attribute ) {
  22773. const backend = this.backend;
  22774. const data = backend.get( this._getBufferAttribute( attribute ) );
  22775. data.buffer.destroy();
  22776. backend.delete( attribute );
  22777. }
  22778. async getArrayBufferAsync( attribute ) {
  22779. const backend = this.backend;
  22780. const device = backend.device;
  22781. const data = backend.get( this._getBufferAttribute( attribute ) );
  22782. const bufferGPU = data.buffer;
  22783. const size = bufferGPU.size;
  22784. const readBufferGPU = device.createBuffer( {
  22785. label: attribute.name,
  22786. size,
  22787. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  22788. } );
  22789. const cmdEncoder = device.createCommandEncoder( {} );
  22790. cmdEncoder.copyBufferToBuffer(
  22791. bufferGPU,
  22792. 0,
  22793. readBufferGPU,
  22794. 0,
  22795. size
  22796. );
  22797. readBufferGPU.unmap();
  22798. const gpuCommands = cmdEncoder.finish();
  22799. device.queue.submit( [ gpuCommands ] );
  22800. await readBufferGPU.mapAsync( GPUMapMode.READ );
  22801. const arrayBuffer = readBufferGPU.getMappedRange();
  22802. return arrayBuffer;
  22803. }
  22804. _getVertexFormat( geometryAttribute ) {
  22805. const { itemSize, normalized } = geometryAttribute;
  22806. const ArrayType = geometryAttribute.array.constructor;
  22807. const AttributeType = geometryAttribute.constructor;
  22808. let format;
  22809. if ( itemSize == 1 ) {
  22810. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  22811. } else {
  22812. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  22813. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  22814. if ( prefix ) {
  22815. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  22816. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  22817. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  22818. if ( paddedItemSize % 1 ) {
  22819. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  22820. }
  22821. format = `${prefix}x${paddedItemSize}`;
  22822. }
  22823. }
  22824. if ( ! format ) {
  22825. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  22826. }
  22827. return format;
  22828. }
  22829. _getBufferAttribute( attribute ) {
  22830. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22831. return attribute;
  22832. }
  22833. }
  22834. class WebGPUBindingUtils {
  22835. constructor( backend ) {
  22836. this.backend = backend;
  22837. this.bindGroupLayoutCache = new WeakMap();
  22838. }
  22839. createBindingsLayout( bindGroup ) {
  22840. const backend = this.backend;
  22841. const device = backend.device;
  22842. const entries = [];
  22843. let index = 0;
  22844. for ( const binding of bindGroup.bindings ) {
  22845. const bindingGPU = {
  22846. binding: index ++,
  22847. visibility: binding.visibility
  22848. };
  22849. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  22850. const buffer = {}; // GPUBufferBindingLayout
  22851. if ( binding.isStorageBuffer ) {
  22852. buffer.type = binding.access;
  22853. }
  22854. bindingGPU.buffer = buffer;
  22855. } else if ( binding.isSampler ) {
  22856. const sampler = {}; // GPUSamplerBindingLayout
  22857. if ( binding.texture.isDepthTexture ) {
  22858. if ( binding.texture.compareFunction !== null ) {
  22859. sampler.type = 'comparison';
  22860. }
  22861. }
  22862. bindingGPU.sampler = sampler;
  22863. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  22864. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  22865. } else if ( binding.isSampledTexture && binding.store ) {
  22866. const format = this.backend.get( binding.texture ).texture.format;
  22867. const access = binding.access;
  22868. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  22869. } else if ( binding.isSampledTexture ) {
  22870. const texture = {}; // GPUTextureBindingLayout
  22871. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  22872. texture.multisampled = true;
  22873. }
  22874. if ( binding.texture.isDepthTexture ) {
  22875. texture.sampleType = GPUTextureSampleType.Depth;
  22876. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  22877. const type = binding.texture.type;
  22878. if ( type === IntType ) {
  22879. texture.sampleType = GPUTextureSampleType.SInt;
  22880. } else if ( type === UnsignedIntType ) {
  22881. texture.sampleType = GPUTextureSampleType.UInt;
  22882. } else if ( type === FloatType ) {
  22883. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  22884. texture.sampleType = GPUTextureSampleType.Float;
  22885. } else {
  22886. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  22887. }
  22888. }
  22889. }
  22890. if ( binding.isSampledCubeTexture ) {
  22891. texture.viewDimension = GPUTextureViewDimension.Cube;
  22892. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22893. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  22894. } else if ( binding.isSampledTexture3D ) {
  22895. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  22896. }
  22897. bindingGPU.texture = texture;
  22898. } else {
  22899. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  22900. }
  22901. entries.push( bindingGPU );
  22902. }
  22903. return device.createBindGroupLayout( { entries } );
  22904. }
  22905. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  22906. const { backend, bindGroupLayoutCache } = this;
  22907. const bindingsData = backend.get( bindGroup );
  22908. // setup (static) binding layout and (dynamic) binding group
  22909. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  22910. if ( bindLayoutGPU === undefined ) {
  22911. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  22912. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  22913. }
  22914. let bindGroupGPU;
  22915. if ( cacheIndex > 0 ) {
  22916. if ( bindingsData.groups === undefined ) {
  22917. bindingsData.groups = [];
  22918. bindingsData.versions = [];
  22919. }
  22920. if ( bindingsData.versions[ cacheIndex ] === version ) {
  22921. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  22922. }
  22923. }
  22924. if ( bindGroupGPU === undefined ) {
  22925. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  22926. if ( cacheIndex > 0 ) {
  22927. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  22928. bindingsData.versions[ cacheIndex ] = version;
  22929. }
  22930. }
  22931. bindingsData.group = bindGroupGPU;
  22932. bindingsData.layout = bindLayoutGPU;
  22933. }
  22934. updateBinding( binding ) {
  22935. const backend = this.backend;
  22936. const device = backend.device;
  22937. const buffer = binding.buffer;
  22938. const bufferGPU = backend.get( binding ).buffer;
  22939. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  22940. }
  22941. createBindGroup( bindGroup, layoutGPU ) {
  22942. const backend = this.backend;
  22943. const device = backend.device;
  22944. let bindingPoint = 0;
  22945. const entriesGPU = [];
  22946. for ( const binding of bindGroup.bindings ) {
  22947. if ( binding.isUniformBuffer ) {
  22948. const bindingData = backend.get( binding );
  22949. if ( bindingData.buffer === undefined ) {
  22950. const byteLength = binding.byteLength;
  22951. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  22952. const bufferGPU = device.createBuffer( {
  22953. label: 'bindingBuffer_' + binding.name,
  22954. size: byteLength,
  22955. usage: usage
  22956. } );
  22957. bindingData.buffer = bufferGPU;
  22958. }
  22959. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22960. } else if ( binding.isStorageBuffer ) {
  22961. const bindingData = backend.get( binding );
  22962. if ( bindingData.buffer === undefined ) {
  22963. const attribute = binding.attribute;
  22964. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  22965. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  22966. bindingData.buffer = backend.get( attribute ).buffer;
  22967. }
  22968. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22969. } else if ( binding.isSampler ) {
  22970. const textureGPU = backend.get( binding.texture );
  22971. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  22972. } else if ( binding.isSampledTexture ) {
  22973. const textureData = backend.get( binding.texture );
  22974. let resourceGPU;
  22975. if ( textureData.externalTexture !== undefined ) {
  22976. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  22977. } else {
  22978. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  22979. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  22980. resourceGPU = textureData[ propertyName ];
  22981. if ( resourceGPU === undefined ) {
  22982. const aspectGPU = GPUTextureAspect.All;
  22983. let dimensionViewGPU;
  22984. if ( binding.isSampledCubeTexture ) {
  22985. dimensionViewGPU = GPUTextureViewDimension.Cube;
  22986. } else if ( binding.isSampledTexture3D ) {
  22987. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  22988. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22989. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  22990. } else {
  22991. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  22992. }
  22993. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  22994. }
  22995. }
  22996. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  22997. }
  22998. bindingPoint ++;
  22999. }
  23000. return device.createBindGroup( {
  23001. label: 'bindGroup_' + bindGroup.name,
  23002. layout: layoutGPU,
  23003. entries: entriesGPU
  23004. } );
  23005. }
  23006. }
  23007. class WebGPUPipelineUtils {
  23008. constructor( backend ) {
  23009. this.backend = backend;
  23010. }
  23011. _getSampleCount( renderObjectContext ) {
  23012. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  23013. }
  23014. createRenderPipeline( renderObject, promises ) {
  23015. const { object, material, geometry, pipeline } = renderObject;
  23016. const { vertexProgram, fragmentProgram } = pipeline;
  23017. const backend = this.backend;
  23018. const device = backend.device;
  23019. const utils = backend.utils;
  23020. const pipelineData = backend.get( pipeline );
  23021. // bind group layouts
  23022. const bindGroupLayouts = [];
  23023. for ( const bindGroup of renderObject.getBindings() ) {
  23024. const bindingsData = backend.get( bindGroup );
  23025. bindGroupLayouts.push( bindingsData.layout );
  23026. }
  23027. // vertex buffers
  23028. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  23029. // blending
  23030. let blending;
  23031. if ( material.transparent === true && material.blending !== NoBlending ) {
  23032. blending = this._getBlending( material );
  23033. }
  23034. // stencil
  23035. let stencilFront = {};
  23036. if ( material.stencilWrite === true ) {
  23037. stencilFront = {
  23038. compare: this._getStencilCompare( material ),
  23039. failOp: this._getStencilOperation( material.stencilFail ),
  23040. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  23041. passOp: this._getStencilOperation( material.stencilZPass )
  23042. };
  23043. }
  23044. const colorWriteMask = this._getColorWriteMask( material );
  23045. const targets = [];
  23046. if ( renderObject.context.textures !== null ) {
  23047. const textures = renderObject.context.textures;
  23048. for ( let i = 0; i < textures.length; i ++ ) {
  23049. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  23050. targets.push( {
  23051. format: colorFormat,
  23052. blend: blending,
  23053. writeMask: colorWriteMask
  23054. } );
  23055. }
  23056. } else {
  23057. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23058. targets.push( {
  23059. format: colorFormat,
  23060. blend: blending,
  23061. writeMask: colorWriteMask
  23062. } );
  23063. }
  23064. const vertexModule = backend.get( vertexProgram ).module;
  23065. const fragmentModule = backend.get( fragmentProgram ).module;
  23066. const primitiveState = this._getPrimitiveState( object, geometry, material );
  23067. const depthCompare = this._getDepthCompare( material );
  23068. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23069. const sampleCount = this._getSampleCount( renderObject.context );
  23070. const pipelineDescriptor = {
  23071. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  23072. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  23073. fragment: Object.assign( {}, fragmentModule, { targets } ),
  23074. primitive: primitiveState,
  23075. multisample: {
  23076. count: sampleCount,
  23077. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  23078. },
  23079. layout: device.createPipelineLayout( {
  23080. bindGroupLayouts
  23081. } )
  23082. };
  23083. const depthStencil = {};
  23084. const renderDepth = renderObject.context.depth;
  23085. const renderStencil = renderObject.context.stencil;
  23086. if ( renderDepth === true || renderStencil === true ) {
  23087. if ( renderDepth === true ) {
  23088. depthStencil.format = depthStencilFormat;
  23089. depthStencil.depthWriteEnabled = material.depthWrite;
  23090. depthStencil.depthCompare = depthCompare;
  23091. }
  23092. if ( renderStencil === true ) {
  23093. depthStencil.stencilFront = stencilFront;
  23094. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  23095. depthStencil.stencilReadMask = material.stencilFuncMask;
  23096. depthStencil.stencilWriteMask = material.stencilWriteMask;
  23097. }
  23098. pipelineDescriptor.depthStencil = depthStencil;
  23099. }
  23100. if ( promises === null ) {
  23101. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  23102. } else {
  23103. const p = new Promise( ( resolve /*, reject*/ ) => {
  23104. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  23105. pipelineData.pipeline = pipeline;
  23106. resolve();
  23107. } );
  23108. } );
  23109. promises.push( p );
  23110. }
  23111. }
  23112. createBundleEncoder( renderContext ) {
  23113. const backend = this.backend;
  23114. const { utils, device } = backend;
  23115. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  23116. const colorFormat = utils.getCurrentColorFormat( renderContext );
  23117. const sampleCount = this._getSampleCount( renderContext );
  23118. const descriptor = {
  23119. label: 'renderBundleEncoder',
  23120. colorFormats: [ colorFormat ],
  23121. depthStencilFormat,
  23122. sampleCount
  23123. };
  23124. return device.createRenderBundleEncoder( descriptor );
  23125. }
  23126. createComputePipeline( pipeline, bindings ) {
  23127. const backend = this.backend;
  23128. const device = backend.device;
  23129. const computeProgram = backend.get( pipeline.computeProgram ).module;
  23130. const pipelineGPU = backend.get( pipeline );
  23131. // bind group layouts
  23132. const bindGroupLayouts = [];
  23133. for ( const bindingsGroup of bindings ) {
  23134. const bindingsData = backend.get( bindingsGroup );
  23135. bindGroupLayouts.push( bindingsData.layout );
  23136. }
  23137. pipelineGPU.pipeline = device.createComputePipeline( {
  23138. compute: computeProgram,
  23139. layout: device.createPipelineLayout( {
  23140. bindGroupLayouts
  23141. } )
  23142. } );
  23143. }
  23144. _getBlending( material ) {
  23145. let color, alpha;
  23146. const blending = material.blending;
  23147. const blendSrc = material.blendSrc;
  23148. const blendDst = material.blendDst;
  23149. const blendEquation = material.blendEquation;
  23150. if ( blending === CustomBlending ) {
  23151. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  23152. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  23153. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  23154. color = {
  23155. srcFactor: this._getBlendFactor( blendSrc ),
  23156. dstFactor: this._getBlendFactor( blendDst ),
  23157. operation: this._getBlendOperation( blendEquation )
  23158. };
  23159. alpha = {
  23160. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  23161. dstFactor: this._getBlendFactor( blendDstAlpha ),
  23162. operation: this._getBlendOperation( blendEquationAlpha )
  23163. };
  23164. } else {
  23165. const premultipliedAlpha = material.premultipliedAlpha;
  23166. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  23167. color = {
  23168. srcFactor: srcRGB,
  23169. dstFactor: dstRGB,
  23170. operation: GPUBlendOperation.Add
  23171. };
  23172. alpha = {
  23173. srcFactor: srcAlpha,
  23174. dstFactor: dstAlpha,
  23175. operation: GPUBlendOperation.Add
  23176. };
  23177. };
  23178. if ( premultipliedAlpha ) {
  23179. switch ( blending ) {
  23180. case NormalBlending:
  23181. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23182. break;
  23183. case AdditiveBlending:
  23184. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  23185. break;
  23186. case SubtractiveBlending:
  23187. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23188. break;
  23189. case MultiplyBlending:
  23190. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  23191. break;
  23192. }
  23193. } else {
  23194. switch ( blending ) {
  23195. case NormalBlending:
  23196. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23197. break;
  23198. case AdditiveBlending:
  23199. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  23200. break;
  23201. case SubtractiveBlending:
  23202. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23203. break;
  23204. case MultiplyBlending:
  23205. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  23206. break;
  23207. }
  23208. }
  23209. }
  23210. if ( color !== undefined && alpha !== undefined ) {
  23211. return { color, alpha };
  23212. } else {
  23213. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  23214. }
  23215. }
  23216. _getBlendFactor( blend ) {
  23217. let blendFactor;
  23218. switch ( blend ) {
  23219. case ZeroFactor:
  23220. blendFactor = GPUBlendFactor.Zero;
  23221. break;
  23222. case OneFactor:
  23223. blendFactor = GPUBlendFactor.One;
  23224. break;
  23225. case SrcColorFactor:
  23226. blendFactor = GPUBlendFactor.Src;
  23227. break;
  23228. case OneMinusSrcColorFactor:
  23229. blendFactor = GPUBlendFactor.OneMinusSrc;
  23230. break;
  23231. case SrcAlphaFactor:
  23232. blendFactor = GPUBlendFactor.SrcAlpha;
  23233. break;
  23234. case OneMinusSrcAlphaFactor:
  23235. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23236. break;
  23237. case DstColorFactor:
  23238. blendFactor = GPUBlendFactor.Dst;
  23239. break;
  23240. case OneMinusDstColorFactor:
  23241. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23242. break;
  23243. case DstAlphaFactor:
  23244. blendFactor = GPUBlendFactor.DstAlpha;
  23245. break;
  23246. case OneMinusDstAlphaFactor:
  23247. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23248. break;
  23249. case SrcAlphaSaturateFactor:
  23250. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23251. break;
  23252. case BlendColorFactor:
  23253. blendFactor = GPUBlendFactor.Constant;
  23254. break;
  23255. case OneMinusBlendColorFactor:
  23256. blendFactor = GPUBlendFactor.OneMinusConstant;
  23257. break;
  23258. default:
  23259. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23260. }
  23261. return blendFactor;
  23262. }
  23263. _getStencilCompare( material ) {
  23264. let stencilCompare;
  23265. const stencilFunc = material.stencilFunc;
  23266. switch ( stencilFunc ) {
  23267. case NeverStencilFunc:
  23268. stencilCompare = GPUCompareFunction.Never;
  23269. break;
  23270. case AlwaysStencilFunc:
  23271. stencilCompare = GPUCompareFunction.Always;
  23272. break;
  23273. case LessStencilFunc:
  23274. stencilCompare = GPUCompareFunction.Less;
  23275. break;
  23276. case LessEqualStencilFunc:
  23277. stencilCompare = GPUCompareFunction.LessEqual;
  23278. break;
  23279. case EqualStencilFunc:
  23280. stencilCompare = GPUCompareFunction.Equal;
  23281. break;
  23282. case GreaterEqualStencilFunc:
  23283. stencilCompare = GPUCompareFunction.GreaterEqual;
  23284. break;
  23285. case GreaterStencilFunc:
  23286. stencilCompare = GPUCompareFunction.Greater;
  23287. break;
  23288. case NotEqualStencilFunc:
  23289. stencilCompare = GPUCompareFunction.NotEqual;
  23290. break;
  23291. default:
  23292. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  23293. }
  23294. return stencilCompare;
  23295. }
  23296. _getStencilOperation( op ) {
  23297. let stencilOperation;
  23298. switch ( op ) {
  23299. case KeepStencilOp:
  23300. stencilOperation = GPUStencilOperation.Keep;
  23301. break;
  23302. case ZeroStencilOp:
  23303. stencilOperation = GPUStencilOperation.Zero;
  23304. break;
  23305. case ReplaceStencilOp:
  23306. stencilOperation = GPUStencilOperation.Replace;
  23307. break;
  23308. case InvertStencilOp:
  23309. stencilOperation = GPUStencilOperation.Invert;
  23310. break;
  23311. case IncrementStencilOp:
  23312. stencilOperation = GPUStencilOperation.IncrementClamp;
  23313. break;
  23314. case DecrementStencilOp:
  23315. stencilOperation = GPUStencilOperation.DecrementClamp;
  23316. break;
  23317. case IncrementWrapStencilOp:
  23318. stencilOperation = GPUStencilOperation.IncrementWrap;
  23319. break;
  23320. case DecrementWrapStencilOp:
  23321. stencilOperation = GPUStencilOperation.DecrementWrap;
  23322. break;
  23323. default:
  23324. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  23325. }
  23326. return stencilOperation;
  23327. }
  23328. _getBlendOperation( blendEquation ) {
  23329. let blendOperation;
  23330. switch ( blendEquation ) {
  23331. case AddEquation:
  23332. blendOperation = GPUBlendOperation.Add;
  23333. break;
  23334. case SubtractEquation:
  23335. blendOperation = GPUBlendOperation.Subtract;
  23336. break;
  23337. case ReverseSubtractEquation:
  23338. blendOperation = GPUBlendOperation.ReverseSubtract;
  23339. break;
  23340. case MinEquation:
  23341. blendOperation = GPUBlendOperation.Min;
  23342. break;
  23343. case MaxEquation:
  23344. blendOperation = GPUBlendOperation.Max;
  23345. break;
  23346. default:
  23347. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  23348. }
  23349. return blendOperation;
  23350. }
  23351. _getPrimitiveState( object, geometry, material ) {
  23352. const descriptor = {};
  23353. const utils = this.backend.utils;
  23354. descriptor.topology = utils.getPrimitiveTopology( object, material );
  23355. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  23356. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23357. }
  23358. switch ( material.side ) {
  23359. case FrontSide:
  23360. descriptor.frontFace = GPUFrontFace.CCW;
  23361. descriptor.cullMode = GPUCullMode.Back;
  23362. break;
  23363. case BackSide:
  23364. descriptor.frontFace = GPUFrontFace.CCW;
  23365. descriptor.cullMode = GPUCullMode.Front;
  23366. break;
  23367. case DoubleSide:
  23368. descriptor.frontFace = GPUFrontFace.CCW;
  23369. descriptor.cullMode = GPUCullMode.None;
  23370. break;
  23371. default:
  23372. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  23373. break;
  23374. }
  23375. return descriptor;
  23376. }
  23377. _getColorWriteMask( material ) {
  23378. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  23379. }
  23380. _getDepthCompare( material ) {
  23381. let depthCompare;
  23382. if ( material.depthTest === false ) {
  23383. depthCompare = GPUCompareFunction.Always;
  23384. } else {
  23385. const depthFunc = material.depthFunc;
  23386. switch ( depthFunc ) {
  23387. case NeverDepth:
  23388. depthCompare = GPUCompareFunction.Never;
  23389. break;
  23390. case AlwaysDepth:
  23391. depthCompare = GPUCompareFunction.Always;
  23392. break;
  23393. case LessDepth:
  23394. depthCompare = GPUCompareFunction.Less;
  23395. break;
  23396. case LessEqualDepth:
  23397. depthCompare = GPUCompareFunction.LessEqual;
  23398. break;
  23399. case EqualDepth:
  23400. depthCompare = GPUCompareFunction.Equal;
  23401. break;
  23402. case GreaterEqualDepth:
  23403. depthCompare = GPUCompareFunction.GreaterEqual;
  23404. break;
  23405. case GreaterDepth:
  23406. depthCompare = GPUCompareFunction.Greater;
  23407. break;
  23408. case NotEqualDepth:
  23409. depthCompare = GPUCompareFunction.NotEqual;
  23410. break;
  23411. default:
  23412. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  23413. }
  23414. }
  23415. return depthCompare;
  23416. }
  23417. }
  23418. /*// debugger tools
  23419. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  23420. //*/
  23421. //
  23422. class WebGPUBackend extends Backend {
  23423. constructor( parameters = {} ) {
  23424. super( parameters );
  23425. this.isWebGPUBackend = true;
  23426. // some parameters require default values other than "undefined"
  23427. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  23428. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  23429. this.trackTimestamp = ( parameters.trackTimestamp === true );
  23430. this.device = null;
  23431. this.context = null;
  23432. this.colorBuffer = null;
  23433. this.defaultRenderPassdescriptor = null;
  23434. this.utils = new WebGPUUtils( this );
  23435. this.attributeUtils = new WebGPUAttributeUtils( this );
  23436. this.bindingUtils = new WebGPUBindingUtils( this );
  23437. this.pipelineUtils = new WebGPUPipelineUtils( this );
  23438. this.textureUtils = new WebGPUTextureUtils( this );
  23439. this.occludedResolveCache = new Map();
  23440. }
  23441. async init( renderer ) {
  23442. await super.init( renderer );
  23443. //
  23444. const parameters = this.parameters;
  23445. // create the device if it is not passed with parameters
  23446. let device;
  23447. if ( parameters.device === undefined ) {
  23448. const adapterOptions = {
  23449. powerPreference: parameters.powerPreference
  23450. };
  23451. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  23452. if ( adapter === null ) {
  23453. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  23454. }
  23455. // feature support
  23456. const features = Object.values( GPUFeatureName );
  23457. const supportedFeatures = [];
  23458. for ( const name of features ) {
  23459. if ( adapter.features.has( name ) ) {
  23460. supportedFeatures.push( name );
  23461. }
  23462. }
  23463. const deviceDescriptor = {
  23464. requiredFeatures: supportedFeatures,
  23465. requiredLimits: parameters.requiredLimits
  23466. };
  23467. device = await adapter.requestDevice( deviceDescriptor );
  23468. } else {
  23469. device = parameters.device;
  23470. }
  23471. device.lost.then( ( info ) => {
  23472. const deviceLossInfo = {
  23473. api: 'WebGPU',
  23474. message: info.message || 'Unknown reason',
  23475. reason: info.reason || null,
  23476. originalEvent: info
  23477. };
  23478. renderer.onDeviceLost( deviceLossInfo );
  23479. } );
  23480. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  23481. this.device = device;
  23482. this.context = context;
  23483. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  23484. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  23485. this.context.configure( {
  23486. device: this.device,
  23487. format: this.utils.getPreferredCanvasFormat(),
  23488. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  23489. alphaMode: alphaMode
  23490. } );
  23491. this.updateSize();
  23492. }
  23493. get coordinateSystem() {
  23494. return WebGPUCoordinateSystem;
  23495. }
  23496. async getArrayBufferAsync( attribute ) {
  23497. return await this.attributeUtils.getArrayBufferAsync( attribute );
  23498. }
  23499. getContext() {
  23500. return this.context;
  23501. }
  23502. _getDefaultRenderPassDescriptor() {
  23503. let descriptor = this.defaultRenderPassdescriptor;
  23504. if ( descriptor === null ) {
  23505. const renderer = this.renderer;
  23506. descriptor = {
  23507. colorAttachments: [ {
  23508. view: null
  23509. } ],
  23510. };
  23511. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  23512. descriptor.depthStencilAttachment = {
  23513. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  23514. };
  23515. }
  23516. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23517. if ( this.renderer.samples > 0 ) {
  23518. colorAttachment.view = this.colorBuffer.createView();
  23519. } else {
  23520. colorAttachment.resolveTarget = undefined;
  23521. }
  23522. this.defaultRenderPassdescriptor = descriptor;
  23523. }
  23524. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23525. if ( this.renderer.samples > 0 ) {
  23526. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  23527. } else {
  23528. colorAttachment.view = this.context.getCurrentTexture().createView();
  23529. }
  23530. return descriptor;
  23531. }
  23532. _getRenderPassDescriptor( renderContext ) {
  23533. const renderTarget = renderContext.renderTarget;
  23534. const renderTargetData = this.get( renderTarget );
  23535. let descriptors = renderTargetData.descriptors;
  23536. if ( descriptors === undefined ||
  23537. renderTargetData.width !== renderTarget.width ||
  23538. renderTargetData.height !== renderTarget.height ||
  23539. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  23540. renderTargetData.samples !== renderTarget.samples
  23541. ) {
  23542. descriptors = {};
  23543. renderTargetData.descriptors = descriptors;
  23544. // dispose
  23545. const onDispose = () => {
  23546. renderTarget.removeEventListener( 'dispose', onDispose );
  23547. this.delete( renderTarget );
  23548. };
  23549. renderTarget.addEventListener( 'dispose', onDispose );
  23550. }
  23551. const cacheKey = renderContext.getCacheKey();
  23552. let descriptor = descriptors[ cacheKey ];
  23553. if ( descriptor === undefined ) {
  23554. const textures = renderContext.textures;
  23555. const colorAttachments = [];
  23556. for ( let i = 0; i < textures.length; i ++ ) {
  23557. const textureData = this.get( textures[ i ] );
  23558. const textureView = textureData.texture.createView( {
  23559. baseMipLevel: renderContext.activeMipmapLevel,
  23560. mipLevelCount: 1,
  23561. baseArrayLayer: renderContext.activeCubeFace,
  23562. dimension: GPUTextureViewDimension.TwoD
  23563. } );
  23564. let view, resolveTarget;
  23565. if ( textureData.msaaTexture !== undefined ) {
  23566. view = textureData.msaaTexture.createView();
  23567. resolveTarget = textureView;
  23568. } else {
  23569. view = textureView;
  23570. resolveTarget = undefined;
  23571. }
  23572. colorAttachments.push( {
  23573. view,
  23574. resolveTarget,
  23575. loadOp: GPULoadOp.Load,
  23576. storeOp: GPUStoreOp.Store
  23577. } );
  23578. }
  23579. descriptor = {
  23580. colorAttachments,
  23581. };
  23582. if ( renderContext.depth ) {
  23583. const depthTextureData = this.get( renderContext.depthTexture );
  23584. const depthStencilAttachment = {
  23585. view: depthTextureData.texture.createView()
  23586. };
  23587. descriptor.depthStencilAttachment = depthStencilAttachment;
  23588. }
  23589. descriptors[ cacheKey ] = descriptor;
  23590. renderTargetData.width = renderTarget.width;
  23591. renderTargetData.height = renderTarget.height;
  23592. renderTargetData.samples = renderTarget.samples;
  23593. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  23594. }
  23595. return descriptor;
  23596. }
  23597. beginRender( renderContext ) {
  23598. const renderContextData = this.get( renderContext );
  23599. const device = this.device;
  23600. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23601. let occlusionQuerySet;
  23602. if ( occlusionQueryCount > 0 ) {
  23603. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  23604. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  23605. // Get a reference to the array of objects with queries. The renderContextData property
  23606. // can be changed by another render pass before the buffer.mapAsyc() completes.
  23607. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  23608. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  23609. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  23610. //
  23611. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  23612. renderContextData.occlusionQuerySet = occlusionQuerySet;
  23613. renderContextData.occlusionQueryIndex = 0;
  23614. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  23615. renderContextData.lastOcclusionObject = null;
  23616. }
  23617. let descriptor;
  23618. if ( renderContext.textures === null ) {
  23619. descriptor = this._getDefaultRenderPassDescriptor();
  23620. } else {
  23621. descriptor = this._getRenderPassDescriptor( renderContext );
  23622. }
  23623. this.initTimestampQuery( renderContext, descriptor );
  23624. descriptor.occlusionQuerySet = occlusionQuerySet;
  23625. const depthStencilAttachment = descriptor.depthStencilAttachment;
  23626. if ( renderContext.textures !== null ) {
  23627. const colorAttachments = descriptor.colorAttachments;
  23628. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  23629. const colorAttachment = colorAttachments[ i ];
  23630. if ( renderContext.clearColor ) {
  23631. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  23632. colorAttachment.loadOp = GPULoadOp.Clear;
  23633. colorAttachment.storeOp = GPUStoreOp.Store;
  23634. } else {
  23635. colorAttachment.loadOp = GPULoadOp.Load;
  23636. colorAttachment.storeOp = GPUStoreOp.Store;
  23637. }
  23638. }
  23639. } else {
  23640. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23641. if ( renderContext.clearColor ) {
  23642. colorAttachment.clearValue = renderContext.clearColorValue;
  23643. colorAttachment.loadOp = GPULoadOp.Clear;
  23644. colorAttachment.storeOp = GPUStoreOp.Store;
  23645. } else {
  23646. colorAttachment.loadOp = GPULoadOp.Load;
  23647. colorAttachment.storeOp = GPUStoreOp.Store;
  23648. }
  23649. }
  23650. //
  23651. if ( renderContext.depth ) {
  23652. if ( renderContext.clearDepth ) {
  23653. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  23654. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23655. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23656. } else {
  23657. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23658. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23659. }
  23660. }
  23661. if ( renderContext.stencil ) {
  23662. if ( renderContext.clearStencil ) {
  23663. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  23664. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23665. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23666. } else {
  23667. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23668. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23669. }
  23670. }
  23671. //
  23672. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  23673. const currentPass = encoder.beginRenderPass( descriptor );
  23674. //
  23675. renderContextData.descriptor = descriptor;
  23676. renderContextData.encoder = encoder;
  23677. renderContextData.currentPass = currentPass;
  23678. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  23679. renderContextData.renderBundles = [];
  23680. //
  23681. if ( renderContext.viewport ) {
  23682. this.updateViewport( renderContext );
  23683. }
  23684. if ( renderContext.scissor ) {
  23685. const { x, y, width, height } = renderContext.scissorValue;
  23686. currentPass.setScissorRect( x, y, width, height );
  23687. }
  23688. }
  23689. finishRender( renderContext ) {
  23690. const renderContextData = this.get( renderContext );
  23691. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23692. if ( renderContextData.renderBundles.length > 0 ) {
  23693. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  23694. }
  23695. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  23696. renderContextData.currentPass.endOcclusionQuery();
  23697. }
  23698. renderContextData.currentPass.end();
  23699. if ( occlusionQueryCount > 0 ) {
  23700. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  23701. //
  23702. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  23703. if ( queryResolveBuffer === undefined ) {
  23704. queryResolveBuffer = this.device.createBuffer(
  23705. {
  23706. size: bufferSize,
  23707. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  23708. }
  23709. );
  23710. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  23711. }
  23712. //
  23713. const readBuffer = this.device.createBuffer(
  23714. {
  23715. size: bufferSize,
  23716. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23717. }
  23718. );
  23719. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  23720. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  23721. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  23722. renderContextData.occlusionQueryBuffer = readBuffer;
  23723. //
  23724. this.resolveOccludedAsync( renderContext );
  23725. }
  23726. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  23727. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  23728. //
  23729. if ( renderContext.textures !== null ) {
  23730. const textures = renderContext.textures;
  23731. for ( let i = 0; i < textures.length; i ++ ) {
  23732. const texture = textures[ i ];
  23733. if ( texture.generateMipmaps === true ) {
  23734. this.textureUtils.generateMipmaps( texture );
  23735. }
  23736. }
  23737. }
  23738. }
  23739. isOccluded( renderContext, object ) {
  23740. const renderContextData = this.get( renderContext );
  23741. return renderContextData.occluded && renderContextData.occluded.has( object );
  23742. }
  23743. async resolveOccludedAsync( renderContext ) {
  23744. const renderContextData = this.get( renderContext );
  23745. // handle occlusion query results
  23746. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  23747. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  23748. const occluded = new WeakSet();
  23749. renderContextData.currentOcclusionQueryObjects = null;
  23750. renderContextData.currentOcclusionQueryBuffer = null;
  23751. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  23752. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  23753. const results = new BigUint64Array( buffer );
  23754. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  23755. if ( results[ i ] !== BigInt( 0 ) ) {
  23756. occluded.add( currentOcclusionQueryObjects[ i ] );
  23757. }
  23758. }
  23759. currentOcclusionQueryBuffer.destroy();
  23760. renderContextData.occluded = occluded;
  23761. }
  23762. }
  23763. updateViewport( renderContext ) {
  23764. const { currentPass } = this.get( renderContext );
  23765. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  23766. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  23767. }
  23768. clear( color, depth, stencil, renderTargetData = null ) {
  23769. const device = this.device;
  23770. const renderer = this.renderer;
  23771. let colorAttachments = [];
  23772. let depthStencilAttachment;
  23773. let clearValue;
  23774. let supportsDepth;
  23775. let supportsStencil;
  23776. if ( color ) {
  23777. const clearColor = this.getClearColor();
  23778. if ( this.renderer.alpha === true ) {
  23779. // premultiply alpha
  23780. const a = clearColor.a;
  23781. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  23782. } else {
  23783. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  23784. }
  23785. }
  23786. if ( renderTargetData === null ) {
  23787. supportsDepth = renderer.depth;
  23788. supportsStencil = renderer.stencil;
  23789. const descriptor = this._getDefaultRenderPassDescriptor();
  23790. if ( color ) {
  23791. colorAttachments = descriptor.colorAttachments;
  23792. const colorAttachment = colorAttachments[ 0 ];
  23793. colorAttachment.clearValue = clearValue;
  23794. colorAttachment.loadOp = GPULoadOp.Clear;
  23795. colorAttachment.storeOp = GPUStoreOp.Store;
  23796. }
  23797. if ( supportsDepth || supportsStencil ) {
  23798. depthStencilAttachment = descriptor.depthStencilAttachment;
  23799. }
  23800. } else {
  23801. supportsDepth = renderTargetData.depth;
  23802. supportsStencil = renderTargetData.stencil;
  23803. if ( color ) {
  23804. for ( const texture of renderTargetData.textures ) {
  23805. const textureData = this.get( texture );
  23806. const textureView = textureData.texture.createView();
  23807. let view, resolveTarget;
  23808. if ( textureData.msaaTexture !== undefined ) {
  23809. view = textureData.msaaTexture.createView();
  23810. resolveTarget = textureView;
  23811. } else {
  23812. view = textureView;
  23813. resolveTarget = undefined;
  23814. }
  23815. colorAttachments.push( {
  23816. view,
  23817. resolveTarget,
  23818. clearValue,
  23819. loadOp: GPULoadOp.Clear,
  23820. storeOp: GPUStoreOp.Store
  23821. } );
  23822. }
  23823. }
  23824. if ( supportsDepth || supportsStencil ) {
  23825. const depthTextureData = this.get( renderTargetData.depthTexture );
  23826. depthStencilAttachment = {
  23827. view: depthTextureData.texture.createView()
  23828. };
  23829. }
  23830. }
  23831. //
  23832. if ( supportsDepth ) {
  23833. if ( depth ) {
  23834. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23835. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  23836. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23837. } else {
  23838. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23839. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23840. }
  23841. }
  23842. //
  23843. if ( supportsStencil ) {
  23844. if ( stencil ) {
  23845. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23846. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  23847. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23848. } else {
  23849. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23850. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23851. }
  23852. }
  23853. //
  23854. const encoder = device.createCommandEncoder( {} );
  23855. const currentPass = encoder.beginRenderPass( {
  23856. colorAttachments,
  23857. depthStencilAttachment
  23858. } );
  23859. currentPass.end();
  23860. device.queue.submit( [ encoder.finish() ] );
  23861. }
  23862. // compute
  23863. beginCompute( computeGroup ) {
  23864. const groupGPU = this.get( computeGroup );
  23865. const descriptor = {};
  23866. this.initTimestampQuery( computeGroup, descriptor );
  23867. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  23868. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  23869. }
  23870. compute( computeGroup, computeNode, bindings, pipeline ) {
  23871. const { passEncoderGPU } = this.get( computeGroup );
  23872. // pipeline
  23873. const pipelineGPU = this.get( pipeline ).pipeline;
  23874. passEncoderGPU.setPipeline( pipelineGPU );
  23875. // bind groups
  23876. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23877. const bindGroup = bindings[ i ];
  23878. const bindingsData = this.get( bindGroup );
  23879. passEncoderGPU.setBindGroup( i, bindingsData.group );
  23880. }
  23881. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  23882. const computeNodeData = this.get( computeNode );
  23883. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  23884. const { dispatchSize } = computeNodeData;
  23885. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  23886. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  23887. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  23888. } else {
  23889. dispatchSize.x = computeNode.dispatchCount;
  23890. }
  23891. passEncoderGPU.dispatchWorkgroups(
  23892. dispatchSize.x,
  23893. dispatchSize.y,
  23894. dispatchSize.z
  23895. );
  23896. }
  23897. finishCompute( computeGroup ) {
  23898. const groupData = this.get( computeGroup );
  23899. groupData.passEncoderGPU.end();
  23900. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  23901. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  23902. }
  23903. async waitForGPU() {
  23904. await this.device.queue.onSubmittedWorkDone();
  23905. }
  23906. // render object
  23907. draw( renderObject, info ) {
  23908. const { object, context, pipeline } = renderObject;
  23909. const bindings = renderObject.getBindings();
  23910. const renderContextData = this.get( context );
  23911. const pipelineGPU = this.get( pipeline ).pipeline;
  23912. const currentSets = renderContextData.currentSets;
  23913. const passEncoderGPU = renderContextData.currentPass;
  23914. const drawParams = renderObject.getDrawParameters();
  23915. if ( drawParams === null ) return;
  23916. // pipeline
  23917. if ( currentSets.pipeline !== pipelineGPU ) {
  23918. passEncoderGPU.setPipeline( pipelineGPU );
  23919. currentSets.pipeline = pipelineGPU;
  23920. }
  23921. // bind groups
  23922. const currentBindingGroups = currentSets.bindingGroups;
  23923. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23924. const bindGroup = bindings[ i ];
  23925. const bindingsData = this.get( bindGroup );
  23926. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  23927. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  23928. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  23929. }
  23930. }
  23931. // attributes
  23932. const index = renderObject.getIndex();
  23933. const hasIndex = ( index !== null );
  23934. // index
  23935. if ( hasIndex === true ) {
  23936. if ( currentSets.index !== index ) {
  23937. const buffer = this.get( index ).buffer;
  23938. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23939. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  23940. currentSets.index = index;
  23941. }
  23942. }
  23943. // vertex buffers
  23944. const vertexBuffers = renderObject.getVertexBuffers();
  23945. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  23946. const vertexBuffer = vertexBuffers[ i ];
  23947. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  23948. const buffer = this.get( vertexBuffer ).buffer;
  23949. passEncoderGPU.setVertexBuffer( i, buffer );
  23950. currentSets.attributes[ i ] = vertexBuffer;
  23951. }
  23952. }
  23953. // occlusion queries - handle multiple consecutive draw calls for an object
  23954. if ( renderContextData.occlusionQuerySet !== undefined ) {
  23955. const lastObject = renderContextData.lastOcclusionObject;
  23956. if ( lastObject !== object ) {
  23957. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  23958. passEncoderGPU.endOcclusionQuery();
  23959. renderContextData.occlusionQueryIndex ++;
  23960. }
  23961. if ( object.occlusionTest === true ) {
  23962. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  23963. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  23964. }
  23965. renderContextData.lastOcclusionObject = object;
  23966. }
  23967. }
  23968. // draw
  23969. if ( object.isBatchedMesh === true ) {
  23970. const starts = object._multiDrawStarts;
  23971. const counts = object._multiDrawCounts;
  23972. const drawCount = object._multiDrawCount;
  23973. const drawInstances = object._multiDrawInstances;
  23974. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  23975. for ( let i = 0; i < drawCount; i ++ ) {
  23976. const count = drawInstances ? drawInstances[ i ] : 1;
  23977. const firstInstance = count > 1 ? 0 : i;
  23978. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  23979. }
  23980. } else if ( hasIndex === true ) {
  23981. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  23982. const indirect = renderObject.getIndirect();
  23983. if ( indirect !== null ) {
  23984. const buffer = this.get( indirect ).buffer;
  23985. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  23986. } else {
  23987. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  23988. }
  23989. info.update( object, indexCount, instanceCount );
  23990. } else {
  23991. const { vertexCount, instanceCount, firstVertex } = drawParams;
  23992. const indirect = renderObject.getIndirect();
  23993. if ( indirect !== null ) {
  23994. const buffer = this.get( indirect ).buffer;
  23995. passEncoderGPU.drawIndirect( buffer, 0 );
  23996. } else {
  23997. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  23998. }
  23999. info.update( object, vertexCount, instanceCount );
  24000. }
  24001. }
  24002. // cache key
  24003. needsRenderUpdate( renderObject ) {
  24004. const data = this.get( renderObject );
  24005. const { object, material } = renderObject;
  24006. const utils = this.utils;
  24007. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  24008. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  24009. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  24010. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  24011. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  24012. let needsUpdate = false;
  24013. if ( data.material !== material || data.materialVersion !== material.version ||
  24014. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  24015. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  24016. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  24017. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  24018. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  24019. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  24020. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  24021. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  24022. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  24023. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  24024. data.primitiveTopology !== primitiveTopology ||
  24025. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  24026. ) {
  24027. data.material = material; data.materialVersion = material.version;
  24028. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  24029. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  24030. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  24031. data.colorWrite = material.colorWrite;
  24032. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  24033. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  24034. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  24035. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  24036. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  24037. data.sampleCount = sampleCount;
  24038. data.colorSpace = colorSpace;
  24039. data.colorFormat = colorFormat;
  24040. data.depthStencilFormat = depthStencilFormat;
  24041. data.primitiveTopology = primitiveTopology;
  24042. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  24043. needsUpdate = true;
  24044. }
  24045. return needsUpdate;
  24046. }
  24047. getRenderCacheKey( renderObject ) {
  24048. const { object, material } = renderObject;
  24049. const utils = this.utils;
  24050. const renderContext = renderObject.context;
  24051. return [
  24052. material.transparent, material.blending, material.premultipliedAlpha,
  24053. material.blendSrc, material.blendDst, material.blendEquation,
  24054. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  24055. material.colorWrite,
  24056. material.depthWrite, material.depthTest, material.depthFunc,
  24057. material.stencilWrite, material.stencilFunc,
  24058. material.stencilFail, material.stencilZFail, material.stencilZPass,
  24059. material.stencilFuncMask, material.stencilWriteMask,
  24060. material.side,
  24061. utils.getSampleCountRenderContext( renderContext ),
  24062. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  24063. utils.getPrimitiveTopology( object, material ),
  24064. renderObject.getGeometryCacheKey(),
  24065. renderObject.clippingContextCacheKey
  24066. ].join();
  24067. }
  24068. // textures
  24069. createSampler( texture ) {
  24070. this.textureUtils.createSampler( texture );
  24071. }
  24072. destroySampler( texture ) {
  24073. this.textureUtils.destroySampler( texture );
  24074. }
  24075. createDefaultTexture( texture ) {
  24076. this.textureUtils.createDefaultTexture( texture );
  24077. }
  24078. createTexture( texture, options ) {
  24079. this.textureUtils.createTexture( texture, options );
  24080. }
  24081. updateTexture( texture, options ) {
  24082. this.textureUtils.updateTexture( texture, options );
  24083. }
  24084. generateMipmaps( texture ) {
  24085. this.textureUtils.generateMipmaps( texture );
  24086. }
  24087. destroyTexture( texture ) {
  24088. this.textureUtils.destroyTexture( texture );
  24089. }
  24090. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24091. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  24092. }
  24093. async initTimestampQuery( renderContext, descriptor ) {
  24094. if ( ! this.trackTimestamp ) return;
  24095. const renderContextData = this.get( renderContext );
  24096. if ( ! renderContextData.timeStampQuerySet ) {
  24097. // Push an error scope to catch any errors during query set creation
  24098. this.device.pushErrorScope( 'out-of-memory' );
  24099. const timeStampQuerySet = await this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_renderContext_${renderContext.id}` } );
  24100. // Pop the error scope and check for errors
  24101. const error = await this.device.popErrorScope();
  24102. if ( error ) {
  24103. if ( ! renderContextData.attemptingTimeStampQuerySetFailed ) {
  24104. console.error( `[GPUOutOfMemoryError][renderContext_${renderContext.id}]:\nFailed to create timestamp query set. This may be because timestamp queries are already running in other tabs.` );
  24105. renderContextData.attemptingTimeStampQuerySetFailed = true;
  24106. }
  24107. renderContextData.timeStampQuerySet = null; // Mark as unavailable
  24108. return;
  24109. }
  24110. const timestampWrites = {
  24111. querySet: timeStampQuerySet,
  24112. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  24113. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  24114. };
  24115. Object.assign( descriptor, { timestampWrites } );
  24116. renderContextData.timeStampQuerySet = timeStampQuerySet;
  24117. }
  24118. }
  24119. // timestamp utils
  24120. prepareTimestampBuffer( renderContext, encoder ) {
  24121. if ( ! this.trackTimestamp ) return;
  24122. const renderContextData = this.get( renderContext );
  24123. if ( ! renderContextData.timeStampQuerySet ) return;
  24124. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  24125. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  24126. renderContextData.currentTimestampQueryBuffers = {
  24127. resolveBuffer: this.device.createBuffer( {
  24128. label: 'timestamp resolve buffer',
  24129. size: size,
  24130. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  24131. } ),
  24132. resultBuffer: this.device.createBuffer( {
  24133. label: 'timestamp result buffer',
  24134. size: size,
  24135. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  24136. } ),
  24137. isMappingPending: false,
  24138. };
  24139. }
  24140. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  24141. if ( isMappingPending === true ) return;
  24142. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  24143. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  24144. }
  24145. async resolveTimestampAsync( renderContext, type = 'render' ) {
  24146. if ( ! this.trackTimestamp ) return;
  24147. const renderContextData = this.get( renderContext );
  24148. if ( ! renderContextData.timeStampQuerySet ) return;
  24149. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  24150. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  24151. if ( isMappingPending === true ) return;
  24152. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  24153. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  24154. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  24155. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  24156. this.renderer.info.updateTimestamp( type, duration );
  24157. resultBuffer.unmap();
  24158. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  24159. } );
  24160. }
  24161. // node builder
  24162. createNodeBuilder( object, renderer ) {
  24163. return new WGSLNodeBuilder( object, renderer );
  24164. }
  24165. // program
  24166. createProgram( program ) {
  24167. const programGPU = this.get( program );
  24168. programGPU.module = {
  24169. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  24170. entryPoint: 'main'
  24171. };
  24172. }
  24173. destroyProgram( program ) {
  24174. this.delete( program );
  24175. }
  24176. // pipelines
  24177. createRenderPipeline( renderObject, promises ) {
  24178. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  24179. }
  24180. createComputePipeline( computePipeline, bindings ) {
  24181. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  24182. }
  24183. beginBundle( renderContext ) {
  24184. const renderContextData = this.get( renderContext );
  24185. renderContextData._currentPass = renderContextData.currentPass;
  24186. renderContextData._currentSets = renderContextData.currentSets;
  24187. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24188. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  24189. }
  24190. finishBundle( renderContext, bundle ) {
  24191. const renderContextData = this.get( renderContext );
  24192. const bundleEncoder = renderContextData.currentPass;
  24193. const bundleGPU = bundleEncoder.finish();
  24194. this.get( bundle ).bundleGPU = bundleGPU;
  24195. // restore render pass state
  24196. renderContextData.currentSets = renderContextData._currentSets;
  24197. renderContextData.currentPass = renderContextData._currentPass;
  24198. }
  24199. addBundle( renderContext, bundle ) {
  24200. const renderContextData = this.get( renderContext );
  24201. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  24202. }
  24203. // bindings
  24204. createBindings( bindGroup, bindings, cacheIndex, version ) {
  24205. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24206. }
  24207. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  24208. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24209. }
  24210. updateBinding( binding ) {
  24211. this.bindingUtils.updateBinding( binding );
  24212. }
  24213. // attributes
  24214. createIndexAttribute( attribute ) {
  24215. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24216. }
  24217. createAttribute( attribute ) {
  24218. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24219. }
  24220. createStorageAttribute( attribute ) {
  24221. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24222. }
  24223. createIndirectStorageAttribute( attribute ) {
  24224. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24225. }
  24226. updateAttribute( attribute ) {
  24227. this.attributeUtils.updateAttribute( attribute );
  24228. }
  24229. destroyAttribute( attribute ) {
  24230. this.attributeUtils.destroyAttribute( attribute );
  24231. }
  24232. // canvas
  24233. updateSize() {
  24234. this.colorBuffer = this.textureUtils.getColorBuffer();
  24235. this.defaultRenderPassdescriptor = null;
  24236. }
  24237. // utils public
  24238. getMaxAnisotropy() {
  24239. return 16;
  24240. }
  24241. hasFeature( name ) {
  24242. return this.device.features.has( name );
  24243. }
  24244. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24245. let dstX = 0;
  24246. let dstY = 0;
  24247. let dstLayer = 0;
  24248. let srcX = 0;
  24249. let srcY = 0;
  24250. let srcLayer = 0;
  24251. let srcWidth = srcTexture.image.width;
  24252. let srcHeight = srcTexture.image.height;
  24253. if ( srcRegion !== null ) {
  24254. srcX = srcRegion.x;
  24255. srcY = srcRegion.y;
  24256. srcLayer = srcRegion.z || 0;
  24257. srcWidth = srcRegion.width;
  24258. srcHeight = srcRegion.height;
  24259. }
  24260. if ( dstPosition !== null ) {
  24261. dstX = dstPosition.x;
  24262. dstY = dstPosition.y;
  24263. dstLayer = dstPosition.z || 0;
  24264. }
  24265. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24266. const sourceGPU = this.get( srcTexture ).texture;
  24267. const destinationGPU = this.get( dstTexture ).texture;
  24268. encoder.copyTextureToTexture(
  24269. {
  24270. texture: sourceGPU,
  24271. mipLevel: level,
  24272. origin: { x: srcX, y: srcY, z: srcLayer }
  24273. },
  24274. {
  24275. texture: destinationGPU,
  24276. mipLevel: level,
  24277. origin: { x: dstX, y: dstY, z: dstLayer }
  24278. },
  24279. [
  24280. srcWidth,
  24281. srcHeight,
  24282. 1
  24283. ]
  24284. );
  24285. this.device.queue.submit( [ encoder.finish() ] );
  24286. }
  24287. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24288. const renderContextData = this.get( renderContext );
  24289. let sourceGPU = null;
  24290. if ( renderContext.renderTarget ) {
  24291. if ( texture.isDepthTexture ) {
  24292. sourceGPU = this.get( renderContext.depthTexture ).texture;
  24293. } else {
  24294. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  24295. }
  24296. } else {
  24297. if ( texture.isDepthTexture ) {
  24298. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  24299. } else {
  24300. sourceGPU = this.context.getCurrentTexture();
  24301. }
  24302. }
  24303. const destinationGPU = this.get( texture ).texture;
  24304. if ( sourceGPU.format !== destinationGPU.format ) {
  24305. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  24306. return;
  24307. }
  24308. let encoder;
  24309. if ( renderContextData.currentPass ) {
  24310. renderContextData.currentPass.end();
  24311. encoder = renderContextData.encoder;
  24312. } else {
  24313. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  24314. }
  24315. encoder.copyTextureToTexture(
  24316. {
  24317. texture: sourceGPU,
  24318. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  24319. },
  24320. {
  24321. texture: destinationGPU
  24322. },
  24323. [
  24324. rectangle.z,
  24325. rectangle.w
  24326. ]
  24327. );
  24328. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  24329. if ( renderContextData.currentPass ) {
  24330. const { descriptor } = renderContextData;
  24331. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  24332. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  24333. }
  24334. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24335. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24336. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  24337. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24338. } else {
  24339. this.device.queue.submit( [ encoder.finish() ] );
  24340. }
  24341. }
  24342. }
  24343. class IESSpotLight extends SpotLight {
  24344. constructor( color, intensity, distance, angle, penumbra, decay ) {
  24345. super( color, intensity, distance, angle, penumbra, decay );
  24346. this.iesMap = null;
  24347. }
  24348. copy( source, recursive ) {
  24349. super.copy( source, recursive );
  24350. this.iesMap = source.iesMap;
  24351. return this;
  24352. }
  24353. }
  24354. class StandardNodeLibrary extends NodeLibrary {
  24355. constructor() {
  24356. super();
  24357. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  24358. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  24359. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  24360. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  24361. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  24362. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  24363. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  24364. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  24365. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  24366. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  24367. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  24368. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  24369. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  24370. this.addLight( PointLightNode, PointLight );
  24371. this.addLight( DirectionalLightNode, DirectionalLight );
  24372. this.addLight( RectAreaLightNode, RectAreaLight );
  24373. this.addLight( SpotLightNode, SpotLight );
  24374. this.addLight( AmbientLightNode, AmbientLight );
  24375. this.addLight( HemisphereLightNode, HemisphereLight );
  24376. this.addLight( LightProbeNode, LightProbe );
  24377. this.addLight( IESSpotLightNode, IESSpotLight );
  24378. this.addToneMapping( linearToneMapping, LinearToneMapping );
  24379. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  24380. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  24381. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  24382. this.addToneMapping( agxToneMapping, AgXToneMapping );
  24383. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  24384. }
  24385. }
  24386. /*
  24387. const debugHandler = {
  24388. get: function ( target, name ) {
  24389. // Add |update
  24390. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  24391. return target[ name ];
  24392. }
  24393. };
  24394. */
  24395. class WebGPURenderer extends Renderer {
  24396. constructor( parameters = {} ) {
  24397. let BackendClass;
  24398. if ( parameters.forceWebGL ) {
  24399. BackendClass = WebGLBackend;
  24400. } else {
  24401. BackendClass = WebGPUBackend;
  24402. parameters.getFallback = () => {
  24403. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  24404. return new WebGLBackend( parameters );
  24405. };
  24406. }
  24407. const backend = new BackendClass( parameters );
  24408. //super( new Proxy( backend, debugHandler ) );
  24409. super( backend, parameters );
  24410. this.library = new StandardNodeLibrary();
  24411. this.isWebGPURenderer = true;
  24412. }
  24413. }
  24414. class BundleGroup extends Group {
  24415. constructor() {
  24416. super();
  24417. this.isBundleGroup = true;
  24418. this.type = 'BundleGroup';
  24419. this.static = true;
  24420. this.version = 0;
  24421. }
  24422. set needsUpdate( value ) {
  24423. if ( value === true ) this.version ++;
  24424. }
  24425. }
  24426. const _material = /*@__PURE__*/ new NodeMaterial();
  24427. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  24428. class PostProcessing {
  24429. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  24430. this.renderer = renderer;
  24431. this.outputNode = outputNode;
  24432. this.outputColorTransform = true;
  24433. this.needsUpdate = true;
  24434. _material.name = 'PostProcessing';
  24435. }
  24436. render() {
  24437. this.update();
  24438. const renderer = this.renderer;
  24439. const toneMapping = renderer.toneMapping;
  24440. const outputColorSpace = renderer.outputColorSpace;
  24441. renderer.toneMapping = NoToneMapping;
  24442. renderer.outputColorSpace = LinearSRGBColorSpace;
  24443. //
  24444. _quadMesh.render( renderer );
  24445. //
  24446. renderer.toneMapping = toneMapping;
  24447. renderer.outputColorSpace = outputColorSpace;
  24448. }
  24449. update() {
  24450. if ( this.needsUpdate === true ) {
  24451. const renderer = this.renderer;
  24452. const toneMapping = renderer.toneMapping;
  24453. const outputColorSpace = renderer.outputColorSpace;
  24454. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  24455. _quadMesh.material.needsUpdate = true;
  24456. this.needsUpdate = false;
  24457. }
  24458. }
  24459. async renderAsync() {
  24460. this.update();
  24461. const renderer = this.renderer;
  24462. const toneMapping = renderer.toneMapping;
  24463. const outputColorSpace = renderer.outputColorSpace;
  24464. renderer.toneMapping = NoToneMapping;
  24465. renderer.outputColorSpace = LinearSRGBColorSpace;
  24466. //
  24467. await _quadMesh.renderAsync( renderer );
  24468. //
  24469. renderer.toneMapping = toneMapping;
  24470. renderer.outputColorSpace = outputColorSpace;
  24471. }
  24472. }
  24473. // renderer state
  24474. function saveRendererState( renderer, state = {} ) {
  24475. state.toneMapping = renderer.toneMapping;
  24476. state.toneMappingExposure = renderer.toneMappingExposure;
  24477. state.outputColorSpace = renderer.outputColorSpace;
  24478. state.renderTarget = renderer.getRenderTarget();
  24479. state.activeCubeFace = renderer.getActiveCubeFace();
  24480. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24481. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24482. state.pixelRatio = renderer.getPixelRatio();
  24483. state.mrt = renderer.getMRT();
  24484. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24485. state.clearAlpha = renderer.getClearAlpha();
  24486. state.autoClear = renderer.autoClear;
  24487. state.scissorTest = renderer.getScissorTest();
  24488. return state;
  24489. }
  24490. function resetRendererState( renderer, state ) {
  24491. state = saveRendererState( renderer, state );
  24492. renderer.setMRT( null );
  24493. renderer.setRenderObjectFunction( null );
  24494. renderer.setClearColor( 0x000000, 1 );
  24495. renderer.autoClear = true;
  24496. return state;
  24497. }
  24498. function restoreRendererState( renderer, state ) {
  24499. renderer.toneMapping = state.toneMapping;
  24500. renderer.toneMappingExposure = state.toneMappingExposure;
  24501. renderer.outputColorSpace = state.outputColorSpace;
  24502. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24503. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24504. renderer.setPixelRatio( state.pixelRatio );
  24505. renderer.setMRT( state.mrt );
  24506. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24507. renderer.autoClear = state.autoClear;
  24508. renderer.setScissorTest( state.scissorTest );
  24509. }
  24510. // renderer and scene state
  24511. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24512. state = saveRendererState( renderer, state );
  24513. state.background = scene.background;
  24514. state.backgroundNode = scene.backgroundNode;
  24515. state.overrideMaterial = scene.overrideMaterial;
  24516. return state;
  24517. }
  24518. function resetRendererAndSceneState( renderer, scene, state ) {
  24519. state = saveRendererAndSceneState( renderer, scene, state );
  24520. scene.background = null;
  24521. scene.backgroundNode = null;
  24522. scene.overrideMaterial = null;
  24523. return state;
  24524. }
  24525. function restoreRendererAndSceneState( renderer, scene, state ) {
  24526. restoreRendererState( renderer, state );
  24527. scene.background = state.background;
  24528. scene.backgroundNode = state.backgroundNode;
  24529. scene.overrideMaterial = state.overrideMaterial;
  24530. }
  24531. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  24532. __proto__: null,
  24533. resetRendererAndSceneState: resetRendererAndSceneState,
  24534. resetRendererState: resetRendererState,
  24535. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24536. restoreRendererState: restoreRendererState,
  24537. saveRendererAndSceneState: saveRendererAndSceneState,
  24538. saveRendererState: saveRendererState
  24539. });
  24540. class StorageTexture extends Texture {
  24541. constructor( width = 1, height = 1 ) {
  24542. super();
  24543. this.image = { width, height };
  24544. this.magFilter = LinearFilter;
  24545. this.minFilter = LinearFilter;
  24546. this.isStorageTexture = true;
  24547. }
  24548. }
  24549. class StorageBufferAttribute extends BufferAttribute {
  24550. constructor( array, itemSize, typeClass = Float32Array ) {
  24551. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24552. super( array, itemSize );
  24553. this.isStorageBufferAttribute = true;
  24554. }
  24555. }
  24556. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24557. constructor( array, itemSize, typeClass = Float32Array ) {
  24558. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24559. super( array, itemSize );
  24560. this.isStorageInstancedBufferAttribute = true;
  24561. }
  24562. }
  24563. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  24564. constructor( array, itemSize ) {
  24565. super( array, itemSize, Uint32Array );
  24566. this.isIndirectStorageBufferAttribute = true;
  24567. }
  24568. }
  24569. class NodeLoader extends Loader {
  24570. constructor( manager ) {
  24571. super( manager );
  24572. this.textures = {};
  24573. this.nodes = {};
  24574. }
  24575. load( url, onLoad, onProgress, onError ) {
  24576. const loader = new FileLoader( this.manager );
  24577. loader.setPath( this.path );
  24578. loader.setRequestHeader( this.requestHeader );
  24579. loader.setWithCredentials( this.withCredentials );
  24580. loader.load( url, ( text ) => {
  24581. try {
  24582. onLoad( this.parse( JSON.parse( text ) ) );
  24583. } catch ( e ) {
  24584. if ( onError ) {
  24585. onError( e );
  24586. } else {
  24587. console.error( e );
  24588. }
  24589. this.manager.itemError( url );
  24590. }
  24591. }, onProgress, onError );
  24592. }
  24593. parseNodes( json ) {
  24594. const nodes = {};
  24595. if ( json !== undefined ) {
  24596. for ( const nodeJSON of json ) {
  24597. const { uuid, type } = nodeJSON;
  24598. nodes[ uuid ] = this.createNodeFromType( type );
  24599. nodes[ uuid ].uuid = uuid;
  24600. }
  24601. const meta = { nodes, textures: this.textures };
  24602. for ( const nodeJSON of json ) {
  24603. nodeJSON.meta = meta;
  24604. const node = nodes[ nodeJSON.uuid ];
  24605. node.deserialize( nodeJSON );
  24606. delete nodeJSON.meta;
  24607. }
  24608. }
  24609. return nodes;
  24610. }
  24611. parse( json ) {
  24612. const node = this.createNodeFromType( json.type );
  24613. node.uuid = json.uuid;
  24614. const nodes = this.parseNodes( json.nodes );
  24615. const meta = { nodes, textures: this.textures };
  24616. json.meta = meta;
  24617. node.deserialize( json );
  24618. delete json.meta;
  24619. return node;
  24620. }
  24621. setTextures( value ) {
  24622. this.textures = value;
  24623. return this;
  24624. }
  24625. setNodes( value ) {
  24626. this.nodes = value;
  24627. return this;
  24628. }
  24629. createNodeFromType( type ) {
  24630. if ( this.nodes[ type ] === undefined ) {
  24631. console.error( 'THREE.NodeLoader: Node type not found:', type );
  24632. return float();
  24633. }
  24634. return nodeObject( new this.nodes[ type ]() );
  24635. }
  24636. }
  24637. class NodeMaterialLoader extends MaterialLoader {
  24638. constructor( manager ) {
  24639. super( manager );
  24640. this.nodes = {};
  24641. this.nodeMaterials = {};
  24642. }
  24643. parse( json ) {
  24644. const material = super.parse( json );
  24645. const nodes = this.nodes;
  24646. const inputNodes = json.inputNodes;
  24647. for ( const property in inputNodes ) {
  24648. const uuid = inputNodes[ property ];
  24649. material[ property ] = nodes[ uuid ];
  24650. }
  24651. return material;
  24652. }
  24653. setNodes( value ) {
  24654. this.nodes = value;
  24655. return this;
  24656. }
  24657. setNodeMaterials( value ) {
  24658. this.nodeMaterials = value;
  24659. return this;
  24660. }
  24661. createMaterialFromType( type ) {
  24662. const materialClass = this.nodeMaterials[ type ];
  24663. if ( materialClass !== undefined ) {
  24664. return new materialClass();
  24665. }
  24666. return super.createMaterialFromType( type );
  24667. }
  24668. }
  24669. class NodeObjectLoader extends ObjectLoader {
  24670. constructor( manager ) {
  24671. super( manager );
  24672. this.nodes = {};
  24673. this.nodeMaterials = {};
  24674. this._nodesJSON = null;
  24675. }
  24676. setNodes( value ) {
  24677. this.nodes = value;
  24678. return this;
  24679. }
  24680. setNodeMaterials( value ) {
  24681. this.nodeMaterials = value;
  24682. return this;
  24683. }
  24684. parse( json, onLoad ) {
  24685. this._nodesJSON = json.nodes;
  24686. const data = super.parse( json, onLoad );
  24687. this._nodesJSON = null; // dispose
  24688. return data;
  24689. }
  24690. parseNodes( json, textures ) {
  24691. if ( json !== undefined ) {
  24692. const loader = new NodeLoader();
  24693. loader.setNodes( this.nodes );
  24694. loader.setTextures( textures );
  24695. return loader.parseNodes( json );
  24696. }
  24697. return {};
  24698. }
  24699. parseMaterials( json, textures ) {
  24700. const materials = {};
  24701. if ( json !== undefined ) {
  24702. const nodes = this.parseNodes( this._nodesJSON, textures );
  24703. const loader = new NodeMaterialLoader();
  24704. loader.setTextures( textures );
  24705. loader.setNodes( nodes );
  24706. loader.setNodeMaterials( this.nodeMaterials );
  24707. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24708. const data = json[ i ];
  24709. materials[ data.uuid ] = loader.parse( data );
  24710. }
  24711. }
  24712. return materials;
  24713. }
  24714. }
  24715. class ClippingGroup extends Group {
  24716. constructor() {
  24717. super();
  24718. this.isClippingGroup = true;
  24719. this.clippingPlanes = [];
  24720. this.enabled = true;
  24721. this.clipIntersection = false;
  24722. this.clipShadows = false;
  24723. }
  24724. }
  24725. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BRDF_GGX, BRDF_Lambert, BackSide, BasicEnvironmentNode, BasicShadowFilter, BasicShadowMap, BatchNode, BoxGeometry, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DFGApprox, D_GGX, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, Discard, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EPSILON, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, If, 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, Loop, 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, 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, PCFShadowFilter, PCFShadowMap, PCFSoftShadowFilter, PI, PI2, 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, Return, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableNodeResources, ScriptableValueNode, SetNode, ShaderNode, 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, TBNViewMatrix, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowFilter, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, backgroundRotation, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blendBurn, blendColor, blendDodge, blendOverlay, blendScreen, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertColorSpace, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getNormalFromDepth, getParallaxCorrectNormal, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, instancedMesh, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearToneMapping, localId, log, log2, logarithmicDepthToViewZ, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBTransferEOTF, sRGBTransferOETF, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToLogarithmicDepth, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号